diff --git a/third_party/spirv-tools/.gitignore b/third_party/spirv-tools/.gitignore index 22fb106d62..b2af56e92b 100644 --- a/third_party/spirv-tools/.gitignore +++ b/third_party/spirv-tools/.gitignore @@ -5,6 +5,8 @@ compile_commands.json /build/ /buildtools/ /external/googletest +/external/SPIRV-Headers +/external/spirv-headers /external/effcee /external/re2 /external/protobuf diff --git a/third_party/spirv-tools/Android.mk b/third_party/spirv-tools/Android.mk index 0b64ea6d6e..1bc844d400 100644 --- a/third_party/spirv-tools/Android.mk +++ b/third_party/spirv-tools/Android.mk @@ -93,7 +93,6 @@ SPVTOOLS_OPT_SRC_FILES := \ source/opt/dead_branch_elim_pass.cpp \ source/opt/dead_insert_elim_pass.cpp \ source/opt/dead_variable_elimination.cpp \ - source/opt/decompose_initialized_variables_pass.cpp \ source/opt/decoration_manager.cpp \ source/opt/debug_info_manager.cpp \ source/opt/def_use_manager.cpp \ @@ -112,7 +111,6 @@ SPVTOOLS_OPT_SRC_FILES := \ source/opt/fold_spec_constant_op_and_composite_pass.cpp \ source/opt/freeze_spec_constant_value_pass.cpp \ source/opt/function.cpp \ - source/opt/generate_webgpu_initializers_pass.cpp \ source/opt/graphics_robust_access_pass.cpp \ source/opt/if_conversion.cpp \ source/opt/inline_pass.cpp \ @@ -124,9 +122,9 @@ SPVTOOLS_OPT_SRC_FILES := \ source/opt/instruction.cpp \ source/opt/instruction_list.cpp \ source/opt/instrument_pass.cpp \ + source/opt/interp_fixup_pass.cpp \ source/opt/ir_context.cpp \ source/opt/ir_loader.cpp \ - source/opt/legalize_vector_shuffle_pass.cpp \ source/opt/licm_pass.cpp \ source/opt/local_access_chain_convert_pass.cpp \ source/opt/local_redundancy_elimination.cpp \ @@ -155,16 +153,15 @@ SPVTOOLS_OPT_SRC_FILES := \ source/opt/register_pressure.cpp \ source/opt/relax_float_ops_pass.cpp \ source/opt/remove_duplicates_pass.cpp \ + source/opt/remove_unused_interface_variables_pass.cpp \ source/opt/replace_invalid_opc.cpp \ source/opt/scalar_analysis.cpp \ source/opt/scalar_analysis_simplification.cpp \ source/opt/scalar_replacement_pass.cpp \ source/opt/set_spec_constant_default_value_pass.cpp \ source/opt/simplification_pass.cpp \ - source/opt/split_invalid_unreachable_pass.cpp \ source/opt/ssa_rewrite_pass.cpp \ source/opt/strength_reduction_pass.cpp \ - source/opt/strip_atomic_counter_memory_pass.cpp \ source/opt/strip_debug_info_pass.cpp \ source/opt/strip_reflect_info_pass.cpp \ source/opt/struct_cfg_analysis.cpp \ diff --git a/third_party/spirv-tools/BUILD.gn b/third_party/spirv-tools/BUILD.gn index 2387fc6ae8..996905a2d7 100644 --- a/third_party/spirv-tools/BUILD.gn +++ b/third_party/spirv-tools/BUILD.gn @@ -19,6 +19,7 @@ if (build_with_chromium) { } spirv_headers = spirv_tools_spirv_headers_dir +spirv_is_winuwp = is_win && target_os == "winuwp" template("spvtools_core_tables") { assert(defined(invoker.version), "Need version in $target_name generation.") @@ -32,13 +33,14 @@ template("spvtools_core_tables") { "${spirv_headers}/include/spirv/$version/spirv.core.grammar.json" core_insts_file = "${target_gen_dir}/core.insts-$version.inc" operand_kinds_file = "${target_gen_dir}/operand.kinds-$version.inc" - debuginfo_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" + debuginfo_insts_file = + "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" cldebuginfo100_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json" sources = [ + cldebuginfo100_insts_file, core_json_file, debuginfo_insts_file, - cldebuginfo100_insts_file, ] outputs = [ core_insts_file, @@ -69,7 +71,8 @@ template("spvtools_core_enums") { core_json_file = "${spirv_headers}/include/spirv/$version/spirv.core.grammar.json" - debuginfo_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" + debuginfo_insts_file = + "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" cldebuginfo100_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json" extension_enum_file = "${target_gen_dir}/extension_enum.inc" @@ -110,7 +113,8 @@ template("spvtools_glsl_tables") { core_json_file = "${spirv_headers}/include/spirv/$version/spirv.core.grammar.json" glsl_json_file = "${spirv_headers}/include/spirv/${version}/extinst.glsl.std.450.grammar.json" - debuginfo_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" + debuginfo_insts_file = + "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" cldebuginfo100_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json" glsl_insts_file = "${target_gen_dir}/glsl.std.450.insts.inc" @@ -133,9 +137,7 @@ template("spvtools_glsl_tables") { debuginfo_insts_file, cldebuginfo100_insts_file, ] - outputs = [ - glsl_insts_file, - ] + outputs = [ glsl_insts_file ] } } @@ -150,7 +152,8 @@ template("spvtools_opencl_tables") { core_json_file = "${spirv_headers}/include/spirv/$version/spirv.core.grammar.json" opencl_json_file = "${spirv_headers}/include/spirv/${version}/extinst.opencl.std.100.grammar.json" - debuginfo_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" + debuginfo_insts_file = + "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" cldebuginfo100_insts_file = "${spirv_headers}/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json" opencl_insts_file = "${target_gen_dir}/opencl.std.insts.inc" @@ -173,9 +176,7 @@ template("spvtools_opencl_tables") { debuginfo_insts_file, cldebuginfo100_insts_file, ] - outputs = [ - opencl_insts_file, - ] + outputs = [ opencl_insts_file ] } } @@ -194,12 +195,8 @@ template("spvtools_language_header") { "--extinst-output-path", rebase_path(extinst_output_path, root_build_dir), ] - inputs = [ - invoker.grammar_file, - ] - outputs = [ - "${extinst_output_path}", - ] + inputs = [ invoker.grammar_file ] + outputs = [ "${extinst_output_path}" ] } } @@ -210,7 +207,8 @@ template("spvtools_vendor_table") { script = "utils/generate_grammar_tables.py" name = invoker.name - extinst_vendor_grammar = "${spirv_headers}/include/spirv/unified1/extinst.${name}.grammar.json" + extinst_vendor_grammar = + "${spirv_headers}/include/spirv/unified1/extinst.${name}.grammar.json" extinst_file = "${target_gen_dir}/${name}.insts.inc" args = [ @@ -219,14 +217,10 @@ template("spvtools_vendor_table") { "--vendor-insts-output", rebase_path(extinst_file, root_build_dir), "--vendor-operand-kind-prefix", - invoker.operand_kind_prefix - ] - inputs = [ - extinst_vendor_grammar, - ] - outputs = [ - extinst_file, + invoker.operand_kind_prefix, ] + inputs = [ extinst_vendor_grammar ] + outputs = [ extinst_file ] } } @@ -237,12 +231,8 @@ action("spvtools_generators_inc") { xml_file = "${spirv_headers}/include/spirv/spir-v.xml" inc_file = "${target_gen_dir}/generators.inc" - sources = [ - xml_file, - ] - outputs = [ - inc_file, - ] + sources = [ xml_file ] + outputs = [ inc_file ] args = [ "--xml", rebase_path(xml_file, root_build_dir), @@ -257,9 +247,7 @@ action("spvtools_build_version") { src_dir = "." inc_file = "${target_gen_dir}/build-version.inc" - outputs = [ - inc_file, - ] + outputs = [ inc_file ] args = [ rebase_path(src_dir, root_build_dir), rebase_path(inc_file, root_build_dir), @@ -280,7 +268,8 @@ spvtools_opencl_tables("opencl1-0") { } spvtools_language_header("debuginfo") { name = "DebugInfo" - grammar_file = "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" + grammar_file = + "${spirv_headers}/include/spirv/unified1/extinst.debuginfo.grammar.json" } spvtools_language_header("cldebuginfo100") { name = "OpenCLDebugInfo100" @@ -288,13 +277,34 @@ spvtools_language_header("cldebuginfo100") { } spvtools_vendor_tables = [ - ["spv-amd-shader-explicit-vertex-parameter", "...nil..."], - ["spv-amd-shader-trinary-minmax", "...nil..."], - ["spv-amd-gcn-shader", "...nil..."], - ["spv-amd-shader-ballot", "...nil..."], - ["debuginfo", "...nil..."], - ["opencl.debuginfo.100", "CLDEBUG100_"], - ["nonsemantic.clspvreflection", "...nil..."], + [ + "spv-amd-shader-explicit-vertex-parameter", + "...nil...", + ], + [ + "spv-amd-shader-trinary-minmax", + "...nil...", + ], + [ + "spv-amd-gcn-shader", + "...nil...", + ], + [ + "spv-amd-shader-ballot", + "...nil...", + ], + [ + "debuginfo", + "...nil...", + ], + [ + "opencl.debuginfo.100", + "CLDEBUG100_", + ], + [ + "nonsemantic.clspvreflection", + "...nil...", + ], ] foreach(table_def, spvtools_vendor_tables) { @@ -317,11 +327,15 @@ config("spvtools_internal_config") { configs = [ ":spvtools_public_config" ] + cflags = [] if (is_clang) { - cflags = [ + cflags += [ "-Wno-implicit-fallthrough", "-Wno-newline-eof", ] + } else if (!is_win) { + # Work around a false-positive on a Skia GCC 10 builder. + cflags += [ "-Wno-format-truncation" ] } } @@ -342,8 +356,8 @@ static_library("spvtools") { ":spvtools_core_tables_unified1", ":spvtools_generators_inc", ":spvtools_glsl_tables_glsl1-0", - ":spvtools_language_header_debuginfo", ":spvtools_language_header_cldebuginfo100", + ":spvtools_language_header_debuginfo", ":spvtools_opencl_tables_opencl1-0", ] foreach(table_def, spvtools_vendor_tables) { @@ -486,9 +500,7 @@ static_library("spvtools_val") { ":spvtools_language_header_cldebuginfo100", ":spvtools_language_header_debuginfo", ] - public_deps = [ - ":spvtools_headers", - ] + public_deps = [ ":spvtools_headers" ] if (build_with_chromium) { configs -= [ "//build/config/compiler:chromium_code" ] @@ -539,12 +551,10 @@ static_library("spvtools_opt") { "source/opt/dead_insert_elim_pass.h", "source/opt/dead_variable_elimination.cpp", "source/opt/dead_variable_elimination.h", - "source/opt/decompose_initialized_variables_pass.cpp", - "source/opt/decompose_initialized_variables_pass.h", - "source/opt/decoration_manager.cpp", - "source/opt/decoration_manager.h", "source/opt/debug_info_manager.cpp", "source/opt/debug_info_manager.h", + "source/opt/decoration_manager.cpp", + "source/opt/decoration_manager.h", "source/opt/def_use_manager.cpp", "source/opt/def_use_manager.h", "source/opt/desc_sroa.cpp", @@ -578,8 +588,6 @@ static_library("spvtools_opt") { "source/opt/freeze_spec_constant_value_pass.h", "source/opt/function.cpp", "source/opt/function.h", - "source/opt/generate_webgpu_initializers_pass.cpp", - "source/opt/generate_webgpu_initializers_pass.h", "source/opt/graphics_robust_access_pass.cpp", "source/opt/graphics_robust_access_pass.h", "source/opt/if_conversion.cpp", @@ -602,14 +610,14 @@ static_library("spvtools_opt") { "source/opt/instruction_list.h", "source/opt/instrument_pass.cpp", "source/opt/instrument_pass.h", + "source/opt/interp_fixup_pass.cpp", + "source/opt/interp_fixup_pass.h", "source/opt/ir_builder.h", "source/opt/ir_context.cpp", "source/opt/ir_context.h", "source/opt/ir_loader.cpp", "source/opt/ir_loader.h", "source/opt/iterator.h", - "source/opt/legalize_vector_shuffle_pass.cpp", - "source/opt/legalize_vector_shuffle_pass.h", "source/opt/licm_pass.cpp", "source/opt/licm_pass.h", "source/opt/local_access_chain_convert_pass.cpp", @@ -668,6 +676,8 @@ static_library("spvtools_opt") { "source/opt/relax_float_ops_pass.h", "source/opt/remove_duplicates_pass.cpp", "source/opt/remove_duplicates_pass.h", + "source/opt/remove_unused_interface_variables_pass.cpp", + "source/opt/remove_unused_interface_variables_pass.h", "source/opt/replace_invalid_opc.cpp", "source/opt/replace_invalid_opc.h", "source/opt/scalar_analysis.cpp", @@ -680,14 +690,10 @@ static_library("spvtools_opt") { "source/opt/set_spec_constant_default_value_pass.h", "source/opt/simplification_pass.cpp", "source/opt/simplification_pass.h", - "source/opt/split_invalid_unreachable_pass.cpp", - "source/opt/split_invalid_unreachable_pass.h", "source/opt/ssa_rewrite_pass.cpp", "source/opt/ssa_rewrite_pass.h", "source/opt/strength_reduction_pass.cpp", "source/opt/strength_reduction_pass.h", - "source/opt/strip_atomic_counter_memory_pass.cpp", - "source/opt/strip_atomic_counter_memory_pass.h", "source/opt/strip_debug_info_pass.cpp", "source/opt/strip_debug_info_pass.h", "source/opt/strip_reflect_info_pass.cpp", @@ -719,9 +725,7 @@ static_library("spvtools_opt") { ":spvtools_language_header_debuginfo", ":spvtools_vendor_tables_spv-amd-shader-ballot", ] - public_deps = [ - ":spvtools_headers", - ] + public_deps = [ ":spvtools_headers" ] if (build_with_chromium) { configs -= [ "//build/config/compiler:chromium_code" ] @@ -731,17 +735,13 @@ static_library("spvtools_opt") { } static_library("spvtools_link") { - sources = [ - "source/link/linker.cpp", - ] + sources = [ "source/link/linker.cpp" ] deps = [ ":spvtools", ":spvtools_opt", ":spvtools_val", ] - public_deps = [ - ":spvtools_headers", - ] + public_deps = [ ":spvtools_headers" ] if (build_with_chromium) { configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code" ] @@ -803,6 +803,10 @@ static_library("spvtools_reduce") { "source/reduce/simple_conditional_branch_to_branch_opportunity_finder.h", "source/reduce/simple_conditional_branch_to_branch_reduction_opportunity.cpp", "source/reduce/simple_conditional_branch_to_branch_reduction_opportunity.h", + "source/reduce/structured_construct_to_block_reduction_opportunity.cpp", + "source/reduce/structured_construct_to_block_reduction_opportunity.h", + "source/reduce/structured_construct_to_block_reduction_opportunity_finder.cpp", + "source/reduce/structured_construct_to_block_reduction_opportunity_finder.h", "source/reduce/structured_loop_to_selection_reduction_opportunity.cpp", "source/reduce/structured_loop_to_selection_reduction_opportunity.h", "source/reduce/structured_loop_to_selection_reduction_opportunity_finder.cpp", @@ -814,9 +818,7 @@ static_library("spvtools_reduce") { ":spvtools", ":spvtools_opt", ] - public_deps = [ - ":spvtools_headers", - ] + public_deps = [ ":spvtools_headers" ] if (build_with_chromium) { configs -= [ "//build/config/compiler:chromium_code" ] configs += [ "//build/config/compiler:no_chromium_code" ] @@ -851,10 +853,10 @@ if (build_with_chromium) { "test/comment_test.cpp", "test/enum_set_test.cpp", "test/enum_string_mapping_test.cpp", + "test/ext_inst.cldebug100_test.cpp", "test/ext_inst.debuginfo_test.cpp", "test/ext_inst.glsl_test.cpp", "test/ext_inst.opencl_test.cpp", - "test/ext_inst.cldebug100_test.cpp", "test/fix_word_test.cpp", "test/generator_magic_number_test.cpp", "test/hex_float_test.cpp", @@ -901,8 +903,8 @@ if (build_with_chromium) { deps = [ ":spvtools", - ":spvtools_language_header_debuginfo", ":spvtools_language_header_cldebuginfo100", + ":spvtools_language_header_debuginfo", ":spvtools_val", "//testing/gmock", "//testing/gtest", @@ -922,9 +924,7 @@ if (build_with_chromium) { if (spirv_tools_standalone) { group("fuzzers") { testonly = true - deps = [ - "test/fuzzers", - ] + deps = [ "test/fuzzers" ] } } @@ -933,16 +933,12 @@ source_set("spvtools_util_cli_consumer") { "tools/util/cli_consumer.cpp", "tools/util/cli_consumer.h", ] - deps = [ - ":spvtools_headers", - ] + deps = [ ":spvtools_headers" ] configs += [ ":spvtools_internal_config" ] } source_set("spvtools_software_version") { - sources = [ - "source/software_version.cpp", - ] + sources = [ "source/software_version.cpp" ] deps = [ ":spvtools_build_version", ":spvtools_headers", @@ -951,9 +947,7 @@ source_set("spvtools_software_version") { } executable("spirv-as") { - sources = [ - "tools/as/as.cpp", - ] + sources = [ "tools/as/as.cpp" ] deps = [ ":spvtools", ":spvtools_software_version", @@ -962,9 +956,7 @@ executable("spirv-as") { } executable("spirv-dis") { - sources = [ - "tools/dis/dis.cpp", - ] + sources = [ "tools/dis/dis.cpp" ] deps = [ ":spvtools", ":spvtools_software_version", @@ -973,9 +965,7 @@ executable("spirv-dis") { } executable("spirv-val") { - sources = [ - "tools/val/val.cpp", - ] + sources = [ "tools/val/val.cpp" ] deps = [ ":spvtools", ":spvtools_software_version", @@ -999,9 +989,7 @@ executable("spirv-cfg") { } executable("spirv-opt") { - sources = [ - "tools/opt/opt.cpp", - ] + sources = [ "tools/opt/opt.cpp" ] deps = [ ":spvtools", ":spvtools_opt", @@ -1013,9 +1001,7 @@ executable("spirv-opt") { } executable("spirv-link") { - sources = [ - "tools/link/linker.cpp", - ] + sources = [ "tools/link/linker.cpp" ] deps = [ ":spvtools", ":spvtools_link", @@ -1026,12 +1012,10 @@ executable("spirv-link") { configs += [ ":spvtools_internal_config" ] } -if (!is_ios) { - # iOS does not allow std::system calls which spirv-reduce requires +if (!is_ios && !spirv_is_winuwp) { + # iOS and UWP do not allow std::system calls which spirv-reduce requires executable("spirv-reduce") { - sources = [ - "tools/reduce/reduce.cpp", - ] + sources = [ "tools/reduce/reduce.cpp" ] deps = [ ":spvtools", ":spvtools_opt", @@ -1053,7 +1037,7 @@ group("all_spirv_tools") { ":spirv-opt", ":spirv-val", ] - if (!is_ios) { + if (!is_ios && !spirv_is_winuwp) { deps += [ ":spirv-reduce" ] } } diff --git a/third_party/spirv-tools/CHANGES b/third_party/spirv-tools/CHANGES index 3c81249df8..467655ccfe 100644 --- a/third_party/spirv-tools/CHANGES +++ b/third_party/spirv-tools/CHANGES @@ -1,7 +1,181 @@ Revision history for SPIRV-Tools -v2020.6 2020-09-24 - - Start SPIRV-Tools v2020.6 +v2021.3-dev 2021-06-22 + - Start v2021.3-dev + +v2021.2 2021-06-18 + - General + - Support SPV_KHR_subgroup_uniform_control_flow (#4318) + - Support Intel extensions for fixed point and hls-float (#4321) + - Fix crash when optimizing shaders with DebugPrintf (#4280) + + - Validator + - Support Vulkan Storage Class for Execution Model (#4212) + + - Optimizer + - Handle SPV_KHR_vulkan_memory_model in dead-code elimination (#4320) + - Support folding OpBitcast with numeric constants (#4247) + + - Fuzz + - Add tests for MaybeGet* functions in fuzzerutil (#4284) + - Fix OutlineFunction in presence of unreachable blocks (#4308) + - Fix def-use update in PermutePhiOperands (#4309) + - Swap positions of two functions in a module (#4236) + +v2021.1 2021-04-19 + - General + - Support SPV_KHR_linkonce_odr, SPV_KHR_expect_assume (#4161) + - Fixes for the vscode language server extension (#4150) + - Validator + - Add validation for SPV_EXT_shader_atomic_float_min_max (#4105) + - Add Vulkan Execution Scope checks (#4183) + - Vulkan 64-bit OpAtomicStore check (#4163) + - Optimizer + - Add interpolate legalization pass (#4220) + - Fuzz + - Various performance optimizations + - Do not add too many dead blocks (#4217) + - Add WGSL compatibility flag to context (#4193) + - Add persistent state to the fuzzer (#4137) + +v2020.7 2021-02-16 + - General + - Support pending Intel extensions (#4116) + - Remove WebGPU support (#4108) + - Validator + - Vulkan image gather constant component (#4133) + - Add Vulkan PSB64 convert VUID (#4122) + - Validate SPV_KHR_workgroup_memory_explicit_layout (#4128) + - Validate VK_KHR_zero_initialize_workgroup_memory (#4124) + - Add Vulkan image gather offset VUID (#4118) + - Label Vulkan atomic semantics VUIDs (#4120) + - Label VUID 04662 (#4123) + - Label VUID 04683 (#4121) + - Add Vulkan EXT builtins (#4115) + - Validate Sampled=1 for Vulkan ImageQuerySizeLod, ImageQueryLevels, ImageQueryLod (#4103) + - Add Vulkan Memory Scope VUs (#4106) + - Add Vulkan Addressing Model check (#4107) + - Vulkan atomic storage class (#4079) + - Label standalone Vulkan VUID (#4091) + - Add Vulkan decroation VUID (#4090) + - Add Vulkan FP Mode VUID (#4088) + - Fix Vulkan image sampled check (#4085) + - Add Vulkan ForwardPointer VUID (#4089) + - Add Vulkan ImageTexelPointer format check (#4087) + - Add Vulkan Group Operation VUID (#4086) + - Add first StandAlone VUID 04633 (#4077) + - Add Subgroup VUIDs (#4074) + - validate return type of OpImageRead (#4072) + - tighter validation of multisampled images (#4059) + - validate OpTypeImage Sampled values for environemnts (#4064) + - validate StorageImageMultisampled capability (#4062) + - Add last TessLevelOuter and TessLevelInner VUID (#4055) + - Add last ClipDistance and CullDistance VUID (#4054) + - Add last ViewportIndex and Layer VUID (#4053) + - Add last Position VUID (#4052) + - Allow forward pointer to be used in types generally (#4044) + - Optimizer + - Mark module as modified if convert-to-half removes decorations (#4127) + - Fix binding number calculation in desc sroa (#4095) + - Run DCE when SPV_KHR_shader_clock is used (#4049) + - Debug Info + - Set correct scope and line info for DebugValue (#4125) + - Avoid integrity check failures caused by propagating line instructions (#4096) + - Linker + - Linker usability improvements (#4084) + - Instrumentation + - Generate differentiated error codes for buffer oob checking (#4097) + - Fuzz + - Fix OpPhi handling in DuplicateRegionWithSelection (#4065) + +v2020.6 2020-12-07 + - General + CMake: Add SPIRV_TOOLS_BUILD_STATIC flag (#3910) + - Disassembler + Add some context comments to disassembly. (#3847) + - Optimizer + - Take new (raytracing) termination instructions into account. (#4050) + - Do run DCE if SPV_KHR_ray_query is used. (#4047) + - Handle 8-bit index in elim dead member (#4043) + - Add texel buffer out-of-bounds checking instrumentation (#4038) + - Update MeshShadingNV dependencies (and land Ray tracing updates) (#4028) + - Fix buffer oob instrumentation for matrix refs (#4025) + - Fix SSA re-writing in the presence of variable pointers. (#4010) + - Add support to prevent functions from being inlined if they have + DontInline flag (#3858) + - Add SPV_EXT_shader_image_int64 (#3852) + - Support SPV_KHR_fragment_shading_rate (#3943) + - Fix use-after-move in val/validate.cpp (#3848) + - Debug Info + - properly preserve DebugValue indexes operand (#4022) + - Add DebugValue for invisible store in single_store_elim (#4002) + - Propagate OpLine to all applied instructions in spirv-opt (#3951) + - Add DebugValue for DebugDecl invisible to value assignment (#3973) + - Add DebugValue for function param regardless of scope (#3923) + - Debug info preservation in convert-local-access-chains pass (#3835) + - Debug info preservation in redundancy-elimination pass (#3839) + - Debug info preservation in if-conversion pass (#3861) + - Validator + - Add validation support for the ray tracing built-in variables (#4041) + - Use less stack space when validating Vulkan builtins (#4019) + - Fix SPV_KHR_fragment_shading_rate VUID label (#4014) + - Label Layer and ViewportIndex VUIDs (#4013) + - Allow the ViewportIndex and Layer built-ins on SPIR-V 1.5 (#3986) + - Fix validation of OpPhi instructions (#3919) + - Fuzz + - Fix facts arising from CompositeConstruct (#4034) + - Do not flatten conditionals that create synonyms (#4030) + - Add support for reining in rogue fuzzer passes (#3987) + - Fix assertion failure in FuzzerPassAddCompositeExtract (#3995) + - Fix invalid equation facts (#4009) + - Fix bugs in TransformationFlattenConditionalBranch (#4006) + - Fix bug related to transformation applicability (#3990) + - Add expand vector reduction transformation (#3869) + - Add FuzzerPassAddCompositeExtract (#3904) + - Fix mismatch with shrinker step limit (#3985) + - Fix off-by-one error in replayer (#3982) + - Get order right for OpSelect arguments (#3974) + - Do not add synonym-creating loops in dead blocks (#3975) + - Skip OpTypeSampledImage when propagating up (#3976) + - Pass OpUndef in function call if needed (#3978) + - Fix off-by-one in TransformationCompositeConstruct (#3979) + - Tolerate absent ids in data synonym fact management (#3966) + - Fix to id availability (#3971) + - Fix operand types (#3962) + - Don't flatten conditional if condition is irrelevant (#3944) + - Do not produce OpPhis of type OpTypeSampledImage (#3964) + - Restrict fuzzer pass to reachable blocks (#3970) + - Handle more types when extending OpPhi instructions (#3969) + - Skip early terminator wrappers when merging returns (#3968) + - Avoid irrelevant constants in synonym-creating loops (#3967) + - Skip dead blocks in FuzzerPassAddOpPhiSynonyms (#3965) + - Avoid the type manager when looking for struct types (#3963) + - Fix to TransformationDuplicateRegionWithSelection (#3941) + - Skip OpFunction when replacing irrelevant ids (#3932) + - Use component-wise selectors when flattening conditional branches (#3921) + - Avoid void struct member when outlining functions (#3936) + - Do not allow Block-decorated structs when adding parameters (#3931) + - Fix to operand id type (#3937) + - Handle dead blocks in TransformationEquationInstruction (#3933) + - Do not allow sampled image load when flattening conditionals (#3930) + - Take care of OpPhi instructions when inlining (#3939) + - Fix to TransformationInlineFunction (#3913) + - Wrap early terminators before merging returns (#3925) + - Lower probability of adding bit instruction synonyms (#3917) + - Fix handling of OpPhi in FlattenConditionalBranch (#3916) + - Avoid creating blocks without parents (#3908) + - Do not allow creation of constants of block-decorated structs (#3903) + - Fixes related to irrelevant ids (#3901) + - Fix to transformation that adds a synonym via a loop (#3898) + - Fix to duplicate region with selection (#3896) + - Do not expose synonym facts for non-existent ids (#3891) + - Do not add synonyms involving irrelevant ids (#3890) + - Do not replace irrelevant ids that are not in blocks (#3892) + - Wrap OpKill and similar in function calls (#3884) + - Integrate spirv-reduce with shrinker (#3849) + - Report fresh ids in transformations (#3856) + - Support OpNot bit instruction case (#3841) + - Return IR and transformation context after replay (#3846) v2020.5 2020-09-22 - General diff --git a/third_party/spirv-tools/CMakeLists.txt b/third_party/spirv-tools/CMakeLists.txt index 41ae7897ca..5530f8c4f3 100755 --- a/third_party/spirv-tools/CMakeLists.txt +++ b/third_party/spirv-tools/CMakeLists.txt @@ -59,6 +59,8 @@ elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") add_definitions(-DSPIRV_MAC) elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "iOS") add_definitions(-DSPIRV_IOS) +elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "tvOS") + add_definitions(-DSPIRV_TVOS) elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Android") add_definitions(-DSPIRV_ANDROID) set(SPIRV_TIMER_ENABLED ${SPIRV_ALLOW_TIMERS}) diff --git a/third_party/spirv-tools/DEPS b/third_party/spirv-tools/DEPS index ef3ee5da5c..718927d040 100644 --- a/third_party/spirv-tools/DEPS +++ b/third_party/spirv-tools/DEPS @@ -4,9 +4,9 @@ vars = { 'github': 'https://github.com', 'effcee_revision': '2ec8f8738118cc483b67c04a759fee53496c5659', - 'googletest_revision': '3af06fe1664d30f98de1e78c53a7087e842a2547', - 're2_revision': 'ca11026a032ce2a3de4b3c389ee53d2bdc8794d6', - 'spirv_headers_revision': '05836bdba63e7debce9fa9feaed42f20cd43af9d', + 'googletest_revision': 'b7d472f1225c5a64943821d8483fecb469d3f382', + 're2_revision': 'f8e389f3acdc2517562924239e2a188037393683', + 'spirv_headers_revision': 'ddf3230c14c71e81fc0eae9b781cc4bcc2d1f0f5', } deps = { diff --git a/third_party/spirv-tools/FILAMENT_README.md b/third_party/spirv-tools/FILAMENT_README.md deleted file mode 100644 index 23bb8a02bf..0000000000 --- a/third_party/spirv-tools/FILAMENT_README.md +++ /dev/null @@ -1,30 +0,0 @@ -When updating spirv-tools to a new version, make sure to preserve all the changes marked with -the following in `CMakeLists.txt` and `source/CMakeLists.txt`: - -`# Filament specific changes` - -You can easily apply these changes by running the following command at Filament's root: - -``` -git apply third_party/spirv-tools/filament-specific-changes.patch -``` - -The following procedure can be used to update spirv-tools. Note that there is a secondary repository -that needs to be downloaded (spirv-headers). - -``` -curl -L https://github.com/KhronosGroup/spirv-tools/archive/master.zip > master.zip -unzip master.zip -rsync -r SPIRV-Tools-master/ spirv-tools/ --delete -rm -rf SPIRV-Tools-master master.zip -curl -L https://github.com/KhronosGroup/spirv-headers/archive/master.zip > master.zip -unzip master.zip -mv SPIRV-Headers-master/ spirv-tools/external/spirv-headers -rm master.zip - -git add spirv-tools -``` - -Edit the .gitignore so it doesn't prevent `spirv-headers` from being committed. - -Finally, remember to bring back the Filament-specific changes in CMakeLists. diff --git a/third_party/spirv-tools/README.md b/third_party/spirv-tools/README.md index 44f582fb8a..3637305bae 100644 --- a/third_party/spirv-tools/README.md +++ b/third_party/spirv-tools/README.md @@ -136,7 +136,6 @@ As of this writing, there are 67 transforms including examples such as: * Loop-invariant code motion * Loop unroll * Other - * Generate WebGPU initializers * Graphics robust access * Upgrade memory model to VulkanKHR diff --git a/third_party/spirv-tools/android_test/jni/Application.mk b/third_party/spirv-tools/android_test/jni/Application.mk index d7ccd349ad..4e66465931 100644 --- a/third_party/spirv-tools/android_test/jni/Application.mk +++ b/third_party/spirv-tools/android_test/jni/Application.mk @@ -1,5 +1,5 @@ APP_ABI := all APP_BUILD_SCRIPT := Android.mk -APP_STL := gnustl_static +APP_STL := c++_static APP_PLATFORM := android-9 NDK_TOOLCHAIN_VERSION := 4.9 diff --git a/third_party/spirv-tools/build_overrides/build.gni b/third_party/spirv-tools/build_overrides/build.gni index 833fcd3497..cf3d6b794b 100644 --- a/third_party/spirv-tools/build_overrides/build.gni +++ b/third_party/spirv-tools/build_overrides/build.gni @@ -16,9 +16,6 @@ # Chromium specific targets in a client project's GN file etc. build_with_chromium = false -# Don't use Chromium's third_party/binutils. -linux_use_bundled_binutils_override = false - declare_args() { # Android 32-bit non-component, non-clang builds cannot have symbol_level=2 # due to 4GiB file size limit, see https://crbug.com/648948. diff --git a/third_party/spirv-tools/docs/spirv-fuzz.md b/third_party/spirv-tools/docs/spirv-fuzz.md index e5439e3cb9..5716b35ead 100644 --- a/third_party/spirv-tools/docs/spirv-fuzz.md +++ b/third_party/spirv-tools/docs/spirv-fuzz.md @@ -53,7 +53,7 @@ See `transformation_set_selection_control.h` for an example. The `IsApplicable` method should have a comment in the header file describing the conditions for applicability in simple terms. These conditions should be implemented in the body of this method in the `.cpp` file. -In the case of `TransformationSetSelectionControl`, `IsApplicable` involves checking that `block_id` is indeed the id of a block that has an `OpSelectoinMerge` instruction, and that `selection_control` is a valid selection mask. +In the case of `TransformationSetSelectionControl`, `IsApplicable` involves checking that `block_id` is indeed the id of a block that has an `OpSelectionMerge` instruction, and that `selection_control` is a valid selection mask. The `Apply` method should have a comment in the header file summarising the result of applying the transformation. It should be implemented in the `.cpp` file, and you should assume that `IsApplicable` holds whenever `Apply` is invoked. diff --git a/third_party/spirv-tools/external/spirv-headers/CMakeLists.txt b/third_party/spirv-tools/external/spirv-headers/CMakeLists.txt index d3940532d1..ef2e566067 100644 --- a/third_party/spirv-tools/external/spirv-headers/CMakeLists.txt +++ b/third_party/spirv-tools/external/spirv-headers/CMakeLists.txt @@ -79,7 +79,7 @@ target_include_directories(${PROJECT_NAME} INTERFACE if (SPIRV_HEADERS_ENABLE_INSTALL) message(STATUS "Installing SPIRV-Header") - set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}") + set(config_install_dir "${CMAKE_INSTALL_DATADIR}/cmake/${PROJECT_NAME}") set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") diff --git a/third_party/spirv-tools/external/spirv-headers/README.md b/third_party/spirv-tools/external/spirv-headers/README.md index b1aa964552..8c7039f7d1 100644 --- a/third_party/spirv-tools/external/spirv-headers/README.md +++ b/third_party/spirv-tools/external/spirv-headers/README.md @@ -140,10 +140,21 @@ and can be used to test a PR, or even to include the results in the PR. This is not required though. The header-generation project is under the `tools/buildHeaders` directory. -Use CMake to build the project, in a `build` subdirectory (under `tools/buildHeaders`). +Use CMake to build and install the project, in a `build` subdirectory (under `tools/buildHeaders`). There is then a bash script at `bin/makeHeaders` that shows how to use the built header-generator binary to generate the headers from the JSON grammar. (Execute `bin/makeHeaders` from the `tools/buildHeaders` directory.) +Here's a complete example: + +``` +cd tools/buildHeaders +mkdir build +cd build +cmake .. +cmake --build . --target install +cd .. +./bin/makeHeaders +``` Notes: - this generator is used in a broader context within Khronos to generate the specification, diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/spir-v.xml b/third_party/spirv-tools/external/spirv-headers/include/spirv/spir-v.xml index d1ebaab589..75cba89a74 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/spir-v.xml +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/spir-v.xml @@ -78,7 +78,10 @@ - + + + + @@ -128,13 +131,15 @@ + + - + @@ -154,13 +159,15 @@ + + - + @@ -180,11 +187,32 @@ - - + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/DebugInfo.h b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/DebugInfo.h index c50a1318b1..4657556bf0 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/DebugInfo.h +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/DebugInfo.h @@ -78,6 +78,7 @@ enum DebugInfoInstructions { enum DebugInfoDebugInfoFlags { + DebugInfoNone = 0x0000, DebugInfoFlagIsProtected = 0x01, DebugInfoFlagIsPrivate = 0x02, DebugInfoFlagIsPublic = 0x03, diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/OpenCLDebugInfo100.h b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/OpenCLDebugInfo100.h index 1149980ffb..e3847c902b 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/OpenCLDebugInfo100.h +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/OpenCLDebugInfo100.h @@ -75,11 +75,13 @@ enum OpenCLDebugInfo100Instructions { OpenCLDebugInfo100DebugMacroUndef = 33, OpenCLDebugInfo100DebugImportedEntity = 34, OpenCLDebugInfo100DebugSource = 35, + OpenCLDebugInfo100DebugModuleINTEL = 36, OpenCLDebugInfo100InstructionsMax = 0x7fffffff }; enum OpenCLDebugInfo100DebugInfoFlags { + OpenCLDebugInfo100None = 0x0000, OpenCLDebugInfo100FlagIsProtected = 0x01, OpenCLDebugInfo100FlagIsPrivate = 0x02, OpenCLDebugInfo100FlagIsPublic = 0x03, diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.debuginfo.grammar.json b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.debuginfo.grammar.json index 9212f6f48c..7d6e8e5b31 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.debuginfo.grammar.json +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.debuginfo.grammar.json @@ -376,6 +376,10 @@ "category" : "BitEnum", "kind" : "DebugInfoFlags", "enumerants" : [ + { + "enumerant" : "None", + "value" : "0x0000" + }, { "enumerant" : "FlagIsProtected", "value" : "0x01" diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json index 08062be4f6..699fe40369 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json @@ -395,6 +395,21 @@ { "kind" : "IdRef", "name" : "'File'" }, { "kind" : "IdRef", "name" : "'Text'", "quantifier" : "?" } ] + }, + { + "opname" : "DebugModuleINTEL", + "opcode" : 36, + "operands" : [ + { "kind" : "IdRef", "name" : "'Name'" }, + { "kind" : "IdRef", "name" : "'Source'" }, + { "kind" : "IdRef", "name" : "'Parent'" }, + { "kind" : "LiteralInteger", "name" : "'Line'" }, + { "kind" : "IdRef", "name" : "'ConfigurationMacros'" }, + { "kind" : "IdRef", "name" : "'IncludePath'" }, + { "kind" : "IdRef", "name" : "'APINotesFile'" }, + { "kind" : "LiteralInteger", "name" : "'IsDeclaration'" } + ], + "capability" : "DebugInfoModuleINTEL" } ], "operand_kinds" : [ @@ -402,6 +417,10 @@ "category" : "BitEnum", "kind" : "DebugInfoFlags", "enumerants" : [ + { + "enumerant" : "None", + "value" : "0x0000" + }, { "enumerant" : "FlagIsProtected", "value" : "0x01" diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.core.grammar.json b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.core.grammar.json index 18901cd16d..2852c09bc0 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.core.grammar.json +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.core.grammar.json @@ -2157,7 +2157,7 @@ { "kind" : "IdRef", "name" : "'Offset'" }, { "kind" : "IdRef", "name" : "'Count'" } ], - "capabilities" : [ "Shader" ] + "capabilities" : [ "Shader", "BitInstructions" ] }, { "opname" : "OpBitFieldSExtract", @@ -2170,7 +2170,7 @@ { "kind" : "IdRef", "name" : "'Offset'" }, { "kind" : "IdRef", "name" : "'Count'" } ], - "capabilities" : [ "Shader" ] + "capabilities" : [ "Shader", "BitInstructions" ] }, { "opname" : "OpBitFieldUExtract", @@ -2183,7 +2183,7 @@ { "kind" : "IdRef", "name" : "'Offset'" }, { "kind" : "IdRef", "name" : "'Count'" } ], - "capabilities" : [ "Shader" ] + "capabilities" : [ "Shader", "BitInstructions" ] }, { "opname" : "OpBitReverse", @@ -2194,7 +2194,7 @@ { "kind" : "IdResult" }, { "kind" : "IdRef", "name" : "'Base'" } ], - "capabilities" : [ "Shader" ] + "capabilities" : [ "Shader", "BitInstructions" ] }, { "opname" : "OpBitCount", @@ -4197,13 +4197,164 @@ "version" : "None" }, { - "opname" : "OpTypeRayQueryProvisionalKHR", + "opname" : "OpTraceRayKHR", + "class" : "Reserved", + "opcode" : 4445, + "operands" : [ + + { "kind" : "IdRef", "name" : "'Accel'" }, + { "kind" : "IdRef", "name" : "'Ray Flags'" }, + { "kind" : "IdRef", "name" : "'Cull Mask'" }, + { "kind" : "IdRef", "name" : "'SBT Offset'" }, + { "kind" : "IdRef", "name" : "'SBT Stride'" }, + { "kind" : "IdRef", "name" : "'Miss Index'" }, + { "kind" : "IdRef", "name" : "'Ray Origin'" }, + { "kind" : "IdRef", "name" : "'Ray Tmin'" }, + { "kind" : "IdRef", "name" : "'Ray Direction'" }, + { "kind" : "IdRef", "name" : "'Ray Tmax'" }, + { "kind" : "IdRef", "name" : "'Payload'" } + ], + "capabilities" : [ "RayTracingKHR" ], + "extensions" : [ "SPV_KHR_ray_tracing" ], + "version" : "None" + }, + { + "opname" : "OpExecuteCallableKHR", + "class" : "Reserved", + "opcode" : 4446, + "operands" : [ + + { "kind" : "IdRef", "name" : "'SBT Index'" }, + { "kind" : "IdRef", "name" : "'Callable Data'" } + ], + "capabilities" : [ "RayTracingKHR" ], + "extensions" : [ "SPV_KHR_ray_tracing" ], + "version" : "None" + }, + { + "opname" : "OpConvertUToAccelerationStructureKHR", + "class" : "Reserved", + "opcode" : 4447, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Accel'" } + ], + "capabilities" : [ "RayTracingKHR", "RayQueryKHR" ], + "extensions" : [ "SPV_KHR_ray_tracing", "SPV_KHR_ray_query" ], + "version" : "None" + }, + { + "opname" : "OpIgnoreIntersectionKHR", + "class" : "Reserved", + "opcode" : 4448, + "capabilities" : [ "RayTracingKHR" ], + "extensions" : [ "SPV_KHR_ray_tracing" ], + "version" : "None" + }, + { + "opname" : "OpTerminateRayKHR", + "class" : "Reserved", + "opcode" : 4449, + "capabilities" : [ "RayTracingKHR" ], + "extensions" : [ "SPV_KHR_ray_tracing" ], + "version" : "None" + }, + { + "opname" : "OpSDotKHR", + "class" : "Arithmetic", + "opcode" : 4450, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Vector 1'" }, + { "kind" : "IdRef", "name" : "'Vector 2'" }, + { "kind" : "PackedVectorFormat", "name" : "'Packed Vector Format'", "quantifier" : "?" } + ], + "capabilities" : [ "DotProductKHR" ], + "version" : "None" + }, + { + "opname" : "OpUDotKHR", + "class" : "Arithmetic", + "opcode" : 4451, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Vector 1'" }, + { "kind" : "IdRef", "name" : "'Vector 2'" }, + { "kind" : "PackedVectorFormat", "name" : "'Packed Vector Format'", "quantifier" : "?" } + ], + "capabilities" : [ "DotProductKHR" ], + "version" : "None" + }, + { + "opname" : "OpSUDotKHR", + "class" : "Arithmetic", + "opcode" : 4452, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Vector 1'" }, + { "kind" : "IdRef", "name" : "'Vector 2'" }, + { "kind" : "PackedVectorFormat", "name" : "'Packed Vector Format'", "quantifier" : "?" } + ], + "capabilities" : [ "DotProductKHR" ], + "version" : "None" + }, + { + "opname" : "OpSDotAccSatKHR", + "class" : "Arithmetic", + "opcode" : 4453, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Vector 1'" }, + { "kind" : "IdRef", "name" : "'Vector 2'" }, + { "kind" : "IdRef", "name" : "'Accumulator'" }, + { "kind" : "PackedVectorFormat", "name" : "'Packed Vector Format'", "quantifier" : "?" } + ], + "capabilities" : [ "DotProductKHR" ], + "version" : "None" + }, + { + "opname" : "OpUDotAccSatKHR", + "class" : "Arithmetic", + "opcode" : 4454, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Vector 1'" }, + { "kind" : "IdRef", "name" : "'Vector 2'" }, + { "kind" : "IdRef", "name" : "'Accumulator'" }, + { "kind" : "PackedVectorFormat", "name" : "'Packed Vector Format'", "quantifier" : "?" } + ], + "capabilities" : [ "DotProductKHR" ], + "version" : "None" + }, + { + "opname" : "OpSUDotAccSatKHR", + "class" : "Arithmetic", + "opcode" : 4455, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Vector 1'" }, + { "kind" : "IdRef", "name" : "'Vector 2'" }, + { "kind" : "IdRef", "name" : "'Accumulator'" }, + { "kind" : "PackedVectorFormat", "name" : "'Packed Vector Format'", "quantifier" : "?" } + ], + "capabilities" : [ "DotProductKHR" ], + "version" : "None" + }, + { + "opname" : "OpTypeRayQueryKHR", "class" : "Reserved", "opcode" : 4472, "operands" : [ { "kind" : "IdResult" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4246,7 +4397,7 @@ } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4260,7 +4411,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4278,7 +4429,7 @@ "name" : "'HitT'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4292,7 +4443,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4308,7 +4459,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4328,7 +4479,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4488,7 +4639,7 @@ "operands" : [ { "kind" : "IdResultType" }, { "kind" : "IdResult" }, - { "kind" : "IdScope", "name" : "'Execution'" } + { "kind" : "IdScope", "name" : "'Scope'" } ], "capabilities" : [ "ShaderClockKHR" ], "extensions" : [ "SPV_KHR_shader_clock" ], @@ -4546,7 +4697,7 @@ { "kind" : "IdRef", "name" : "'Hit'" }, { "kind" : "IdRef", "name" : "'HitKind'" } ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, @@ -4560,7 +4711,7 @@ { "kind" : "IdRef", "name" : "'Hit'" }, { "kind" : "IdRef", "name" : "'HitKind'" } ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, @@ -4568,32 +4719,16 @@ "opname" : "OpIgnoreIntersectionNV", "class" : "Reserved", "opcode" : 5335, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "version" : "None" - }, - { - "opname" : "OpIgnoreIntersectionKHR", - "class" : "Reserved", - "opcode" : 5335, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], + "capabilities" : [ "RayTracingNV" ], + "extensions" : [ "SPV_NV_ray_tracing" ], "version" : "None" }, { "opname" : "OpTerminateRayNV", "class" : "Reserved", "opcode" : 5336, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "version" : "None" - }, - { - "opname" : "OpTerminateRayKHR", - "class" : "Reserved", - "opcode" : 5336, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], + "capabilities" : [ "RayTracingNV" ], + "extensions" : [ "SPV_NV_ray_tracing" ], "version" : "None" }, { @@ -4614,30 +4749,8 @@ { "kind" : "IdRef", "name" : "'Ray Tmax'" }, { "kind" : "IdRef", "name" : "'PayloadId'" } ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "version" : "None" - }, - { - "opname" : "OpTraceRayKHR", - "class" : "Reserved", - "opcode" : 5337, - "operands" : [ - - { "kind" : "IdRef", "name" : "'Accel'" }, - { "kind" : "IdRef", "name" : "'Ray Flags'" }, - { "kind" : "IdRef", "name" : "'Cull Mask'" }, - { "kind" : "IdRef", "name" : "'SBT Offset'" }, - { "kind" : "IdRef", "name" : "'SBT Stride'" }, - { "kind" : "IdRef", "name" : "'Miss Index'" }, - { "kind" : "IdRef", "name" : "'Ray Origin'" }, - { "kind" : "IdRef", "name" : "'Ray Tmin'" }, - { "kind" : "IdRef", "name" : "'Ray Direction'" }, - { "kind" : "IdRef", "name" : "'Ray Tmax'" }, - { "kind" : "IdRef", "name" : "'PayloadId'" } - ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], + "capabilities" : [ "RayTracingNV" ], + "extensions" : [ "SPV_NV_ray_tracing" ], "version" : "None" }, { @@ -4647,7 +4760,7 @@ "operands" : [ { "kind" : "IdResult" } ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR", "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR", "RayQueryKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing", "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4658,7 +4771,7 @@ "operands" : [ { "kind" : "IdResult" } ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR", "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR", "RayQueryKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing", "SPV_KHR_ray_query" ], "version" : "None" }, @@ -4671,21 +4784,8 @@ { "kind" : "IdRef", "name" : "'SBT Index'" }, { "kind" : "IdRef", "name" : "'Callable DataId'" } ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "version" : "None" - }, - { - "opname" : "OpExecuteCallableKHR", - "class" : "Reserved", - "opcode" : 5344, - "operands" : [ - - { "kind" : "IdRef", "name" : "'SBT Index'" }, - { "kind" : "IdRef", "name" : "'Callable DataId'" } - ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], + "capabilities" : [ "RayTracingNV" ], + "extensions" : [ "SPV_NV_ray_tracing" ], "version" : "None" }, { @@ -5110,7 +5210,7 @@ "version" : "None" }, { - "opname" : "OpFunctionPointerINTEL", + "opname" : "OpConstFunctionPointerINTEL", "class" : "@exclude", "opcode" : 5600, "operands" : [ @@ -5135,6 +5235,101 @@ "extensions" : [ "SPV_INTEL_function_pointers" ], "version" : "None" }, + { + "opname" : "OpAsmTargetINTEL", + "class" : "@exclude", + "opcode" : 5609, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "LiteralString", "name" : "'Asm target'" } + ], + "capabilities" : [ "AsmINTEL" ], + "version" : "None" + }, + { + "opname" : "OpAsmINTEL", + "class" : "@exclude", + "opcode" : 5610, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Asm type'" }, + { "kind" : "IdRef", "name" : "'Target'" }, + { "kind" : "LiteralString", "name" : "'Asm instructions'" }, + { "kind" : "LiteralString", "name" : "'Constraints'" } + ], + "capabilities" : [ "AsmINTEL" ], + "version" : "None" + }, + { + "opname" : "OpAsmCallINTEL", + "class" : "@exclude", + "opcode" : 5611, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Asm'" }, + { "kind" : "IdRef", "quantifier" : "*", "name" : "'Argument 0'" } + ], + "capabilities" : [ "AsmINTEL" ], + "version" : "None" + }, + { + "opname" : "OpAtomicFMinEXT", + "class" : "Atomic", + "opcode" : 5614, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Pointer'" }, + { "kind" : "IdScope", "name" : "'Memory'" }, + { "kind" : "IdMemorySemantics", "name" : "'Semantics'" }, + { "kind" : "IdRef", "name" : "'Value'" } + ], + "capabilities" : [ "AtomicFloat16MinMaxEXT", "AtomicFloat32MinMaxEXT", "AtomicFloat64MinMaxEXT" ], + "version" : "None" + }, + { + "opname" : "OpAtomicFMaxEXT", + "class" : "Atomic", + "opcode" : 5615, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Pointer'" }, + { "kind" : "IdScope", "name" : "'Memory'" }, + { "kind" : "IdMemorySemantics", "name" : "'Semantics'" }, + { "kind" : "IdRef", "name" : "'Value'" } + ], + "capabilities" : [ "AtomicFloat16MinMaxEXT", "AtomicFloat32MinMaxEXT", "AtomicFloat64MinMaxEXT" ], + "version" : "None" + }, + { + "opname" : "OpAssumeTrueKHR", + "class" : "Miscellaneous", + "opcode" : 5630, + "operands" : [ + { "kind" : "IdRef", "name" : "'Condition'" } + ], + "capabilities" : [ "ExpectAssumeKHR" ], + "extensions" : [ "SPV_KHR_expect_assume" ], + "version" : "None" + }, + { + "opname" : "OpExpectKHR", + "class" : "Miscellaneous", + "opcode" : 5631, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Value'" }, + { "kind" : "IdRef", "name" : "'ExpectedValue'" } + ], + "capabilities" : [ "ExpectAssumeKHR" ], + "extensions" : [ "SPV_KHR_expect_assume" ], + "version" : "None" + }, { "opname" : "OpDecorateString", "class" : "Annotation", @@ -6698,6 +6893,761 @@ "capabilities" : [ "SubgroupAvcMotionEstimationINTEL" ], "version" : "None" }, + { + "opname" : "OpVariableLengthArrayINTEL", + "class" : "@exclude", + "opcode" : 5818, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Lenght'" } + ], + "capabilities" : [ "VariableLengthArrayINTEL" ], + "version" : "None" + }, + { + "opname" : "OpSaveMemoryINTEL", + "class" : "@exclude", + "opcode" : 5819, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" } + ], + "capabilities" : [ "VariableLengthArrayINTEL" ], + "version" : "None" + }, + { + "opname" : "OpRestoreMemoryINTEL", + "class" : "@exclude", + "opcode" : 5820, + "operands" : [ + { "kind" : "IdRef", "name" : "'Ptr'" } + ], + "capabilities" : [ "VariableLengthArrayINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatSinCosPiINTEL", + "class" : "@exclude", + "opcode" : 5840, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'FromSign'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatCastINTEL", + "class" : "@exclude", + "opcode" : 5841, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatCastFromIntINTEL", + "class" : "@exclude", + "opcode" : 5842, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'FromSign'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatCastToIntINTEL", + "class" : "@exclude", + "opcode" : 5843, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatAddINTEL", + "class" : "@exclude", + "opcode" : 5846, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatSubINTEL", + "class" : "@exclude", + "opcode" : 5847, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatMulINTEL", + "class" : "@exclude", + "opcode" : 5848, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatDivINTEL", + "class" : "@exclude", + "opcode" : 5849, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatGTINTEL", + "class" : "@exclude", + "opcode" : 5850, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatGEINTEL", + "class" : "@exclude", + "opcode" : 5851, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatLTINTEL", + "class" : "@exclude", + "opcode" : 5852, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatLEINTEL", + "class" : "@exclude", + "opcode" : 5853, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatEQINTEL", + "class" : "@exclude", + "opcode" : 5854, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatRecipINTEL", + "class" : "@exclude", + "opcode" : 5855, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatRSqrtINTEL", + "class" : "@exclude", + "opcode" : 5856, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatCbrtINTEL", + "class" : "@exclude", + "opcode" : 5857, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatHypotINTEL", + "class" : "@exclude", + "opcode" : 5858, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatSqrtINTEL", + "class" : "@exclude", + "opcode" : 5859, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatLogINTEL", + "class" : "@exclude", + "opcode" : 5860, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatLog2INTEL", + "class" : "@exclude", + "opcode" : 5861, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatLog10INTEL", + "class" : "@exclude", + "opcode" : 5862, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatLog1pINTEL", + "class" : "@exclude", + "opcode" : 5863, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatExpINTEL", + "class" : "@exclude", + "opcode" : 5864, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatExp2INTEL", + "class" : "@exclude", + "opcode" : 5865, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatExp10INTEL", + "class" : "@exclude", + "opcode" : 5866, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatExpm1INTEL", + "class" : "@exclude", + "opcode" : 5867, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatSinINTEL", + "class" : "@exclude", + "opcode" : 5868, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatCosINTEL", + "class" : "@exclude", + "opcode" : 5869, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatSinCosINTEL", + "class" : "@exclude", + "opcode" : 5870, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatSinPiINTEL", + "class" : "@exclude", + "opcode" : 5871, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatCosPiINTEL", + "class" : "@exclude", + "opcode" : 5872, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatASinINTEL", + "class" : "@exclude", + "opcode" : 5873, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatASinPiINTEL", + "class" : "@exclude", + "opcode" : 5874, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatACosINTEL", + "class" : "@exclude", + "opcode" : 5875, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatACosPiINTEL", + "class" : "@exclude", + "opcode" : 5876, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatATanINTEL", + "class" : "@exclude", + "opcode" : 5877, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatATanPiINTEL", + "class" : "@exclude", + "opcode" : 5878, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatATan2INTEL", + "class" : "@exclude", + "opcode" : 5879, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatPowINTEL", + "class" : "@exclude", + "opcode" : 5880, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatPowRINTEL", + "class" : "@exclude", + "opcode" : 5881, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'M2'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatPowNINTEL", + "class" : "@exclude", + "opcode" : 5882, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpArbitraryFloatPowNINTEL", + "class" : "@exclude", + "opcode" : 5882, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'A'" }, + { "kind" : "LiteralInteger", "name" : "'M1'" }, + { "kind" : "IdRef", "name" : "'B'" }, + { "kind" : "LiteralInteger", "name" : "'Mout'" }, + { "kind" : "LiteralInteger", "name" : "'EnableSubnormals'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingMode'" }, + { "kind" : "LiteralInteger", "name" : "'RoundingAccuracy'" } + ], + "capabilities" : [ "ArbitraryPrecisionFloatingPointINTEL" ], + "version" : "None" + }, { "opname" : "OpLoopControlINTEL", "class" : "Reserved", @@ -6709,6 +7659,228 @@ "extensions" : [ "SPV_INTEL_unstructured_loop_controls" ], "version" : "None" }, + { + "opname" : "OpFixedSqrtINTEL", + "class" : "@exclude", + "opcode" : 5923, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedRecipINTEL", + "class" : "@exclude", + "opcode" : 5924, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedRsqrtINTEL", + "class" : "@exclude", + "opcode" : 5925, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedSinINTEL", + "class" : "@exclude", + "opcode" : 5926, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedCosINTEL", + "class" : "@exclude", + "opcode" : 5927, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedSinCosINTEL", + "class" : "@exclude", + "opcode" : 5928, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedSinPiINTEL", + "class" : "@exclude", + "opcode" : 5929, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedCosPiINTEL", + "class" : "@exclude", + "opcode" : 5930, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedSinCosPiINTEL", + "class" : "@exclude", + "opcode" : 5931, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedLogINTEL", + "class" : "@exclude", + "opcode" : 5932, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpFixedExpINTEL", + "class" : "@exclude", + "opcode" : 5933, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Input Type'" }, + { "kind" : "IdRef", "name" : "'Input'" }, + { "kind" : "LiteralInteger", "name" : "'S'" }, + { "kind" : "LiteralInteger", "name" : "'I'" }, + { "kind" : "LiteralInteger", "name" : "'rI'" }, + { "kind" : "LiteralInteger", "name" : "'Q'" }, + { "kind" : "LiteralInteger", "name" : "'O'" } + ], + "capabilities" : [ "ArbitraryPrecisionFixedPointINTEL" ], + "version" : "None" + }, + { + "opname" : "OpPtrCastToCrossWorkgroupINTEL", + "class" : "@exclude", + "opcode" : 5934, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Pointer'" } + ], + "capabilities" : [ "USMStorageClassesINTEL" ], + "version" : "None" + }, + { + "opname" : "OpCrossWorkgroupCastToPtrINTEL", + "class" : "@exclude", + "opcode" : 5938, + "operands" : [ + { "kind" : "IdResultType" }, + { "kind" : "IdResult" }, + { "kind" : "IdRef", "name" : "'Pointer'" } + ], + "capabilities" : [ "USMStorageClassesINTEL" ], + "version" : "None" + }, { "opname" : "OpReadPipeBlockingINTEL", "class" : "Pipe", @@ -6763,7 +7935,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6779,7 +7951,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6799,7 +7971,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6819,7 +7991,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6839,7 +8011,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6859,7 +8031,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6879,7 +8051,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6899,7 +8071,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6919,7 +8091,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6939,7 +8111,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6955,7 +8127,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6975,7 +8147,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -6995,7 +8167,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -7011,7 +8183,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -7027,7 +8199,7 @@ "name" : "'RayQuery'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -7047,7 +8219,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -7067,7 +8239,7 @@ "name" : "'Intersection'" } ], - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "extensions" : [ "SPV_KHR_ray_query" ], "version" : "None" }, @@ -7083,9 +8255,53 @@ { "kind" : "IdMemorySemantics", "name" : "'Semantics'" }, { "kind" : "IdRef", "name" : "'Value'" } ], - "capabilities" : [ "AtomicFloat32AddEXT", "AtomicFloat64AddEXT" ], + "capabilities" : [ "AtomicFloat16AddEXT", "AtomicFloat32AddEXT", "AtomicFloat64AddEXT" ], "extensions" : [ "SPV_EXT_shader_atomic_float_add" ], "version" : "None" + }, + { + "opname" : "OpTypeBufferSurfaceINTEL", + "class" : "Type-Declaration", + "opcode" : 6086, + "operands" : [ + { "kind" : "IdResult" }, + { + "kind" : "AccessQualifier", + "name" : "'AccessQualifier'" + } + ], + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "opname" : "OpTypeStructContinuedINTEL", + "class" : "Type-Declaration", + "opcode" : 6090, + "operands" : [ + { "kind" : "IdRef", "quantifier" : "*", "name" : "'Member 0 type', +\n'member 1 type', +\n..." } + ], + "capabilities" : [ "LongConstantCompositeINTEL" ], + "version" : "None" + }, + { + "opname" : "OpConstantCompositeContinuedINTEL", + "class" : "Constant-Creation", + "opcode" : 6091, + "operands" : [ + { "kind" : "IdRef", "quantifier" : "*", "name" : "'Constituents'" } + ], + "capabilities" : [ "LongConstantCompositeINTEL" ], + "version" : "None" + }, + { + "opname" : "OpSpecConstantCompositeContinuedINTEL", + "class" : "Constant-Creation", + "opcode" : 6092, + "operands" : [ + { "kind" : "IdRef", "quantifier" : "*", "name" : "'Constituents'" } + ], + "capabilities" : [ "LongConstantCompositeINTEL" ], + "version" : "None" } ], "operand_kinds" : [ @@ -7266,6 +8482,18 @@ "enumerant" : "Fast", "value" : "0x0010", "capabilities" : [ "Kernel" ] + }, + { + "enumerant" : "AllowContractFastINTEL", + "value" : "0x10000", + "capabilities" : [ "FPFastMathModeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "AllowReassocINTEL", + "value" : "0x20000", + "capabilities" : [ "FPFastMathModeINTEL" ], + "version" : "None" } ] }, @@ -7425,6 +8653,16 @@ "capabilities" : [ "FPGALoopControlsINTEL" ], "extensions" : [ "SPV_INTEL_fpga_loop_controls" ], "version" : "None" + }, + { + "enumerant" : "NoFusionINTEL", + "value" : "0x800000", + "parameters" : [ + { "kind" : "LiteralInteger" } + ], + "capabilities" : [ "FPGALoopControlsINTEL" ], + "extensions" : [ "SPV_INTEL_fpga_loop_controls" ], + "version" : "None" } ] }, @@ -7654,67 +8892,67 @@ { "enumerant" : "NoneKHR", "value" : "0x0000", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "OpaqueKHR", "value" : "0x0001", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "NoOpaqueKHR", "value" : "0x0002", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "TerminateOnFirstHitKHR", "value" : "0x0004", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "SkipClosestHitShaderKHR", "value" : "0x0008", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CullBackFacingTrianglesKHR", "value" : "0x0010", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CullFrontFacingTrianglesKHR", "value" : "0x0020", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CullOpaqueKHR", "value" : "0x0040", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CullNoOpaqueKHR", "value" : "0x0080", - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "version" : "None" }, { "enumerant" : "SkipTrianglesKHR", "value" : "0x0100", - "capabilities" : [ "RayTraversalPrimitiveCullingProvisionalKHR" ], + "capabilities" : [ "RayTraversalPrimitiveCullingKHR" ], "version" : "None" }, { "enumerant" : "SkipAABBsKHR", "value" : "0x0200", - "capabilities" : [ "RayTraversalPrimitiveCullingProvisionalKHR" ], + "capabilities" : [ "RayTraversalPrimitiveCullingKHR" ], "version" : "None" } ] @@ -7776,6 +9014,10 @@ { "enumerant" : "HLSL", "value" : 5 + }, + { + "enumerant" : "CPP_for_OpenCL", + "value" : 6 } ] }, @@ -7833,73 +9075,73 @@ { "enumerant" : "RayGenerationNV", "value" : 5313, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "RayGenerationKHR", "value" : 5313, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "IntersectionNV", "value" : 5314, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "IntersectionKHR", "value" : 5314, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "AnyHitNV", "value" : 5315, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "AnyHitKHR", "value" : 5315, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "ClosestHitNV", "value" : 5316, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "ClosestHitKHR", "value" : 5316, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "MissNV", "value" : 5317, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "MissKHR", "value" : 5317, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CallableNV", "value" : 5318, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CallableKHR", "value" : 5318, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" } ] @@ -8207,6 +9449,13 @@ ], "version" : "1.2" }, + { + "enumerant" : "SubgroupUniformControlFlowKHR", + "value" : 4421, + "capabilities" : [ "Shader" ], + "extensions" : [ "SPV_KHR_subgroup_uniform_control_flow" ], + "version" : "None" + }, { "enumerant" : "PostDepthCoverage", "value" : 4446, @@ -8351,6 +9600,51 @@ "extensions" : [ "SPV_EXT_fragment_shader_interlock" ], "version" : "None" }, + { + "enumerant" : "SharedLocalMemorySizeINTEL", + "value" : 5618, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Size'" } + ], + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "RoundingModeRTPINTEL", + "value" : 5620, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" } + ], + "capabilities" : [ "RoundToInfinityINTEL" ], + "version" : "None" + }, + { + "enumerant" : "RoundingModeRTNINTEL", + "value" : 5621, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" } + ], + "capabilities" : [ "RoundToInfinityINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FloatingPointModeALTINTEL", + "value" : 5622, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" } + ], + "capabilities" : [ "RoundToInfinityINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FloatingPointModeIEEEINTEL", + "value" : 5623, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" } + ], + "capabilities" : [ "RoundToInfinityINTEL" ], + "version" : "None" + }, { "enumerant" : "MaxWorkgroupSizeINTEL", "value" : 5893, @@ -8389,6 +9683,15 @@ "capabilities" : [ "FPGAKernelAttributesINTEL" ], "extensions" : [ "SPV_INTEL_kernel_attributes" ], "version" : "None" + }, + { + "enumerant" : "SchedulerTargetFmaxMhzINTEL", + "value" : 5903, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'target_fmax'" } + ], + "capabilities" : [ "FPGAKernelAttributesINTEL" ], + "version" : "None" } ] }, @@ -8425,7 +9728,7 @@ { "enumerant" : "Private", "value" : 6, - "capabilities" : [ "Shader" ] + "capabilities" : [ "Shader", "VectorComputeINTEL" ] }, { "enumerant" : "Function", @@ -8464,84 +9767,84 @@ "enumerant" : "CallableDataNV", "value" : 5328, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "CallableDataKHR", "value" : 5328, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "IncomingCallableDataNV", "value" : 5329, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "IncomingCallableDataKHR", "value" : 5329, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "RayPayloadNV", "value" : 5338, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "RayPayloadKHR", "value" : 5338, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "HitAttributeNV", "value" : 5339, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "HitAttributeKHR", "value" : 5339, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "IncomingRayPayloadNV", "value" : 5342, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "IncomingRayPayloadKHR", "value" : 5342, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "ShaderRecordBufferNV", "value" : 5343, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { "enumerant" : "ShaderRecordBufferKHR", "value" : 5343, "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "version" : "None" }, { @@ -8564,6 +9867,24 @@ "extensions" : [ "SPV_INTEL_function_pointers" ], "capabilities" : [ "FunctionPointersINTEL" ], "version" : "None" + }, + { + "enumerant" : "DeviceOnlyINTEL", + "value" : 5936, + "extensions" : [ + "SPV_INTEL_usm_storage_classes" + ], + "capabilities" : [ "USMStorageClassesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "HostOnlyINTEL", + "value" : 5937, + "extensions" : [ + "SPV_INTEL_usm_storage_classes" + ], + "capabilities" : [ "USMStorageClassesINTEL" ], + "version" : "None" } ] }, @@ -9088,6 +10409,102 @@ } ] }, + { + "category" : "ValueEnum", + "kind" : "FPDenormMode", + "enumerants" : [ + { + "enumerant" : "Preserve", + "value" : 0, + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FlushToZero", + "value" : 1, + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + } + ] + }, + { + "category" : "ValueEnum", + "kind" : "QuantizationModes", + "enumerants" : [ + { + "enumerant" : "TRN", + "value" : 0 + }, + { + "enumerant" : "TRN_ZERO", + "value" : 1 + }, + { + "enumerant" : "RND", + "value" : 2 + }, + { + "enumerant" : "RND_ZERO", + "value" : 3 + }, + { + "enumerant" : "RND_INF", + "value" : 4 + }, + { + "enumerant" : "RND_MIN_INF", + "value" : 5 + }, + { + "enumerant" : "RND_CONV", + "value" : 6 + }, + { + "enumerant" : "RND_CONV_ODD", + "value" : 7 + } + ] + }, + { + "category" : "ValueEnum", + "kind" : "FPOperationMode", + "enumerants" : [ + { + "enumerant" : "IEEE", + "value" : 0, + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + }, + { + "enumerant" : "ALT", + "value" : 1, + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + } + ] + }, + { + "category" : "ValueEnum", + "kind" : "OverflowModes", + "enumerants" : [ + { + "enumerant" : "WRAP", + "value" : 0 + }, + { + "enumerant" : "SAT", + "value" : 1 + }, + { + "enumerant" : "SAT_ZERO", + "value" : 2 + }, + { + "enumerant" : "SAT_SYM", + "value" : 3 + } + ] + }, { "category" : "ValueEnum", "kind" : "LinkageType", @@ -9101,6 +10518,13 @@ "enumerant" : "Import", "value" : 1, "capabilities" : [ "Linkage" ] + }, + { + "enumerant" : "LinkOnceODR", + "value" : 2, + "capabilities" : [ "Linkage" ], + "extensions" : [ "SPV_KHR_linkonce_odr" ], + "version" : "None" } ] }, @@ -9594,6 +11018,15 @@ "extensions" : [ "SPV_EXT_physical_storage_buffer" ], "version" : "1.5" }, + { + "enumerant" : "SIMTCallINTEL", + "value" : 5599, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'N'" } + ], + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, { "enumerant" : "ReferencedIndirectlyINTEL", "value" : 5602, @@ -9601,6 +11034,57 @@ "extensions" : [ "SPV_INTEL_function_pointers" ], "version" : "None" }, + { + "enumerant" : "ClobberINTEL", + "value" : 5607, + "parameters" : [ + { "kind" : "LiteralString", "name" : "'Register'" } + ], + "capabilities" : [ "AsmINTEL" ], + "version" : "None" + }, + { + "enumerant" : "SideEffectsINTEL", + "value" : 5608, + "capabilities" : [ "AsmINTEL" ], + "version" : "None" + }, + { + "enumerant" : "VectorComputeVariableINTEL", + "value" : 5624, + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FuncParamIOKindINTEL", + "value" : 5625, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Kind'" } + ], + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "VectorComputeFunctionINTEL", + "value" : 5626, + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "StackCallINTEL", + "value" : 5627, + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "GlobalVariableOffsetINTEL", + "value" : 5628, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Offset'" } + ], + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, { "enumerant" : "CounterBuffer", "value" : 5634, @@ -9644,6 +11128,26 @@ "extensions" : [ "SPV_GOOGLE_user_type" ], "version" : "None" }, + { + "enumerant" : "FunctionRoundingModeINTEL", + "value" : 5822, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" }, + { "kind" : "FPRoundingMode", "name" : "'FP Rounding Mode'" } + ], + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FunctionDenormModeINTEL", + "value" : 5823, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" }, + { "kind" : "FPDenormMode", "name" : "'FP Denorm Mode'" } + ], + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + }, { "enumerant" : "RegisterINTEL", "value" : 5825, @@ -9752,6 +11256,88 @@ "capabilities" : [ "FPGAMemoryAttributesINTEL" ], "extensions" : [ "SPV_INTEL_fpga_memory_attributes" ], "version" : "None" + }, + { + "enumerant" : "BurstCoalesceINTEL", + "value" : 5899, + "capabilities" : [ "FPGAMemoryAccessesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "CacheSizeINTEL", + "value" : 5900, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Cache Size in bytes'" } + ], + "capabilities" : [ "FPGAMemoryAccessesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "DontStaticallyCoalesceINTEL", + "value" : 5901, + "capabilities" : [ "FPGAMemoryAccessesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "PrefetchINTEL", + "value" : 5902, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Prefetcher Size in bytes'" } + ], + "capabilities" : [ "FPGAMemoryAccessesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "StallEnableINTEL", + "value" : 5905, + "capabilities" : [ "FPGAClusterAttributesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FuseLoopsInFunctionINTEL", + "value" : 5907, + "capabilities" : [ "LoopFuseINTEL" ], + "version" : "None" + }, + { + "enumerant" : "BufferLocationINTEL", + "value" : 5921, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Buffer Location ID'" } + ], + "capabilities" : [ "FPGABufferLocationINTEL" ], + "version" : "None" + }, + { + "enumerant" : "IOPipeStorageINTEL", + "value" : 5944, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'IO Pipe ID'" } + ], + "capabilities" : [ "IOPipesINTEL" ], + "version" : "None" + }, + { + "enumerant" : "FunctionFloatingPointModeINTEL", + "value" : 6080, + "parameters" : [ + { "kind" : "LiteralInteger", "name" : "'Target Width'" }, + { "kind" : "FPOperationMode", "name" : "'FP Operation Mode'" } + ], + "capabilities" : [ "FunctionFloatControlINTEL" ], + "version" : "None" + }, + { + "enumerant" : "SingleElementVectorINTEL", + "value" : 6085, + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" + }, + { + "enumerant" : "VectorComputeCallableFunctionINTEL", + "value" : 6087, + "capabilities" : [ "VectorComputeINTEL" ], + "version" : "None" } ] }, @@ -9792,7 +11378,7 @@ { "enumerant" : "PrimitiveId", "value" : 7, - "capabilities" : [ "Geometry", "Tessellation", "RayTracingNV", "RayTracingProvisionalKHR" ] + "capabilities" : [ "Geometry", "Tessellation", "RayTracingNV", "RayTracingKHR", "MeshShadingNV" ] }, { "enumerant" : "InvocationId", @@ -9802,12 +11388,12 @@ { "enumerant" : "Layer", "value" : 9, - "capabilities" : [ "Geometry", "ShaderLayer", "ShaderViewportIndexLayerEXT" ] + "capabilities" : [ "Geometry", "ShaderLayer", "ShaderViewportIndexLayerEXT", "MeshShadingNV" ] }, { "enumerant" : "ViewportIndex", "value" : 10, - "capabilities" : [ "MultiViewport", "ShaderViewportIndex", "ShaderViewportIndexLayerEXT" ] + "capabilities" : [ "MultiViewport", "ShaderViewportIndex", "ShaderViewportIndexLayerEXT", "MeshShadingNV" ] }, { "enumerant" : "TessLevelOuter", @@ -9964,30 +11550,6 @@ "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], "version" : "1.3" }, - { - "enumerant" : "SubgroupGeMask", - "value" : 4417, - "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], - "version" : "1.3" - }, - { - "enumerant" : "SubgroupGtMask", - "value" : 4418, - "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], - "version" : "1.3" - }, - { - "enumerant" : "SubgroupLeMask", - "value" : 4419, - "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], - "version" : "1.3" - }, - { - "enumerant" : "SubgroupLtMask", - "value" : 4420, - "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], - "version" : "1.3" - }, { "enumerant" : "SubgroupEqMaskKHR", "value" : 4416, @@ -9995,6 +11557,12 @@ "extensions" : [ "SPV_KHR_shader_ballot" ], "version" : "1.3" }, + { + "enumerant" : "SubgroupGeMask", + "value" : 4417, + "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], + "version" : "1.3" + }, { "enumerant" : "SubgroupGeMaskKHR", "value" : 4417, @@ -10002,6 +11570,12 @@ "extensions" : [ "SPV_KHR_shader_ballot" ], "version" : "1.3" }, + { + "enumerant" : "SubgroupGtMask", + "value" : 4418, + "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], + "version" : "1.3" + }, { "enumerant" : "SubgroupGtMaskKHR", "value" : 4418, @@ -10009,6 +11583,12 @@ "extensions" : [ "SPV_KHR_shader_ballot" ], "version" : "1.3" }, + { + "enumerant" : "SubgroupLeMask", + "value" : 4419, + "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], + "version" : "1.3" + }, { "enumerant" : "SubgroupLeMaskKHR", "value" : 4419, @@ -10016,6 +11596,12 @@ "extensions" : [ "SPV_KHR_shader_ballot" ], "version" : "1.3" }, + { + "enumerant" : "SubgroupLtMask", + "value" : 4420, + "capabilities" : [ "SubgroupBallotKHR", "GroupNonUniformBallot" ], + "version" : "1.3" + }, { "enumerant" : "SubgroupLtMaskKHR", "value" : 4420, @@ -10264,203 +11850,196 @@ { "enumerant" : "LaunchIdNV", "value" : 5319, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "LaunchIdKHR", "value" : 5319, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "LaunchSizeNV", "value" : 5320, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "LaunchSizeKHR", "value" : 5320, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "WorldRayOriginNV", "value" : 5321, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "WorldRayOriginKHR", "value" : 5321, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "WorldRayDirectionNV", "value" : 5322, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "WorldRayDirectionKHR", "value" : 5322, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "ObjectRayOriginNV", "value" : 5323, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "ObjectRayOriginKHR", "value" : 5323, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "ObjectRayDirectionNV", "value" : 5324, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "ObjectRayDirectionKHR", "value" : 5324, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "RayTminNV", "value" : 5325, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "RayTminKHR", "value" : 5325, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "RayTmaxNV", "value" : 5326, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "RayTmaxKHR", "value" : 5326, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "InstanceCustomIndexNV", "value" : 5327, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "InstanceCustomIndexKHR", "value" : 5327, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "ObjectToWorldNV", "value" : 5330, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "ObjectToWorldKHR", "value" : 5330, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "WorldToObjectNV", "value" : 5331, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "WorldToObjectKHR", "value" : 5331, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "HitTNV", "value" : 5332, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], - "version" : "None" - }, - { - "enumerant" : "HitTKHR", - "value" : 5332, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], - "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], + "capabilities" : [ "RayTracingNV" ], + "extensions" : [ "SPV_NV_ray_tracing" ], "version" : "None" }, { "enumerant" : "HitKindNV", "value" : 5333, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "HitKindKHR", "value" : 5333, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "IncomingRayFlagsNV", "value" : 5351, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "IncomingRayFlagsKHR", "value" : 5351, - "capabilities" : [ "RayTracingNV" , "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingNV" , "RayTracingKHR" ], "extensions" : [ "SPV_NV_ray_tracing" , "SPV_KHR_ray_tracing" ], "version" : "None" }, { "enumerant" : "RayGeometryIndexKHR", "value" : 5352, - "capabilities" : [ "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingKHR" ], "extensions" : [ "SPV_KHR_ray_tracing" ], "version" : "None" }, @@ -10533,7 +12112,7 @@ { "enumerant" : "ShaderCallKHR", "value" : 6, - "capabilities" : [ "RayTracingProvisionalKHR" ], + "capabilities" : [ "RayTracingKHR" ], "version" : "None" } ] @@ -10975,6 +12554,27 @@ "extensions" : [ "SPV_KHR_shader_draw_parameters" ], "version" : "1.3" }, + { + "enumerant" : "WorkgroupMemoryExplicitLayoutKHR", + "value" : 4428, + "capabilities" : [ "Shader" ], + "extensions" : [ "SPV_KHR_workgroup_memory_explicit_layout" ], + "version" : "None" + }, + { + "enumerant" : "WorkgroupMemoryExplicitLayout8BitAccessKHR", + "value" : 4429, + "capabilities" : [ "WorkgroupMemoryExplicitLayoutKHR" ], + "extensions" : [ "SPV_KHR_workgroup_memory_explicit_layout" ], + "version" : "None" + }, + { + "enumerant" : "WorkgroupMemoryExplicitLayout16BitAccessKHR", + "value" : 4430, + "capabilities" : [ "Shader" ], + "extensions" : [ "SPV_KHR_workgroup_memory_explicit_layout" ], + "version" : "None" + }, { "enumerant" : "SubgroupVoteKHR", "value" : 4431, @@ -11121,12 +12721,26 @@ "version" : "None" }, { - "enumerant" : "RayTraversalPrimitiveCullingProvisionalKHR", + "enumerant" : "RayQueryKHR", + "value" : 4472, + "capabilities" : [ "Shader" ], + "extensions" : [ "SPV_KHR_ray_query" ], + "version" : "None" + }, + { + "enumerant" : "RayTraversalPrimitiveCullingKHR", "value" : 4478, - "capabilities" : [ "RayQueryProvisionalKHR","RayTracingProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR","RayTracingKHR" ], "extensions" : [ "SPV_KHR_ray_query","SPV_KHR_ray_tracing" ], "version" : "None" }, + { + "enumerant" : "RayTracingKHR", + "value" : 4479, + "capabilities" : [ "Shader" ], + "extensions" : [ "SPV_KHR_ray_tracing" ], + "version" : "None" + }, { "enumerant" : "Float16ImageAMD", "value" : 5008, @@ -11555,6 +13169,18 @@ "extensions" : [ "SPV_INTEL_media_block_io" ], "version" : "None" }, + { + "enumerant" : "RoundToInfinityINTEL", + "value" : 5582, + "extensions" : [ "SPV_INTEL_float_controls2" ], + "version" : "None" + }, + { + "enumerant" : "FloatingPointModeINTEL", + "value" : 5583, + "extensions" : [ "SPV_INTEL_float_controls2" ], + "version" : "None" + }, { "enumerant" : "IntegerFunctions2INTEL", "value" : 5584, @@ -11574,6 +13200,49 @@ "extensions" : [ "SPV_INTEL_function_pointers" ], "version" : "None" }, + { + "enumerant" : "AsmINTEL", + "value" : 5606, + "extensions" : [ "SPV_INTEL_inline_assembly" ], + "version" : "None" + }, + { + "enumerant" : "AtomicFloat32MinMaxEXT", + "value" : 5612, + "extensions" : [ "SPV_EXT_shader_atomic_float_min_max" ], + "version" : "None" + }, + { + "enumerant" : "AtomicFloat64MinMaxEXT", + "value" : 5613, + "extensions" : [ "SPV_EXT_shader_atomic_float_min_max" ], + "version" : "None" + }, + { + "enumerant" : "AtomicFloat16MinMaxEXT", + "value" : 5616, + "extensions" : [ "SPV_EXT_shader_atomic_float_min_max" ], + "version" : "None" + }, + { + "enumerant" : "VectorComputeINTEL", + "value" : 5617, + "capabilities" : [ "VectorAnyINTEL" ], + "extensions" : [ "SPV_INTEL_vector_compute" ], + "version" : "None" + }, + { + "enumerant" : "VectorAnyINTEL", + "value" : 5619, + "extensions" : [ "SPV_INTEL_vector_compute" ], + "version" : "None" + }, + { + "enumerant" : "ExpectAssumeKHR", + "value" : 5629, + "extensions" : [ "SPV_KHR_expect_assume" ], + "version" : "None" + }, { "enumerant" : "SubgroupAvcMotionEstimationINTEL", "value" : 5696, @@ -11592,12 +13261,43 @@ "extensions" : [ "SPV_INTEL_device_side_avc_motion_estimation" ], "version" : "None" }, + { + "enumerant" : "VariableLengthArrayINTEL", + "value" : 5817, + "extensions" : [ "SPV_INTEL_variable_length_array" ], + "version" : "None" + }, + { + "enumerant" : "FunctionFloatControlINTEL", + "value" : 5821, + "extensions" : [ "SPV_INTEL_float_controls2" ], + "version" : "None" + }, { "enumerant" : "FPGAMemoryAttributesINTEL", "value" : 5824, "extensions" : [ "SPV_INTEL_fpga_memory_attributes" ], "version" : "None" }, + { + "enumerant" : "FPFastMathModeINTEL", + "value" : 5837, + "capabilities" : [ "Kernel" ], + "extensions" : [ "SPV_INTEL_fp_fast_math_mode" ], + "version" : "None" + }, + { + "enumerant" : "ArbitraryPrecisionIntegersINTEL", + "value" : 5844, + "extensions" : [ "SPV_INTEL_arbitrary_precision_integers" ], + "version" : "None" + }, + { + "enumerant" : "ArbitraryPrecisionFloatingPointINTEL", + "value" : 5845, + "extensions" : [ "SPV_INTEL_arbitrary_precision_floating_point" ], + "version" : "None" + }, { "enumerant" : "UnstructuredLoopControlsINTEL", "value" : 5886, @@ -11622,6 +13322,48 @@ "extensions" : [ "SPV_INTEL_kernel_attributes" ], "version" : "None" }, + { + "enumerant" : "FPGAMemoryAccessesINTEL", + "value" : 5898, + "extensions" : [ "SPV_INTEL_fpga_memory_accesses" ], + "version" : "None" + }, + { + "enumerant" : "FPGAClusterAttributesINTEL", + "value" : 5904, + "extensions" : [ "SPV_INTEL_fpga_cluster_attributes" ], + "version" : "None" + }, + { + "enumerant" : "LoopFuseINTEL", + "value" : 5906, + "extensions" : [ "SPV_INTEL_loop_fuse" ], + "version" : "None" + }, + { + "enumerant" : "FPGABufferLocationINTEL", + "value" : 5920, + "extensions" : [ "SPV_INTEL_fpga_buffer_location" ], + "version" : "None" + }, + { + "enumerant" : "ArbitraryPrecisionFixedPointINTEL", + "value" : 5922, + "extensions" : [ "SPV_INTEL_arbitrary_precision_fixed_point" ], + "version" : "None" + }, + { + "enumerant" : "USMStorageClassesINTEL", + "value" : 5935, + "extensions" : [ "SPV_INTEL_usm_storage_classes" ], + "version" : "None" + }, + { + "enumerant" : "IOPipesINTEL", + "value" : 5943, + "extensions" : [ "SPV_INTEL_io_pipes" ], + "version" : "None" + }, { "enumerant" : "BlockingPipesINTEL", "value" : 5945, @@ -11634,6 +13376,37 @@ "extensions" : [ "SPV_INTEL_fpga_reg" ], "version" : "None" }, + { + "enumerant" : "DotProductInputAllKHR", + "value" : 6016, + "extensions" : [ "SPV_KHR_integer_dot_product" ], + "version" : "None" + }, + { + "enumerant" : "DotProductInput4x8BitKHR", + "value" : 6017, + "capabilities" : [ "Int8" ], + "extensions" : [ "SPV_KHR_integer_dot_product" ], + "version" : "None" + }, + { + "enumerant" : "DotProductInput4x8BitPackedKHR", + "value" : 6018, + "extensions" : [ "SPV_KHR_integer_dot_product" ], + "version" : "None" + }, + { + "enumerant" : "DotProductKHR", + "value" : 6019, + "extensions" : [ "SPV_KHR_integer_dot_product" ], + "version" : "None" + }, + { + "enumerant" : "BitInstructions", + "value" : 6025, + "extensions" : [ "SPV_KHR_bit_instructions" ], + "version" : "None" + }, { "enumerant" : "AtomicFloat32AddEXT", "value" : 6033, @@ -11647,6 +13420,25 @@ "capabilities" : [ "Shader" ], "extensions" : [ "SPV_EXT_shader_atomic_float_add" ], "version" : "None" + }, + { + "enumerant" : "LongConstantCompositeINTEL", + "value" : 6089, + "extensions" : [ "SPV_INTEL_long_constant_composite" ], + "version" : "None" + }, + { + "enumerant" : "AtomicFloat16AddEXT", + "value" : 6095, + "capabilities" : [ "Shader" ], + "extensions" : [ "SPV_EXT_shader_atomic_float16_add" ], + "version" : "None" + }, + { + "enumerant" : "DebugInfoModuleINTEL", + "value" : 6114, + "extensions" : [ "SPV_INTEL_debug_module" ], + "version" : "None" } ] }, @@ -11657,13 +13449,13 @@ { "enumerant" : "RayQueryCandidateIntersectionKHR", "value" : 0, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "version" : "None" }, { "enumerant" : "RayQueryCommittedIntersectionKHR", "value" : 1, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "version" : "None" } ] @@ -11675,19 +13467,19 @@ { "enumerant" : "RayQueryCommittedIntersectionNoneKHR", "value" : 0, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "version" : "None" }, { "enumerant" : "RayQueryCommittedIntersectionTriangleKHR", "value" : 1, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "version" : "None" }, { "enumerant" : "RayQueryCommittedIntersectionGeneratedKHR", "value" : 2, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "version" : "None" } ] @@ -11699,13 +13491,25 @@ { "enumerant" : "RayQueryCandidateIntersectionTriangleKHR", "value" : 0, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], "version" : "None" }, { "enumerant" : "RayQueryCandidateIntersectionAABBKHR", "value" : 1, - "capabilities" : [ "RayQueryProvisionalKHR" ], + "capabilities" : [ "RayQueryKHR" ], + "version" : "None" + } + ] + }, + { + "category" : "ValueEnum", + "kind" : "PackedVectorFormat", + "enumerants" : [ + { + "enumerant" : "PackedVectorFormat4x8BitKHR", + "value" : 0, + "capabilities" : [ "DotProductInput4x8BitPackedKHR" ], "version" : "None" } ] diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.cs b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.cs index 0419c0f7d0..859f0e7c48 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.cs +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.cs @@ -61,6 +61,7 @@ namespace Spv OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, + CPP_for_OpenCL = 6, } public enum ExecutionModel @@ -146,6 +147,7 @@ namespace Spv SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, + SubgroupUniformControlFlowKHR = 4421, PostDepthCoverage = 4446, DenormPreserve = 4459, DenormFlushToZero = 4460, @@ -164,10 +166,16 @@ namespace Spv SampleInterlockUnorderedEXT = 5369, ShadingRateInterlockOrderedEXT = 5370, ShadingRateInterlockUnorderedEXT = 5371, + SharedLocalMemorySizeINTEL = 5618, + RoundingModeRTPINTEL = 5620, + RoundingModeRTNINTEL = 5621, + FloatingPointModeALTINTEL = 5622, + FloatingPointModeIEEEINTEL = 5623, MaxWorkgroupSizeINTEL = 5893, MaxWorkDimINTEL = 5894, NoGlobalOffsetINTEL = 5895, NumSIMDWorkitemsINTEL = 5896, + SchedulerTargetFmaxMhzINTEL = 5903, } public enum StorageClass @@ -200,6 +208,8 @@ namespace Spv PhysicalStorageBuffer = 5349, PhysicalStorageBufferEXT = 5349, CodeSectionINTEL = 5605, + DeviceOnlyINTEL = 5936, + HostOnlyINTEL = 5937, } public enum Dim @@ -371,6 +381,8 @@ namespace Spv NSZ = 2, AllowRecip = 3, Fast = 4, + AllowContractFastINTEL = 16, + AllowReassocINTEL = 17, } public enum FPFastMathModeMask @@ -381,6 +393,8 @@ namespace Spv NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, + AllowContractFastINTEL = 0x00010000, + AllowReassocINTEL = 0x00020000, } public enum FPRoundingMode @@ -395,6 +409,7 @@ namespace Spv { Export = 0, Import = 1, + LinkOnceODR = 2, } public enum AccessQualifier @@ -482,12 +497,22 @@ namespace Spv RestrictPointerEXT = 5355, AliasedPointer = 5356, AliasedPointerEXT = 5356, + SIMTCallINTEL = 5599, ReferencedIndirectlyINTEL = 5602, + ClobberINTEL = 5607, + SideEffectsINTEL = 5608, + VectorComputeVariableINTEL = 5624, + FuncParamIOKindINTEL = 5625, + VectorComputeFunctionINTEL = 5626, + StackCallINTEL = 5627, + GlobalVariableOffsetINTEL = 5628, CounterBuffer = 5634, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, UserSemantic = 5635, UserTypeGOOGLE = 5636, + FunctionRoundingModeINTEL = 5822, + FunctionDenormModeINTEL = 5823, RegisterINTEL = 5825, MemoryINTEL = 5826, NumbanksINTEL = 5827, @@ -500,6 +525,17 @@ namespace Spv MergeINTEL = 5834, BankBitsINTEL = 5835, ForcePow2DepthINTEL = 5836, + BurstCoalesceINTEL = 5899, + CacheSizeINTEL = 5900, + DontStaticallyCoalesceINTEL = 5901, + PrefetchINTEL = 5902, + StallEnableINTEL = 5905, + FuseLoopsInFunctionINTEL = 5907, + BufferLocationINTEL = 5921, + IOPipeStorageINTEL = 5944, + FunctionFloatingPointModeINTEL = 6080, + SingleElementVectorINTEL = 6085, + VectorComputeCallableFunctionINTEL = 6087, } public enum BuiltIn @@ -612,7 +648,6 @@ namespace Spv ObjectToWorldNV = 5330, WorldToObjectKHR = 5331, WorldToObjectNV = 5331, - HitTKHR = 5332, HitTNV = 5332, HitKindKHR = 5333, HitKindNV = 5333, @@ -656,6 +691,7 @@ namespace Spv LoopCoalesceINTEL = 20, MaxInterleavingINTEL = 21, SpeculatedIterationsINTEL = 22, + NoFusionINTEL = 23, } public enum LoopControlMask @@ -677,6 +713,7 @@ namespace Spv LoopCoalesceINTEL = 0x00100000, MaxInterleavingINTEL = 0x00200000, SpeculatedIterationsINTEL = 0x00400000, + NoFusionINTEL = 0x00800000, } public enum FunctionControlShift @@ -881,6 +918,9 @@ namespace Spv FragmentShadingRateKHR = 4422, SubgroupBallotKHR = 4423, DrawParameters = 4427, + WorkgroupMemoryExplicitLayoutKHR = 4428, + WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, + WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, @@ -903,7 +943,9 @@ namespace Spv RoundingModeRTE = 4467, RoundingModeRTZ = 4468, RayQueryProvisionalKHR = 4471, - RayTraversalPrimitiveCullingProvisionalKHR = 4478, + RayQueryKHR = 4472, + RayTraversalPrimitiveCullingKHR = 4478, + RayTracingKHR = 4479, Float16ImageAMD = 5008, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, @@ -969,21 +1011,50 @@ namespace Spv SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, SubgroupImageMediaBlockIOINTEL = 5579, + RoundToInfinityINTEL = 5582, + FloatingPointModeINTEL = 5583, IntegerFunctions2INTEL = 5584, FunctionPointersINTEL = 5603, IndirectReferencesINTEL = 5604, + AsmINTEL = 5606, + AtomicFloat32MinMaxEXT = 5612, + AtomicFloat64MinMaxEXT = 5613, + AtomicFloat16MinMaxEXT = 5616, + VectorComputeINTEL = 5617, + VectorAnyINTEL = 5619, + ExpectAssumeKHR = 5629, SubgroupAvcMotionEstimationINTEL = 5696, SubgroupAvcMotionEstimationIntraINTEL = 5697, SubgroupAvcMotionEstimationChromaINTEL = 5698, + VariableLengthArrayINTEL = 5817, + FunctionFloatControlINTEL = 5821, FPGAMemoryAttributesINTEL = 5824, + FPFastMathModeINTEL = 5837, + ArbitraryPrecisionIntegersINTEL = 5844, + ArbitraryPrecisionFloatingPointINTEL = 5845, UnstructuredLoopControlsINTEL = 5886, FPGALoopControlsINTEL = 5888, KernelAttributesINTEL = 5892, FPGAKernelAttributesINTEL = 5897, + FPGAMemoryAccessesINTEL = 5898, + FPGAClusterAttributesINTEL = 5904, + LoopFuseINTEL = 5906, + FPGABufferLocationINTEL = 5920, + ArbitraryPrecisionFixedPointINTEL = 5922, + USMStorageClassesINTEL = 5935, + IOPipesINTEL = 5943, BlockingPipesINTEL = 5945, FPGARegINTEL = 5948, + DotProductInputAllKHR = 6016, + DotProductInput4x8BitKHR = 6017, + DotProductInput4x8BitPackedKHR = 6018, + DotProductKHR = 6019, + BitInstructions = 6025, AtomicFloat32AddEXT = 6033, AtomicFloat64AddEXT = 6034, + LongConstantCompositeINTEL = 6089, + AtomicFloat16AddEXT = 6095, + DebugInfoModuleINTEL = 6114, } public enum RayFlagsShift @@ -1051,6 +1122,43 @@ namespace Spv Horizontal4Pixels = 0x00000008, } + public enum FPDenormMode + { + Preserve = 0, + FlushToZero = 1, + } + + public enum FPOperationMode + { + IEEE = 0, + ALT = 1, + } + + public enum QuantizationModes + { + TRN = 0, + TRN_ZERO = 1, + RND = 2, + RND_ZERO = 3, + RND_INF = 4, + RND_MIN_INF = 5, + RND_CONV = 6, + RND_CONV_ODD = 7, + } + + public enum OverflowModes + { + WRAP = 0, + SAT = 1, + SAT_ZERO = 2, + SAT_SYM = 3, + } + + public enum PackedVectorFormat + { + PackedVectorFormat4x8BitKHR = 0, + } + public enum Op { OpNop = 0, @@ -1404,7 +1512,18 @@ namespace Spv OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, - OpTypeRayQueryProvisionalKHR = 4472, + OpTraceRayKHR = 4445, + OpExecuteCallableKHR = 4446, + OpConvertUToAccelerationStructureKHR = 4447, + OpIgnoreIntersectionKHR = 4448, + OpTerminateRayKHR = 4449, + OpSDotKHR = 4450, + OpUDotKHR = 4451, + OpSUDotKHR = 4452, + OpSDotAccSatKHR = 4453, + OpUDotAccSatKHR = 4454, + OpSUDotAccSatKHR = 4455, + OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, @@ -1427,15 +1546,11 @@ namespace Spv OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionKHR = 5334, OpReportIntersectionNV = 5334, - OpIgnoreIntersectionKHR = 5335, OpIgnoreIntersectionNV = 5335, - OpTerminateRayKHR = 5336, OpTerminateRayNV = 5336, OpTraceNV = 5337, - OpTraceRayKHR = 5337, OpTypeAccelerationStructureKHR = 5341, OpTypeAccelerationStructureNV = 5341, - OpExecuteCallableKHR = 5344, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, @@ -1470,8 +1585,15 @@ namespace Spv OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, - OpFunctionPointerINTEL = 5600, + OpConstFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, + OpAsmTargetINTEL = 5609, + OpAsmINTEL = 5610, + OpAsmCallINTEL = 5611, + OpAtomicFMinEXT = 5614, + OpAtomicFMaxEXT = 5615, + OpAssumeTrueKHR = 5630, + OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, @@ -1594,7 +1716,64 @@ namespace Spv OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, + OpVariableLengthArrayINTEL = 5818, + OpSaveMemoryINTEL = 5819, + OpRestoreMemoryINTEL = 5820, + OpArbitraryFloatSinCosPiINTEL = 5840, + OpArbitraryFloatCastINTEL = 5841, + OpArbitraryFloatCastFromIntINTEL = 5842, + OpArbitraryFloatCastToIntINTEL = 5843, + OpArbitraryFloatAddINTEL = 5846, + OpArbitraryFloatSubINTEL = 5847, + OpArbitraryFloatMulINTEL = 5848, + OpArbitraryFloatDivINTEL = 5849, + OpArbitraryFloatGTINTEL = 5850, + OpArbitraryFloatGEINTEL = 5851, + OpArbitraryFloatLTINTEL = 5852, + OpArbitraryFloatLEINTEL = 5853, + OpArbitraryFloatEQINTEL = 5854, + OpArbitraryFloatRecipINTEL = 5855, + OpArbitraryFloatRSqrtINTEL = 5856, + OpArbitraryFloatCbrtINTEL = 5857, + OpArbitraryFloatHypotINTEL = 5858, + OpArbitraryFloatSqrtINTEL = 5859, + OpArbitraryFloatLogINTEL = 5860, + OpArbitraryFloatLog2INTEL = 5861, + OpArbitraryFloatLog10INTEL = 5862, + OpArbitraryFloatLog1pINTEL = 5863, + OpArbitraryFloatExpINTEL = 5864, + OpArbitraryFloatExp2INTEL = 5865, + OpArbitraryFloatExp10INTEL = 5866, + OpArbitraryFloatExpm1INTEL = 5867, + OpArbitraryFloatSinINTEL = 5868, + OpArbitraryFloatCosINTEL = 5869, + OpArbitraryFloatSinCosINTEL = 5870, + OpArbitraryFloatSinPiINTEL = 5871, + OpArbitraryFloatCosPiINTEL = 5872, + OpArbitraryFloatASinINTEL = 5873, + OpArbitraryFloatASinPiINTEL = 5874, + OpArbitraryFloatACosINTEL = 5875, + OpArbitraryFloatACosPiINTEL = 5876, + OpArbitraryFloatATanINTEL = 5877, + OpArbitraryFloatATanPiINTEL = 5878, + OpArbitraryFloatATan2INTEL = 5879, + OpArbitraryFloatPowINTEL = 5880, + OpArbitraryFloatPowRINTEL = 5881, + OpArbitraryFloatPowNINTEL = 5882, OpLoopControlINTEL = 5887, + OpFixedSqrtINTEL = 5923, + OpFixedRecipINTEL = 5924, + OpFixedRsqrtINTEL = 5925, + OpFixedSinINTEL = 5926, + OpFixedCosINTEL = 5927, + OpFixedSinCosINTEL = 5928, + OpFixedSinPiINTEL = 5929, + OpFixedCosPiINTEL = 5930, + OpFixedSinCosPiINTEL = 5931, + OpFixedLogINTEL = 5932, + OpFixedExpINTEL = 5933, + OpPtrCastToCrossWorkgroupINTEL = 5934, + OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, @@ -1616,6 +1795,10 @@ namespace Spv OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, + OpTypeBufferSurfaceINTEL = 6086, + OpTypeStructContinuedINTEL = 6090, + OpConstantCompositeContinuedINTEL = 6091, + OpSpecConstantCompositeContinuedINTEL = 6092, } } } diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.h b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.h index 4e36b3a4c4..34f90d3183 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.h +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.h @@ -69,6 +69,7 @@ typedef enum SpvSourceLanguage_ { SpvSourceLanguageOpenCL_C = 3, SpvSourceLanguageOpenCL_CPP = 4, SpvSourceLanguageHLSL = 5, + SpvSourceLanguageCPP_for_OpenCL = 6, SpvSourceLanguageMax = 0x7fffffff, } SpvSourceLanguage; @@ -154,6 +155,7 @@ typedef enum SpvExecutionMode_ { SpvExecutionModeSubgroupsPerWorkgroupId = 37, SpvExecutionModeLocalSizeId = 38, SpvExecutionModeLocalSizeHintId = 39, + SpvExecutionModeSubgroupUniformControlFlowKHR = 4421, SpvExecutionModePostDepthCoverage = 4446, SpvExecutionModeDenormPreserve = 4459, SpvExecutionModeDenormFlushToZero = 4460, @@ -172,10 +174,16 @@ typedef enum SpvExecutionMode_ { SpvExecutionModeSampleInterlockUnorderedEXT = 5369, SpvExecutionModeShadingRateInterlockOrderedEXT = 5370, SpvExecutionModeShadingRateInterlockUnorderedEXT = 5371, + SpvExecutionModeSharedLocalMemorySizeINTEL = 5618, + SpvExecutionModeRoundingModeRTPINTEL = 5620, + SpvExecutionModeRoundingModeRTNINTEL = 5621, + SpvExecutionModeFloatingPointModeALTINTEL = 5622, + SpvExecutionModeFloatingPointModeIEEEINTEL = 5623, SpvExecutionModeMaxWorkgroupSizeINTEL = 5893, SpvExecutionModeMaxWorkDimINTEL = 5894, SpvExecutionModeNoGlobalOffsetINTEL = 5895, SpvExecutionModeNumSIMDWorkitemsINTEL = 5896, + SpvExecutionModeSchedulerTargetFmaxMhzINTEL = 5903, SpvExecutionModeMax = 0x7fffffff, } SpvExecutionMode; @@ -208,6 +216,8 @@ typedef enum SpvStorageClass_ { SpvStorageClassPhysicalStorageBuffer = 5349, SpvStorageClassPhysicalStorageBufferEXT = 5349, SpvStorageClassCodeSectionINTEL = 5605, + SpvStorageClassDeviceOnlyINTEL = 5936, + SpvStorageClassHostOnlyINTEL = 5937, SpvStorageClassMax = 0x7fffffff, } SpvStorageClass; @@ -378,6 +388,8 @@ typedef enum SpvFPFastMathModeShift_ { SpvFPFastMathModeNSZShift = 2, SpvFPFastMathModeAllowRecipShift = 3, SpvFPFastMathModeFastShift = 4, + SpvFPFastMathModeAllowContractFastINTELShift = 16, + SpvFPFastMathModeAllowReassocINTELShift = 17, SpvFPFastMathModeMax = 0x7fffffff, } SpvFPFastMathModeShift; @@ -388,6 +400,8 @@ typedef enum SpvFPFastMathModeMask_ { SpvFPFastMathModeNSZMask = 0x00000004, SpvFPFastMathModeAllowRecipMask = 0x00000008, SpvFPFastMathModeFastMask = 0x00000010, + SpvFPFastMathModeAllowContractFastINTELMask = 0x00010000, + SpvFPFastMathModeAllowReassocINTELMask = 0x00020000, } SpvFPFastMathModeMask; typedef enum SpvFPRoundingMode_ { @@ -401,6 +415,7 @@ typedef enum SpvFPRoundingMode_ { typedef enum SpvLinkageType_ { SpvLinkageTypeExport = 0, SpvLinkageTypeImport = 1, + SpvLinkageTypeLinkOnceODR = 2, SpvLinkageTypeMax = 0x7fffffff, } SpvLinkageType; @@ -488,12 +503,22 @@ typedef enum SpvDecoration_ { SpvDecorationRestrictPointerEXT = 5355, SpvDecorationAliasedPointer = 5356, SpvDecorationAliasedPointerEXT = 5356, + SpvDecorationSIMTCallINTEL = 5599, SpvDecorationReferencedIndirectlyINTEL = 5602, + SpvDecorationClobberINTEL = 5607, + SpvDecorationSideEffectsINTEL = 5608, + SpvDecorationVectorComputeVariableINTEL = 5624, + SpvDecorationFuncParamIOKindINTEL = 5625, + SpvDecorationVectorComputeFunctionINTEL = 5626, + SpvDecorationStackCallINTEL = 5627, + SpvDecorationGlobalVariableOffsetINTEL = 5628, SpvDecorationCounterBuffer = 5634, SpvDecorationHlslCounterBufferGOOGLE = 5634, SpvDecorationHlslSemanticGOOGLE = 5635, SpvDecorationUserSemantic = 5635, SpvDecorationUserTypeGOOGLE = 5636, + SpvDecorationFunctionRoundingModeINTEL = 5822, + SpvDecorationFunctionDenormModeINTEL = 5823, SpvDecorationRegisterINTEL = 5825, SpvDecorationMemoryINTEL = 5826, SpvDecorationNumbanksINTEL = 5827, @@ -506,6 +531,17 @@ typedef enum SpvDecoration_ { SpvDecorationMergeINTEL = 5834, SpvDecorationBankBitsINTEL = 5835, SpvDecorationForcePow2DepthINTEL = 5836, + SpvDecorationBurstCoalesceINTEL = 5899, + SpvDecorationCacheSizeINTEL = 5900, + SpvDecorationDontStaticallyCoalesceINTEL = 5901, + SpvDecorationPrefetchINTEL = 5902, + SpvDecorationStallEnableINTEL = 5905, + SpvDecorationFuseLoopsInFunctionINTEL = 5907, + SpvDecorationBufferLocationINTEL = 5921, + SpvDecorationIOPipeStorageINTEL = 5944, + SpvDecorationFunctionFloatingPointModeINTEL = 6080, + SpvDecorationSingleElementVectorINTEL = 6085, + SpvDecorationVectorComputeCallableFunctionINTEL = 6087, SpvDecorationMax = 0x7fffffff, } SpvDecoration; @@ -618,7 +654,6 @@ typedef enum SpvBuiltIn_ { SpvBuiltInObjectToWorldNV = 5330, SpvBuiltInWorldToObjectKHR = 5331, SpvBuiltInWorldToObjectNV = 5331, - SpvBuiltInHitTKHR = 5332, SpvBuiltInHitTNV = 5332, SpvBuiltInHitKindKHR = 5333, SpvBuiltInHitKindNV = 5333, @@ -661,6 +696,7 @@ typedef enum SpvLoopControlShift_ { SpvLoopControlLoopCoalesceINTELShift = 20, SpvLoopControlMaxInterleavingINTELShift = 21, SpvLoopControlSpeculatedIterationsINTELShift = 22, + SpvLoopControlNoFusionINTELShift = 23, SpvLoopControlMax = 0x7fffffff, } SpvLoopControlShift; @@ -682,6 +718,7 @@ typedef enum SpvLoopControlMask_ { SpvLoopControlLoopCoalesceINTELMask = 0x00100000, SpvLoopControlMaxInterleavingINTELMask = 0x00200000, SpvLoopControlSpeculatedIterationsINTELMask = 0x00400000, + SpvLoopControlNoFusionINTELMask = 0x00800000, } SpvLoopControlMask; typedef enum SpvFunctionControlShift_ { @@ -881,6 +918,9 @@ typedef enum SpvCapability_ { SpvCapabilityFragmentShadingRateKHR = 4422, SpvCapabilitySubgroupBallotKHR = 4423, SpvCapabilityDrawParameters = 4427, + SpvCapabilityWorkgroupMemoryExplicitLayoutKHR = 4428, + SpvCapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, + SpvCapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SpvCapabilitySubgroupVoteKHR = 4431, SpvCapabilityStorageBuffer16BitAccess = 4433, SpvCapabilityStorageUniformBufferBlock16 = 4433, @@ -903,7 +943,9 @@ typedef enum SpvCapability_ { SpvCapabilityRoundingModeRTE = 4467, SpvCapabilityRoundingModeRTZ = 4468, SpvCapabilityRayQueryProvisionalKHR = 4471, - SpvCapabilityRayTraversalPrimitiveCullingProvisionalKHR = 4478, + SpvCapabilityRayQueryKHR = 4472, + SpvCapabilityRayTraversalPrimitiveCullingKHR = 4478, + SpvCapabilityRayTracingKHR = 4479, SpvCapabilityFloat16ImageAMD = 5008, SpvCapabilityImageGatherBiasLodAMD = 5009, SpvCapabilityFragmentMaskAMD = 5010, @@ -969,21 +1011,50 @@ typedef enum SpvCapability_ { SpvCapabilitySubgroupBufferBlockIOINTEL = 5569, SpvCapabilitySubgroupImageBlockIOINTEL = 5570, SpvCapabilitySubgroupImageMediaBlockIOINTEL = 5579, + SpvCapabilityRoundToInfinityINTEL = 5582, + SpvCapabilityFloatingPointModeINTEL = 5583, SpvCapabilityIntegerFunctions2INTEL = 5584, SpvCapabilityFunctionPointersINTEL = 5603, SpvCapabilityIndirectReferencesINTEL = 5604, + SpvCapabilityAsmINTEL = 5606, + SpvCapabilityAtomicFloat32MinMaxEXT = 5612, + SpvCapabilityAtomicFloat64MinMaxEXT = 5613, + SpvCapabilityAtomicFloat16MinMaxEXT = 5616, + SpvCapabilityVectorComputeINTEL = 5617, + SpvCapabilityVectorAnyINTEL = 5619, + SpvCapabilityExpectAssumeKHR = 5629, SpvCapabilitySubgroupAvcMotionEstimationINTEL = 5696, SpvCapabilitySubgroupAvcMotionEstimationIntraINTEL = 5697, SpvCapabilitySubgroupAvcMotionEstimationChromaINTEL = 5698, + SpvCapabilityVariableLengthArrayINTEL = 5817, + SpvCapabilityFunctionFloatControlINTEL = 5821, SpvCapabilityFPGAMemoryAttributesINTEL = 5824, + SpvCapabilityFPFastMathModeINTEL = 5837, + SpvCapabilityArbitraryPrecisionIntegersINTEL = 5844, + SpvCapabilityArbitraryPrecisionFloatingPointINTEL = 5845, SpvCapabilityUnstructuredLoopControlsINTEL = 5886, SpvCapabilityFPGALoopControlsINTEL = 5888, SpvCapabilityKernelAttributesINTEL = 5892, SpvCapabilityFPGAKernelAttributesINTEL = 5897, + SpvCapabilityFPGAMemoryAccessesINTEL = 5898, + SpvCapabilityFPGAClusterAttributesINTEL = 5904, + SpvCapabilityLoopFuseINTEL = 5906, + SpvCapabilityFPGABufferLocationINTEL = 5920, + SpvCapabilityArbitraryPrecisionFixedPointINTEL = 5922, + SpvCapabilityUSMStorageClassesINTEL = 5935, + SpvCapabilityIOPipesINTEL = 5943, SpvCapabilityBlockingPipesINTEL = 5945, SpvCapabilityFPGARegINTEL = 5948, + SpvCapabilityDotProductInputAllKHR = 6016, + SpvCapabilityDotProductInput4x8BitKHR = 6017, + SpvCapabilityDotProductInput4x8BitPackedKHR = 6018, + SpvCapabilityDotProductKHR = 6019, + SpvCapabilityBitInstructions = 6025, SpvCapabilityAtomicFloat32AddEXT = 6033, SpvCapabilityAtomicFloat64AddEXT = 6034, + SpvCapabilityLongConstantCompositeINTEL = 6089, + SpvCapabilityAtomicFloat16AddEXT = 6095, + SpvCapabilityDebugInfoModuleINTEL = 6114, SpvCapabilityMax = 0x7fffffff, } SpvCapability; @@ -1050,6 +1121,43 @@ typedef enum SpvFragmentShadingRateMask_ { SpvFragmentShadingRateHorizontal4PixelsMask = 0x00000008, } SpvFragmentShadingRateMask; +typedef enum SpvFPDenormMode_ { + SpvFPDenormModePreserve = 0, + SpvFPDenormModeFlushToZero = 1, + SpvFPDenormModeMax = 0x7fffffff, +} SpvFPDenormMode; + +typedef enum SpvFPOperationMode_ { + SpvFPOperationModeIEEE = 0, + SpvFPOperationModeALT = 1, + SpvFPOperationModeMax = 0x7fffffff, +} SpvFPOperationMode; + +typedef enum SpvQuantizationModes_ { + SpvQuantizationModesTRN = 0, + SpvQuantizationModesTRN_ZERO = 1, + SpvQuantizationModesRND = 2, + SpvQuantizationModesRND_ZERO = 3, + SpvQuantizationModesRND_INF = 4, + SpvQuantizationModesRND_MIN_INF = 5, + SpvQuantizationModesRND_CONV = 6, + SpvQuantizationModesRND_CONV_ODD = 7, + SpvQuantizationModesMax = 0x7fffffff, +} SpvQuantizationModes; + +typedef enum SpvOverflowModes_ { + SpvOverflowModesWRAP = 0, + SpvOverflowModesSAT = 1, + SpvOverflowModesSAT_ZERO = 2, + SpvOverflowModesSAT_SYM = 3, + SpvOverflowModesMax = 0x7fffffff, +} SpvOverflowModes; + +typedef enum SpvPackedVectorFormat_ { + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR = 0, + SpvPackedVectorFormatMax = 0x7fffffff, +} SpvPackedVectorFormat; + typedef enum SpvOp_ { SpvOpNop = 0, SpvOpUndef = 1, @@ -1402,7 +1510,18 @@ typedef enum SpvOp_ { SpvOpSubgroupAnyKHR = 4429, SpvOpSubgroupAllEqualKHR = 4430, SpvOpSubgroupReadInvocationKHR = 4432, - SpvOpTypeRayQueryProvisionalKHR = 4472, + SpvOpTraceRayKHR = 4445, + SpvOpExecuteCallableKHR = 4446, + SpvOpConvertUToAccelerationStructureKHR = 4447, + SpvOpIgnoreIntersectionKHR = 4448, + SpvOpTerminateRayKHR = 4449, + SpvOpSDotKHR = 4450, + SpvOpUDotKHR = 4451, + SpvOpSUDotKHR = 4452, + SpvOpSDotAccSatKHR = 4453, + SpvOpUDotAccSatKHR = 4454, + SpvOpSUDotAccSatKHR = 4455, + SpvOpTypeRayQueryKHR = 4472, SpvOpRayQueryInitializeKHR = 4473, SpvOpRayQueryTerminateKHR = 4474, SpvOpRayQueryGenerateIntersectionKHR = 4475, @@ -1425,15 +1544,11 @@ typedef enum SpvOp_ { SpvOpWritePackedPrimitiveIndices4x8NV = 5299, SpvOpReportIntersectionKHR = 5334, SpvOpReportIntersectionNV = 5334, - SpvOpIgnoreIntersectionKHR = 5335, SpvOpIgnoreIntersectionNV = 5335, - SpvOpTerminateRayKHR = 5336, SpvOpTerminateRayNV = 5336, SpvOpTraceNV = 5337, - SpvOpTraceRayKHR = 5337, SpvOpTypeAccelerationStructureKHR = 5341, SpvOpTypeAccelerationStructureNV = 5341, - SpvOpExecuteCallableKHR = 5344, SpvOpExecuteCallableNV = 5344, SpvOpTypeCooperativeMatrixNV = 5358, SpvOpCooperativeMatrixLoadNV = 5359, @@ -1468,8 +1583,15 @@ typedef enum SpvOp_ { SpvOpUSubSatINTEL = 5596, SpvOpIMul32x16INTEL = 5597, SpvOpUMul32x16INTEL = 5598, - SpvOpFunctionPointerINTEL = 5600, + SpvOpConstFunctionPointerINTEL = 5600, SpvOpFunctionPointerCallINTEL = 5601, + SpvOpAsmTargetINTEL = 5609, + SpvOpAsmINTEL = 5610, + SpvOpAsmCallINTEL = 5611, + SpvOpAtomicFMinEXT = 5614, + SpvOpAtomicFMaxEXT = 5615, + SpvOpAssumeTrueKHR = 5630, + SpvOpExpectKHR = 5631, SpvOpDecorateString = 5632, SpvOpDecorateStringGOOGLE = 5632, SpvOpMemberDecorateString = 5633, @@ -1592,7 +1714,64 @@ typedef enum SpvOp_ { SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, SpvOpSubgroupAvcSicGetInterRawSadsINTEL = 5816, + SpvOpVariableLengthArrayINTEL = 5818, + SpvOpSaveMemoryINTEL = 5819, + SpvOpRestoreMemoryINTEL = 5820, + SpvOpArbitraryFloatSinCosPiINTEL = 5840, + SpvOpArbitraryFloatCastINTEL = 5841, + SpvOpArbitraryFloatCastFromIntINTEL = 5842, + SpvOpArbitraryFloatCastToIntINTEL = 5843, + SpvOpArbitraryFloatAddINTEL = 5846, + SpvOpArbitraryFloatSubINTEL = 5847, + SpvOpArbitraryFloatMulINTEL = 5848, + SpvOpArbitraryFloatDivINTEL = 5849, + SpvOpArbitraryFloatGTINTEL = 5850, + SpvOpArbitraryFloatGEINTEL = 5851, + SpvOpArbitraryFloatLTINTEL = 5852, + SpvOpArbitraryFloatLEINTEL = 5853, + SpvOpArbitraryFloatEQINTEL = 5854, + SpvOpArbitraryFloatRecipINTEL = 5855, + SpvOpArbitraryFloatRSqrtINTEL = 5856, + SpvOpArbitraryFloatCbrtINTEL = 5857, + SpvOpArbitraryFloatHypotINTEL = 5858, + SpvOpArbitraryFloatSqrtINTEL = 5859, + SpvOpArbitraryFloatLogINTEL = 5860, + SpvOpArbitraryFloatLog2INTEL = 5861, + SpvOpArbitraryFloatLog10INTEL = 5862, + SpvOpArbitraryFloatLog1pINTEL = 5863, + SpvOpArbitraryFloatExpINTEL = 5864, + SpvOpArbitraryFloatExp2INTEL = 5865, + SpvOpArbitraryFloatExp10INTEL = 5866, + SpvOpArbitraryFloatExpm1INTEL = 5867, + SpvOpArbitraryFloatSinINTEL = 5868, + SpvOpArbitraryFloatCosINTEL = 5869, + SpvOpArbitraryFloatSinCosINTEL = 5870, + SpvOpArbitraryFloatSinPiINTEL = 5871, + SpvOpArbitraryFloatCosPiINTEL = 5872, + SpvOpArbitraryFloatASinINTEL = 5873, + SpvOpArbitraryFloatASinPiINTEL = 5874, + SpvOpArbitraryFloatACosINTEL = 5875, + SpvOpArbitraryFloatACosPiINTEL = 5876, + SpvOpArbitraryFloatATanINTEL = 5877, + SpvOpArbitraryFloatATanPiINTEL = 5878, + SpvOpArbitraryFloatATan2INTEL = 5879, + SpvOpArbitraryFloatPowINTEL = 5880, + SpvOpArbitraryFloatPowRINTEL = 5881, + SpvOpArbitraryFloatPowNINTEL = 5882, SpvOpLoopControlINTEL = 5887, + SpvOpFixedSqrtINTEL = 5923, + SpvOpFixedRecipINTEL = 5924, + SpvOpFixedRsqrtINTEL = 5925, + SpvOpFixedSinINTEL = 5926, + SpvOpFixedCosINTEL = 5927, + SpvOpFixedSinCosINTEL = 5928, + SpvOpFixedSinPiINTEL = 5929, + SpvOpFixedCosPiINTEL = 5930, + SpvOpFixedSinCosPiINTEL = 5931, + SpvOpFixedLogINTEL = 5932, + SpvOpFixedExpINTEL = 5933, + SpvOpPtrCastToCrossWorkgroupINTEL = 5934, + SpvOpCrossWorkgroupCastToPtrINTEL = 5938, SpvOpReadPipeBlockingINTEL = 5946, SpvOpWritePipeBlockingINTEL = 5947, SpvOpFPGARegINTEL = 5949, @@ -1614,6 +1793,10 @@ typedef enum SpvOp_ { SpvOpRayQueryGetIntersectionObjectToWorldKHR = 6031, SpvOpRayQueryGetIntersectionWorldToObjectKHR = 6032, SpvOpAtomicFAddEXT = 6035, + SpvOpTypeBufferSurfaceINTEL = 6086, + SpvOpTypeStructContinuedINTEL = 6090, + SpvOpConstantCompositeContinuedINTEL = 6091, + SpvOpSpecConstantCompositeContinuedINTEL = 6092, SpvOpMax = 0x7fffffff, } SpvOp; @@ -1973,7 +2156,18 @@ inline void SpvHasResultAndType(SpvOp opcode, bool *hasResult, bool *hasResultTy case SpvOpSubgroupAnyKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAllEqualKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupReadInvocationKHR: *hasResult = true; *hasResultType = true; break; - case SpvOpTypeRayQueryProvisionalKHR: *hasResult = true; *hasResultType = false; break; + case SpvOpTraceRayKHR: *hasResult = false; *hasResultType = false; break; + case SpvOpExecuteCallableKHR: *hasResult = false; *hasResultType = false; break; + case SpvOpConvertUToAccelerationStructureKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpIgnoreIntersectionKHR: *hasResult = false; *hasResultType = false; break; + case SpvOpTerminateRayKHR: *hasResult = false; *hasResultType = false; break; + case SpvOpSDotKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpUDotKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpSUDotKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpSDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpUDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpSUDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case SpvOpTypeRayQueryKHR: *hasResult = true; *hasResultType = false; break; case SpvOpRayQueryInitializeKHR: *hasResult = false; *hasResultType = false; break; case SpvOpRayQueryTerminateKHR: *hasResult = false; *hasResultType = false; break; case SpvOpRayQueryGenerateIntersectionKHR: *hasResult = false; *hasResultType = false; break; @@ -2033,8 +2227,15 @@ inline void SpvHasResultAndType(SpvOp opcode, bool *hasResult, bool *hasResultTy case SpvOpUSubSatINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpIMul32x16INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUMul32x16INTEL: *hasResult = true; *hasResultType = true; break; - case SpvOpFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpConstFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFunctionPointerCallINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpAsmTargetINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpAsmINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpAsmCallINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpAtomicFMinEXT: *hasResult = true; *hasResultType = true; break; + case SpvOpAtomicFMaxEXT: *hasResult = true; *hasResultType = true; break; + case SpvOpAssumeTrueKHR: *hasResult = false; *hasResultType = false; break; + case SpvOpExpectKHR: *hasResult = true; *hasResultType = true; break; case SpvOpDecorateString: *hasResult = false; *hasResultType = false; break; case SpvOpMemberDecorateString: *hasResult = false; *hasResultType = false; break; case SpvOpVmeImageINTEL: *hasResult = true; *hasResultType = true; break; @@ -2155,7 +2356,64 @@ inline void SpvHasResultAndType(SpvOp opcode, bool *hasResult, bool *hasResultTy case SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetInterRawSadsINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpVariableLengthArrayINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpSaveMemoryINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpRestoreMemoryINTEL: *hasResult = false; *hasResultType = false; break; + case SpvOpArbitraryFloatSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatCastINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatCastFromIntINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatCastToIntINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatAddINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatSubINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatMulINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatDivINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatGTINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatGEINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatLTINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatLEINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatEQINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatRecipINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatRSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatCbrtINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatHypotINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatLogINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatLog2INTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatLog10INTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatLog1pINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatExpINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatExp2INTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatExp10INTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatExpm1INTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatSinINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatCosINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatSinCosINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatSinPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatASinINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatASinPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatACosINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatACosPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatATanINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatATanPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatATan2INTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatPowINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatPowRINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpArbitraryFloatPowNINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpLoopControlINTEL: *hasResult = false; *hasResultType = false; break; + case SpvOpFixedSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedRecipINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedRsqrtINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedSinINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedCosINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedSinCosINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedSinPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedLogINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpFixedExpINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpPtrCastToCrossWorkgroupINTEL: *hasResult = true; *hasResultType = true; break; + case SpvOpCrossWorkgroupCastToPtrINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpReadPipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpWritePipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFPGARegINTEL: *hasResult = true; *hasResultType = true; break; @@ -2177,6 +2435,10 @@ inline void SpvHasResultAndType(SpvOp opcode, bool *hasResult, bool *hasResultTy case SpvOpRayQueryGetIntersectionObjectToWorldKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionWorldToObjectKHR: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicFAddEXT: *hasResult = true; *hasResultType = true; break; + case SpvOpTypeBufferSurfaceINTEL: *hasResult = true; *hasResultType = false; break; + case SpvOpTypeStructContinuedINTEL: *hasResult = false; *hasResultType = false; break; + case SpvOpConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; + case SpvOpSpecConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; } } #endif /* SPV_ENABLE_UTILITY_CODE */ diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp index 988545c9d2..a0b35b3f15 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp @@ -65,6 +65,7 @@ enum SourceLanguage { SourceLanguageOpenCL_C = 3, SourceLanguageOpenCL_CPP = 4, SourceLanguageHLSL = 5, + SourceLanguageCPP_for_OpenCL = 6, SourceLanguageMax = 0x7fffffff, }; @@ -150,6 +151,7 @@ enum ExecutionMode { ExecutionModeSubgroupsPerWorkgroupId = 37, ExecutionModeLocalSizeId = 38, ExecutionModeLocalSizeHintId = 39, + ExecutionModeSubgroupUniformControlFlowKHR = 4421, ExecutionModePostDepthCoverage = 4446, ExecutionModeDenormPreserve = 4459, ExecutionModeDenormFlushToZero = 4460, @@ -168,10 +170,16 @@ enum ExecutionMode { ExecutionModeSampleInterlockUnorderedEXT = 5369, ExecutionModeShadingRateInterlockOrderedEXT = 5370, ExecutionModeShadingRateInterlockUnorderedEXT = 5371, + ExecutionModeSharedLocalMemorySizeINTEL = 5618, + ExecutionModeRoundingModeRTPINTEL = 5620, + ExecutionModeRoundingModeRTNINTEL = 5621, + ExecutionModeFloatingPointModeALTINTEL = 5622, + ExecutionModeFloatingPointModeIEEEINTEL = 5623, ExecutionModeMaxWorkgroupSizeINTEL = 5893, ExecutionModeMaxWorkDimINTEL = 5894, ExecutionModeNoGlobalOffsetINTEL = 5895, ExecutionModeNumSIMDWorkitemsINTEL = 5896, + ExecutionModeSchedulerTargetFmaxMhzINTEL = 5903, ExecutionModeMax = 0x7fffffff, }; @@ -204,6 +212,8 @@ enum StorageClass { StorageClassPhysicalStorageBuffer = 5349, StorageClassPhysicalStorageBufferEXT = 5349, StorageClassCodeSectionINTEL = 5605, + StorageClassDeviceOnlyINTEL = 5936, + StorageClassHostOnlyINTEL = 5937, StorageClassMax = 0x7fffffff, }; @@ -374,6 +384,8 @@ enum FPFastMathModeShift { FPFastMathModeNSZShift = 2, FPFastMathModeAllowRecipShift = 3, FPFastMathModeFastShift = 4, + FPFastMathModeAllowContractFastINTELShift = 16, + FPFastMathModeAllowReassocINTELShift = 17, FPFastMathModeMax = 0x7fffffff, }; @@ -384,6 +396,8 @@ enum FPFastMathModeMask { FPFastMathModeNSZMask = 0x00000004, FPFastMathModeAllowRecipMask = 0x00000008, FPFastMathModeFastMask = 0x00000010, + FPFastMathModeAllowContractFastINTELMask = 0x00010000, + FPFastMathModeAllowReassocINTELMask = 0x00020000, }; enum FPRoundingMode { @@ -397,6 +411,7 @@ enum FPRoundingMode { enum LinkageType { LinkageTypeExport = 0, LinkageTypeImport = 1, + LinkageTypeLinkOnceODR = 2, LinkageTypeMax = 0x7fffffff, }; @@ -484,12 +499,22 @@ enum Decoration { DecorationRestrictPointerEXT = 5355, DecorationAliasedPointer = 5356, DecorationAliasedPointerEXT = 5356, + DecorationSIMTCallINTEL = 5599, DecorationReferencedIndirectlyINTEL = 5602, + DecorationClobberINTEL = 5607, + DecorationSideEffectsINTEL = 5608, + DecorationVectorComputeVariableINTEL = 5624, + DecorationFuncParamIOKindINTEL = 5625, + DecorationVectorComputeFunctionINTEL = 5626, + DecorationStackCallINTEL = 5627, + DecorationGlobalVariableOffsetINTEL = 5628, DecorationCounterBuffer = 5634, DecorationHlslCounterBufferGOOGLE = 5634, DecorationHlslSemanticGOOGLE = 5635, DecorationUserSemantic = 5635, DecorationUserTypeGOOGLE = 5636, + DecorationFunctionRoundingModeINTEL = 5822, + DecorationFunctionDenormModeINTEL = 5823, DecorationRegisterINTEL = 5825, DecorationMemoryINTEL = 5826, DecorationNumbanksINTEL = 5827, @@ -502,6 +527,17 @@ enum Decoration { DecorationMergeINTEL = 5834, DecorationBankBitsINTEL = 5835, DecorationForcePow2DepthINTEL = 5836, + DecorationBurstCoalesceINTEL = 5899, + DecorationCacheSizeINTEL = 5900, + DecorationDontStaticallyCoalesceINTEL = 5901, + DecorationPrefetchINTEL = 5902, + DecorationStallEnableINTEL = 5905, + DecorationFuseLoopsInFunctionINTEL = 5907, + DecorationBufferLocationINTEL = 5921, + DecorationIOPipeStorageINTEL = 5944, + DecorationFunctionFloatingPointModeINTEL = 6080, + DecorationSingleElementVectorINTEL = 6085, + DecorationVectorComputeCallableFunctionINTEL = 6087, DecorationMax = 0x7fffffff, }; @@ -614,7 +650,6 @@ enum BuiltIn { BuiltInObjectToWorldNV = 5330, BuiltInWorldToObjectKHR = 5331, BuiltInWorldToObjectNV = 5331, - BuiltInHitTKHR = 5332, BuiltInHitTNV = 5332, BuiltInHitKindKHR = 5333, BuiltInHitKindNV = 5333, @@ -657,6 +692,7 @@ enum LoopControlShift { LoopControlLoopCoalesceINTELShift = 20, LoopControlMaxInterleavingINTELShift = 21, LoopControlSpeculatedIterationsINTELShift = 22, + LoopControlNoFusionINTELShift = 23, LoopControlMax = 0x7fffffff, }; @@ -678,6 +714,7 @@ enum LoopControlMask { LoopControlLoopCoalesceINTELMask = 0x00100000, LoopControlMaxInterleavingINTELMask = 0x00200000, LoopControlSpeculatedIterationsINTELMask = 0x00400000, + LoopControlNoFusionINTELMask = 0x00800000, }; enum FunctionControlShift { @@ -877,6 +914,9 @@ enum Capability { CapabilityFragmentShadingRateKHR = 4422, CapabilitySubgroupBallotKHR = 4423, CapabilityDrawParameters = 4427, + CapabilityWorkgroupMemoryExplicitLayoutKHR = 4428, + CapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, + CapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, CapabilitySubgroupVoteKHR = 4431, CapabilityStorageBuffer16BitAccess = 4433, CapabilityStorageUniformBufferBlock16 = 4433, @@ -899,7 +939,9 @@ enum Capability { CapabilityRoundingModeRTE = 4467, CapabilityRoundingModeRTZ = 4468, CapabilityRayQueryProvisionalKHR = 4471, - CapabilityRayTraversalPrimitiveCullingProvisionalKHR = 4478, + CapabilityRayQueryKHR = 4472, + CapabilityRayTraversalPrimitiveCullingKHR = 4478, + CapabilityRayTracingKHR = 4479, CapabilityFloat16ImageAMD = 5008, CapabilityImageGatherBiasLodAMD = 5009, CapabilityFragmentMaskAMD = 5010, @@ -965,21 +1007,50 @@ enum Capability { CapabilitySubgroupBufferBlockIOINTEL = 5569, CapabilitySubgroupImageBlockIOINTEL = 5570, CapabilitySubgroupImageMediaBlockIOINTEL = 5579, + CapabilityRoundToInfinityINTEL = 5582, + CapabilityFloatingPointModeINTEL = 5583, CapabilityIntegerFunctions2INTEL = 5584, CapabilityFunctionPointersINTEL = 5603, CapabilityIndirectReferencesINTEL = 5604, + CapabilityAsmINTEL = 5606, + CapabilityAtomicFloat32MinMaxEXT = 5612, + CapabilityAtomicFloat64MinMaxEXT = 5613, + CapabilityAtomicFloat16MinMaxEXT = 5616, + CapabilityVectorComputeINTEL = 5617, + CapabilityVectorAnyINTEL = 5619, + CapabilityExpectAssumeKHR = 5629, CapabilitySubgroupAvcMotionEstimationINTEL = 5696, CapabilitySubgroupAvcMotionEstimationIntraINTEL = 5697, CapabilitySubgroupAvcMotionEstimationChromaINTEL = 5698, + CapabilityVariableLengthArrayINTEL = 5817, + CapabilityFunctionFloatControlINTEL = 5821, CapabilityFPGAMemoryAttributesINTEL = 5824, + CapabilityFPFastMathModeINTEL = 5837, + CapabilityArbitraryPrecisionIntegersINTEL = 5844, + CapabilityArbitraryPrecisionFloatingPointINTEL = 5845, CapabilityUnstructuredLoopControlsINTEL = 5886, CapabilityFPGALoopControlsINTEL = 5888, CapabilityKernelAttributesINTEL = 5892, CapabilityFPGAKernelAttributesINTEL = 5897, + CapabilityFPGAMemoryAccessesINTEL = 5898, + CapabilityFPGAClusterAttributesINTEL = 5904, + CapabilityLoopFuseINTEL = 5906, + CapabilityFPGABufferLocationINTEL = 5920, + CapabilityArbitraryPrecisionFixedPointINTEL = 5922, + CapabilityUSMStorageClassesINTEL = 5935, + CapabilityIOPipesINTEL = 5943, CapabilityBlockingPipesINTEL = 5945, CapabilityFPGARegINTEL = 5948, + CapabilityDotProductInputAllKHR = 6016, + CapabilityDotProductInput4x8BitKHR = 6017, + CapabilityDotProductInput4x8BitPackedKHR = 6018, + CapabilityDotProductKHR = 6019, + CapabilityBitInstructions = 6025, CapabilityAtomicFloat32AddEXT = 6033, CapabilityAtomicFloat64AddEXT = 6034, + CapabilityLongConstantCompositeINTEL = 6089, + CapabilityAtomicFloat16AddEXT = 6095, + CapabilityDebugInfoModuleINTEL = 6114, CapabilityMax = 0x7fffffff, }; @@ -1046,6 +1117,43 @@ enum FragmentShadingRateMask { FragmentShadingRateHorizontal4PixelsMask = 0x00000008, }; +enum FPDenormMode { + FPDenormModePreserve = 0, + FPDenormModeFlushToZero = 1, + FPDenormModeMax = 0x7fffffff, +}; + +enum FPOperationMode { + FPOperationModeIEEE = 0, + FPOperationModeALT = 1, + FPOperationModeMax = 0x7fffffff, +}; + +enum QuantizationModes { + QuantizationModesTRN = 0, + QuantizationModesTRN_ZERO = 1, + QuantizationModesRND = 2, + QuantizationModesRND_ZERO = 3, + QuantizationModesRND_INF = 4, + QuantizationModesRND_MIN_INF = 5, + QuantizationModesRND_CONV = 6, + QuantizationModesRND_CONV_ODD = 7, + QuantizationModesMax = 0x7fffffff, +}; + +enum OverflowModes { + OverflowModesWRAP = 0, + OverflowModesSAT = 1, + OverflowModesSAT_ZERO = 2, + OverflowModesSAT_SYM = 3, + OverflowModesMax = 0x7fffffff, +}; + +enum PackedVectorFormat { + PackedVectorFormatPackedVectorFormat4x8BitKHR = 0, + PackedVectorFormatMax = 0x7fffffff, +}; + enum Op { OpNop = 0, OpUndef = 1, @@ -1398,7 +1506,18 @@ enum Op { OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, - OpTypeRayQueryProvisionalKHR = 4472, + OpTraceRayKHR = 4445, + OpExecuteCallableKHR = 4446, + OpConvertUToAccelerationStructureKHR = 4447, + OpIgnoreIntersectionKHR = 4448, + OpTerminateRayKHR = 4449, + OpSDotKHR = 4450, + OpUDotKHR = 4451, + OpSUDotKHR = 4452, + OpSDotAccSatKHR = 4453, + OpUDotAccSatKHR = 4454, + OpSUDotAccSatKHR = 4455, + OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, @@ -1421,15 +1540,11 @@ enum Op { OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionKHR = 5334, OpReportIntersectionNV = 5334, - OpIgnoreIntersectionKHR = 5335, OpIgnoreIntersectionNV = 5335, - OpTerminateRayKHR = 5336, OpTerminateRayNV = 5336, OpTraceNV = 5337, - OpTraceRayKHR = 5337, OpTypeAccelerationStructureKHR = 5341, OpTypeAccelerationStructureNV = 5341, - OpExecuteCallableKHR = 5344, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, @@ -1464,8 +1579,15 @@ enum Op { OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, - OpFunctionPointerINTEL = 5600, + OpConstFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, + OpAsmTargetINTEL = 5609, + OpAsmINTEL = 5610, + OpAsmCallINTEL = 5611, + OpAtomicFMinEXT = 5614, + OpAtomicFMaxEXT = 5615, + OpAssumeTrueKHR = 5630, + OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, @@ -1588,7 +1710,64 @@ enum Op { OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, + OpVariableLengthArrayINTEL = 5818, + OpSaveMemoryINTEL = 5819, + OpRestoreMemoryINTEL = 5820, + OpArbitraryFloatSinCosPiINTEL = 5840, + OpArbitraryFloatCastINTEL = 5841, + OpArbitraryFloatCastFromIntINTEL = 5842, + OpArbitraryFloatCastToIntINTEL = 5843, + OpArbitraryFloatAddINTEL = 5846, + OpArbitraryFloatSubINTEL = 5847, + OpArbitraryFloatMulINTEL = 5848, + OpArbitraryFloatDivINTEL = 5849, + OpArbitraryFloatGTINTEL = 5850, + OpArbitraryFloatGEINTEL = 5851, + OpArbitraryFloatLTINTEL = 5852, + OpArbitraryFloatLEINTEL = 5853, + OpArbitraryFloatEQINTEL = 5854, + OpArbitraryFloatRecipINTEL = 5855, + OpArbitraryFloatRSqrtINTEL = 5856, + OpArbitraryFloatCbrtINTEL = 5857, + OpArbitraryFloatHypotINTEL = 5858, + OpArbitraryFloatSqrtINTEL = 5859, + OpArbitraryFloatLogINTEL = 5860, + OpArbitraryFloatLog2INTEL = 5861, + OpArbitraryFloatLog10INTEL = 5862, + OpArbitraryFloatLog1pINTEL = 5863, + OpArbitraryFloatExpINTEL = 5864, + OpArbitraryFloatExp2INTEL = 5865, + OpArbitraryFloatExp10INTEL = 5866, + OpArbitraryFloatExpm1INTEL = 5867, + OpArbitraryFloatSinINTEL = 5868, + OpArbitraryFloatCosINTEL = 5869, + OpArbitraryFloatSinCosINTEL = 5870, + OpArbitraryFloatSinPiINTEL = 5871, + OpArbitraryFloatCosPiINTEL = 5872, + OpArbitraryFloatASinINTEL = 5873, + OpArbitraryFloatASinPiINTEL = 5874, + OpArbitraryFloatACosINTEL = 5875, + OpArbitraryFloatACosPiINTEL = 5876, + OpArbitraryFloatATanINTEL = 5877, + OpArbitraryFloatATanPiINTEL = 5878, + OpArbitraryFloatATan2INTEL = 5879, + OpArbitraryFloatPowINTEL = 5880, + OpArbitraryFloatPowRINTEL = 5881, + OpArbitraryFloatPowNINTEL = 5882, OpLoopControlINTEL = 5887, + OpFixedSqrtINTEL = 5923, + OpFixedRecipINTEL = 5924, + OpFixedRsqrtINTEL = 5925, + OpFixedSinINTEL = 5926, + OpFixedCosINTEL = 5927, + OpFixedSinCosINTEL = 5928, + OpFixedSinPiINTEL = 5929, + OpFixedCosPiINTEL = 5930, + OpFixedSinCosPiINTEL = 5931, + OpFixedLogINTEL = 5932, + OpFixedExpINTEL = 5933, + OpPtrCastToCrossWorkgroupINTEL = 5934, + OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, @@ -1610,6 +1789,10 @@ enum Op { OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, + OpTypeBufferSurfaceINTEL = 6086, + OpTypeStructContinuedINTEL = 6090, + OpConstantCompositeContinuedINTEL = 6091, + OpSpecConstantCompositeContinuedINTEL = 6092, OpMax = 0x7fffffff, }; @@ -1969,7 +2152,18 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case OpSubgroupAnyKHR: *hasResult = true; *hasResultType = true; break; case OpSubgroupAllEqualKHR: *hasResult = true; *hasResultType = true; break; case OpSubgroupReadInvocationKHR: *hasResult = true; *hasResultType = true; break; - case OpTypeRayQueryProvisionalKHR: *hasResult = true; *hasResultType = false; break; + case OpTraceRayKHR: *hasResult = false; *hasResultType = false; break; + case OpExecuteCallableKHR: *hasResult = false; *hasResultType = false; break; + case OpConvertUToAccelerationStructureKHR: *hasResult = true; *hasResultType = true; break; + case OpIgnoreIntersectionKHR: *hasResult = false; *hasResultType = false; break; + case OpTerminateRayKHR: *hasResult = false; *hasResultType = false; break; + case OpSDotKHR: *hasResult = true; *hasResultType = true; break; + case OpUDotKHR: *hasResult = true; *hasResultType = true; break; + case OpSUDotKHR: *hasResult = true; *hasResultType = true; break; + case OpSDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case OpUDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case OpSUDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case OpTypeRayQueryKHR: *hasResult = true; *hasResultType = false; break; case OpRayQueryInitializeKHR: *hasResult = false; *hasResultType = false; break; case OpRayQueryTerminateKHR: *hasResult = false; *hasResultType = false; break; case OpRayQueryGenerateIntersectionKHR: *hasResult = false; *hasResultType = false; break; @@ -2029,8 +2223,15 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case OpUSubSatINTEL: *hasResult = true; *hasResultType = true; break; case OpIMul32x16INTEL: *hasResult = true; *hasResultType = true; break; case OpUMul32x16INTEL: *hasResult = true; *hasResultType = true; break; - case OpFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; + case OpConstFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; case OpFunctionPointerCallINTEL: *hasResult = true; *hasResultType = true; break; + case OpAsmTargetINTEL: *hasResult = true; *hasResultType = true; break; + case OpAsmINTEL: *hasResult = true; *hasResultType = true; break; + case OpAsmCallINTEL: *hasResult = true; *hasResultType = true; break; + case OpAtomicFMinEXT: *hasResult = true; *hasResultType = true; break; + case OpAtomicFMaxEXT: *hasResult = true; *hasResultType = true; break; + case OpAssumeTrueKHR: *hasResult = false; *hasResultType = false; break; + case OpExpectKHR: *hasResult = true; *hasResultType = true; break; case OpDecorateString: *hasResult = false; *hasResultType = false; break; case OpMemberDecorateString: *hasResult = false; *hasResultType = false; break; case OpVmeImageINTEL: *hasResult = true; *hasResultType = true; break; @@ -2151,7 +2352,64 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL: *hasResult = true; *hasResultType = true; break; case OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL: *hasResult = true; *hasResultType = true; break; case OpSubgroupAvcSicGetInterRawSadsINTEL: *hasResult = true; *hasResultType = true; break; + case OpVariableLengthArrayINTEL: *hasResult = true; *hasResultType = true; break; + case OpSaveMemoryINTEL: *hasResult = true; *hasResultType = true; break; + case OpRestoreMemoryINTEL: *hasResult = false; *hasResultType = false; break; + case OpArbitraryFloatSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatCastINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatCastFromIntINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatCastToIntINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatAddINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatSubINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatMulINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatDivINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatGTINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatGEINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatLTINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatLEINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatEQINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatRecipINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatRSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatCbrtINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatHypotINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatLogINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatLog2INTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatLog10INTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatLog1pINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatExpINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatExp2INTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatExp10INTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatExpm1INTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatSinINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatCosINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatSinCosINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatSinPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatASinINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatASinPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatACosINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatACosPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatATanINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatATanPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatATan2INTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatPowINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatPowRINTEL: *hasResult = true; *hasResultType = true; break; + case OpArbitraryFloatPowNINTEL: *hasResult = true; *hasResultType = true; break; case OpLoopControlINTEL: *hasResult = false; *hasResultType = false; break; + case OpFixedSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedRecipINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedRsqrtINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedSinINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedCosINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedSinCosINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedSinPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedLogINTEL: *hasResult = true; *hasResultType = true; break; + case OpFixedExpINTEL: *hasResult = true; *hasResultType = true; break; + case OpPtrCastToCrossWorkgroupINTEL: *hasResult = true; *hasResultType = true; break; + case OpCrossWorkgroupCastToPtrINTEL: *hasResult = true; *hasResultType = true; break; case OpReadPipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case OpWritePipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case OpFPGARegINTEL: *hasResult = true; *hasResultType = true; break; @@ -2173,6 +2431,10 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case OpRayQueryGetIntersectionObjectToWorldKHR: *hasResult = true; *hasResultType = true; break; case OpRayQueryGetIntersectionWorldToObjectKHR: *hasResult = true; *hasResultType = true; break; case OpAtomicFAddEXT: *hasResult = true; *hasResultType = true; break; + case OpTypeBufferSurfaceINTEL: *hasResult = true; *hasResultType = false; break; + case OpTypeStructContinuedINTEL: *hasResult = false; *hasResultType = false; break; + case OpConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; + case OpSpecConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; } } #endif /* SPV_ENABLE_UTILITY_CODE */ diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp11 b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp11 index 1e7d12e162..e17c6c6d26 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp11 +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.hpp11 @@ -65,6 +65,7 @@ enum class SourceLanguage : unsigned { OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, + CPP_for_OpenCL = 6, Max = 0x7fffffff, }; @@ -150,6 +151,7 @@ enum class ExecutionMode : unsigned { SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, + SubgroupUniformControlFlowKHR = 4421, PostDepthCoverage = 4446, DenormPreserve = 4459, DenormFlushToZero = 4460, @@ -168,10 +170,16 @@ enum class ExecutionMode : unsigned { SampleInterlockUnorderedEXT = 5369, ShadingRateInterlockOrderedEXT = 5370, ShadingRateInterlockUnorderedEXT = 5371, + SharedLocalMemorySizeINTEL = 5618, + RoundingModeRTPINTEL = 5620, + RoundingModeRTNINTEL = 5621, + FloatingPointModeALTINTEL = 5622, + FloatingPointModeIEEEINTEL = 5623, MaxWorkgroupSizeINTEL = 5893, MaxWorkDimINTEL = 5894, NoGlobalOffsetINTEL = 5895, NumSIMDWorkitemsINTEL = 5896, + SchedulerTargetFmaxMhzINTEL = 5903, Max = 0x7fffffff, }; @@ -204,6 +212,8 @@ enum class StorageClass : unsigned { PhysicalStorageBuffer = 5349, PhysicalStorageBufferEXT = 5349, CodeSectionINTEL = 5605, + DeviceOnlyINTEL = 5936, + HostOnlyINTEL = 5937, Max = 0x7fffffff, }; @@ -374,6 +384,8 @@ enum class FPFastMathModeShift : unsigned { NSZ = 2, AllowRecip = 3, Fast = 4, + AllowContractFastINTEL = 16, + AllowReassocINTEL = 17, Max = 0x7fffffff, }; @@ -384,6 +396,8 @@ enum class FPFastMathModeMask : unsigned { NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, + AllowContractFastINTEL = 0x00010000, + AllowReassocINTEL = 0x00020000, }; enum class FPRoundingMode : unsigned { @@ -397,6 +411,7 @@ enum class FPRoundingMode : unsigned { enum class LinkageType : unsigned { Export = 0, Import = 1, + LinkOnceODR = 2, Max = 0x7fffffff, }; @@ -484,12 +499,22 @@ enum class Decoration : unsigned { RestrictPointerEXT = 5355, AliasedPointer = 5356, AliasedPointerEXT = 5356, + SIMTCallINTEL = 5599, ReferencedIndirectlyINTEL = 5602, + ClobberINTEL = 5607, + SideEffectsINTEL = 5608, + VectorComputeVariableINTEL = 5624, + FuncParamIOKindINTEL = 5625, + VectorComputeFunctionINTEL = 5626, + StackCallINTEL = 5627, + GlobalVariableOffsetINTEL = 5628, CounterBuffer = 5634, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, UserSemantic = 5635, UserTypeGOOGLE = 5636, + FunctionRoundingModeINTEL = 5822, + FunctionDenormModeINTEL = 5823, RegisterINTEL = 5825, MemoryINTEL = 5826, NumbanksINTEL = 5827, @@ -502,6 +527,17 @@ enum class Decoration : unsigned { MergeINTEL = 5834, BankBitsINTEL = 5835, ForcePow2DepthINTEL = 5836, + BurstCoalesceINTEL = 5899, + CacheSizeINTEL = 5900, + DontStaticallyCoalesceINTEL = 5901, + PrefetchINTEL = 5902, + StallEnableINTEL = 5905, + FuseLoopsInFunctionINTEL = 5907, + BufferLocationINTEL = 5921, + IOPipeStorageINTEL = 5944, + FunctionFloatingPointModeINTEL = 6080, + SingleElementVectorINTEL = 6085, + VectorComputeCallableFunctionINTEL = 6087, Max = 0x7fffffff, }; @@ -614,7 +650,6 @@ enum class BuiltIn : unsigned { ObjectToWorldNV = 5330, WorldToObjectKHR = 5331, WorldToObjectNV = 5331, - HitTKHR = 5332, HitTNV = 5332, HitKindKHR = 5333, HitKindNV = 5333, @@ -657,6 +692,7 @@ enum class LoopControlShift : unsigned { LoopCoalesceINTEL = 20, MaxInterleavingINTEL = 21, SpeculatedIterationsINTEL = 22, + NoFusionINTEL = 23, Max = 0x7fffffff, }; @@ -678,6 +714,7 @@ enum class LoopControlMask : unsigned { LoopCoalesceINTEL = 0x00100000, MaxInterleavingINTEL = 0x00200000, SpeculatedIterationsINTEL = 0x00400000, + NoFusionINTEL = 0x00800000, }; enum class FunctionControlShift : unsigned { @@ -877,6 +914,9 @@ enum class Capability : unsigned { FragmentShadingRateKHR = 4422, SubgroupBallotKHR = 4423, DrawParameters = 4427, + WorkgroupMemoryExplicitLayoutKHR = 4428, + WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, + WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, @@ -899,7 +939,9 @@ enum class Capability : unsigned { RoundingModeRTE = 4467, RoundingModeRTZ = 4468, RayQueryProvisionalKHR = 4471, - RayTraversalPrimitiveCullingProvisionalKHR = 4478, + RayQueryKHR = 4472, + RayTraversalPrimitiveCullingKHR = 4478, + RayTracingKHR = 4479, Float16ImageAMD = 5008, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, @@ -965,21 +1007,50 @@ enum class Capability : unsigned { SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, SubgroupImageMediaBlockIOINTEL = 5579, + RoundToInfinityINTEL = 5582, + FloatingPointModeINTEL = 5583, IntegerFunctions2INTEL = 5584, FunctionPointersINTEL = 5603, IndirectReferencesINTEL = 5604, + AsmINTEL = 5606, + AtomicFloat32MinMaxEXT = 5612, + AtomicFloat64MinMaxEXT = 5613, + AtomicFloat16MinMaxEXT = 5616, + VectorComputeINTEL = 5617, + VectorAnyINTEL = 5619, + ExpectAssumeKHR = 5629, SubgroupAvcMotionEstimationINTEL = 5696, SubgroupAvcMotionEstimationIntraINTEL = 5697, SubgroupAvcMotionEstimationChromaINTEL = 5698, + VariableLengthArrayINTEL = 5817, + FunctionFloatControlINTEL = 5821, FPGAMemoryAttributesINTEL = 5824, + FPFastMathModeINTEL = 5837, + ArbitraryPrecisionIntegersINTEL = 5844, + ArbitraryPrecisionFloatingPointINTEL = 5845, UnstructuredLoopControlsINTEL = 5886, FPGALoopControlsINTEL = 5888, KernelAttributesINTEL = 5892, FPGAKernelAttributesINTEL = 5897, + FPGAMemoryAccessesINTEL = 5898, + FPGAClusterAttributesINTEL = 5904, + LoopFuseINTEL = 5906, + FPGABufferLocationINTEL = 5920, + ArbitraryPrecisionFixedPointINTEL = 5922, + USMStorageClassesINTEL = 5935, + IOPipesINTEL = 5943, BlockingPipesINTEL = 5945, FPGARegINTEL = 5948, + DotProductInputAllKHR = 6016, + DotProductInput4x8BitKHR = 6017, + DotProductInput4x8BitPackedKHR = 6018, + DotProductKHR = 6019, + BitInstructions = 6025, AtomicFloat32AddEXT = 6033, AtomicFloat64AddEXT = 6034, + LongConstantCompositeINTEL = 6089, + AtomicFloat16AddEXT = 6095, + DebugInfoModuleINTEL = 6114, Max = 0x7fffffff, }; @@ -1046,6 +1117,43 @@ enum class FragmentShadingRateMask : unsigned { Horizontal4Pixels = 0x00000008, }; +enum class FPDenormMode : unsigned { + Preserve = 0, + FlushToZero = 1, + Max = 0x7fffffff, +}; + +enum class FPOperationMode : unsigned { + IEEE = 0, + ALT = 1, + Max = 0x7fffffff, +}; + +enum class QuantizationModes : unsigned { + TRN = 0, + TRN_ZERO = 1, + RND = 2, + RND_ZERO = 3, + RND_INF = 4, + RND_MIN_INF = 5, + RND_CONV = 6, + RND_CONV_ODD = 7, + Max = 0x7fffffff, +}; + +enum class OverflowModes : unsigned { + WRAP = 0, + SAT = 1, + SAT_ZERO = 2, + SAT_SYM = 3, + Max = 0x7fffffff, +}; + +enum class PackedVectorFormat : unsigned { + PackedVectorFormat4x8BitKHR = 0, + Max = 0x7fffffff, +}; + enum class Op : unsigned { OpNop = 0, OpUndef = 1, @@ -1398,7 +1506,18 @@ enum class Op : unsigned { OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, - OpTypeRayQueryProvisionalKHR = 4472, + OpTraceRayKHR = 4445, + OpExecuteCallableKHR = 4446, + OpConvertUToAccelerationStructureKHR = 4447, + OpIgnoreIntersectionKHR = 4448, + OpTerminateRayKHR = 4449, + OpSDotKHR = 4450, + OpUDotKHR = 4451, + OpSUDotKHR = 4452, + OpSDotAccSatKHR = 4453, + OpUDotAccSatKHR = 4454, + OpSUDotAccSatKHR = 4455, + OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, @@ -1421,15 +1540,11 @@ enum class Op : unsigned { OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionKHR = 5334, OpReportIntersectionNV = 5334, - OpIgnoreIntersectionKHR = 5335, OpIgnoreIntersectionNV = 5335, - OpTerminateRayKHR = 5336, OpTerminateRayNV = 5336, OpTraceNV = 5337, - OpTraceRayKHR = 5337, OpTypeAccelerationStructureKHR = 5341, OpTypeAccelerationStructureNV = 5341, - OpExecuteCallableKHR = 5344, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, @@ -1464,8 +1579,15 @@ enum class Op : unsigned { OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, - OpFunctionPointerINTEL = 5600, + OpConstFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, + OpAsmTargetINTEL = 5609, + OpAsmINTEL = 5610, + OpAsmCallINTEL = 5611, + OpAtomicFMinEXT = 5614, + OpAtomicFMaxEXT = 5615, + OpAssumeTrueKHR = 5630, + OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, @@ -1588,7 +1710,64 @@ enum class Op : unsigned { OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, + OpVariableLengthArrayINTEL = 5818, + OpSaveMemoryINTEL = 5819, + OpRestoreMemoryINTEL = 5820, + OpArbitraryFloatSinCosPiINTEL = 5840, + OpArbitraryFloatCastINTEL = 5841, + OpArbitraryFloatCastFromIntINTEL = 5842, + OpArbitraryFloatCastToIntINTEL = 5843, + OpArbitraryFloatAddINTEL = 5846, + OpArbitraryFloatSubINTEL = 5847, + OpArbitraryFloatMulINTEL = 5848, + OpArbitraryFloatDivINTEL = 5849, + OpArbitraryFloatGTINTEL = 5850, + OpArbitraryFloatGEINTEL = 5851, + OpArbitraryFloatLTINTEL = 5852, + OpArbitraryFloatLEINTEL = 5853, + OpArbitraryFloatEQINTEL = 5854, + OpArbitraryFloatRecipINTEL = 5855, + OpArbitraryFloatRSqrtINTEL = 5856, + OpArbitraryFloatCbrtINTEL = 5857, + OpArbitraryFloatHypotINTEL = 5858, + OpArbitraryFloatSqrtINTEL = 5859, + OpArbitraryFloatLogINTEL = 5860, + OpArbitraryFloatLog2INTEL = 5861, + OpArbitraryFloatLog10INTEL = 5862, + OpArbitraryFloatLog1pINTEL = 5863, + OpArbitraryFloatExpINTEL = 5864, + OpArbitraryFloatExp2INTEL = 5865, + OpArbitraryFloatExp10INTEL = 5866, + OpArbitraryFloatExpm1INTEL = 5867, + OpArbitraryFloatSinINTEL = 5868, + OpArbitraryFloatCosINTEL = 5869, + OpArbitraryFloatSinCosINTEL = 5870, + OpArbitraryFloatSinPiINTEL = 5871, + OpArbitraryFloatCosPiINTEL = 5872, + OpArbitraryFloatASinINTEL = 5873, + OpArbitraryFloatASinPiINTEL = 5874, + OpArbitraryFloatACosINTEL = 5875, + OpArbitraryFloatACosPiINTEL = 5876, + OpArbitraryFloatATanINTEL = 5877, + OpArbitraryFloatATanPiINTEL = 5878, + OpArbitraryFloatATan2INTEL = 5879, + OpArbitraryFloatPowINTEL = 5880, + OpArbitraryFloatPowRINTEL = 5881, + OpArbitraryFloatPowNINTEL = 5882, OpLoopControlINTEL = 5887, + OpFixedSqrtINTEL = 5923, + OpFixedRecipINTEL = 5924, + OpFixedRsqrtINTEL = 5925, + OpFixedSinINTEL = 5926, + OpFixedCosINTEL = 5927, + OpFixedSinCosINTEL = 5928, + OpFixedSinPiINTEL = 5929, + OpFixedCosPiINTEL = 5930, + OpFixedSinCosPiINTEL = 5931, + OpFixedLogINTEL = 5932, + OpFixedExpINTEL = 5933, + OpPtrCastToCrossWorkgroupINTEL = 5934, + OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, @@ -1610,6 +1789,10 @@ enum class Op : unsigned { OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, + OpTypeBufferSurfaceINTEL = 6086, + OpTypeStructContinuedINTEL = 6090, + OpConstantCompositeContinuedINTEL = 6091, + OpSpecConstantCompositeContinuedINTEL = 6092, Max = 0x7fffffff, }; @@ -1969,7 +2152,18 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case Op::OpSubgroupAnyKHR: *hasResult = true; *hasResultType = true; break; case Op::OpSubgroupAllEqualKHR: *hasResult = true; *hasResultType = true; break; case Op::OpSubgroupReadInvocationKHR: *hasResult = true; *hasResultType = true; break; - case Op::OpTypeRayQueryProvisionalKHR: *hasResult = true; *hasResultType = false; break; + case Op::OpTraceRayKHR: *hasResult = false; *hasResultType = false; break; + case Op::OpExecuteCallableKHR: *hasResult = false; *hasResultType = false; break; + case Op::OpConvertUToAccelerationStructureKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpIgnoreIntersectionKHR: *hasResult = false; *hasResultType = false; break; + case Op::OpTerminateRayKHR: *hasResult = false; *hasResultType = false; break; + case Op::OpSDotKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpUDotKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpSUDotKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpSDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpUDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpSUDotAccSatKHR: *hasResult = true; *hasResultType = true; break; + case Op::OpTypeRayQueryKHR: *hasResult = true; *hasResultType = false; break; case Op::OpRayQueryInitializeKHR: *hasResult = false; *hasResultType = false; break; case Op::OpRayQueryTerminateKHR: *hasResult = false; *hasResultType = false; break; case Op::OpRayQueryGenerateIntersectionKHR: *hasResult = false; *hasResultType = false; break; @@ -2029,8 +2223,15 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case Op::OpUSubSatINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpIMul32x16INTEL: *hasResult = true; *hasResultType = true; break; case Op::OpUMul32x16INTEL: *hasResult = true; *hasResultType = true; break; - case Op::OpFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpConstFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpFunctionPointerCallINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpAsmTargetINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpAsmINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpAsmCallINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpAtomicFMinEXT: *hasResult = true; *hasResultType = true; break; + case Op::OpAtomicFMaxEXT: *hasResult = true; *hasResultType = true; break; + case Op::OpAssumeTrueKHR: *hasResult = false; *hasResultType = false; break; + case Op::OpExpectKHR: *hasResult = true; *hasResultType = true; break; case Op::OpDecorateString: *hasResult = false; *hasResultType = false; break; case Op::OpMemberDecorateString: *hasResult = false; *hasResultType = false; break; case Op::OpVmeImageINTEL: *hasResult = true; *hasResultType = true; break; @@ -2151,7 +2352,64 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case Op::OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpSubgroupAvcSicGetInterRawSadsINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpVariableLengthArrayINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpSaveMemoryINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpRestoreMemoryINTEL: *hasResult = false; *hasResultType = false; break; + case Op::OpArbitraryFloatSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatCastINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatCastFromIntINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatCastToIntINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatAddINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatSubINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatMulINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatDivINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatGTINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatGEINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatLTINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatLEINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatEQINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatRecipINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatRSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatCbrtINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatHypotINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatLogINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatLog2INTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatLog10INTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatLog1pINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatExpINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatExp2INTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatExp10INTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatExpm1INTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatSinINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatCosINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatSinCosINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatSinPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatASinINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatASinPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatACosINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatACosPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatATanINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatATanPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatATan2INTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatPowINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatPowRINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpArbitraryFloatPowNINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpLoopControlINTEL: *hasResult = false; *hasResultType = false; break; + case Op::OpFixedSqrtINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedRecipINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedRsqrtINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedSinINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedCosINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedSinCosINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedSinPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedLogINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpFixedExpINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpPtrCastToCrossWorkgroupINTEL: *hasResult = true; *hasResultType = true; break; + case Op::OpCrossWorkgroupCastToPtrINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpReadPipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpWritePipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case Op::OpFPGARegINTEL: *hasResult = true; *hasResultType = true; break; @@ -2173,6 +2431,10 @@ inline void HasResultAndType(Op opcode, bool *hasResult, bool *hasResultType) { case Op::OpRayQueryGetIntersectionObjectToWorldKHR: *hasResult = true; *hasResultType = true; break; case Op::OpRayQueryGetIntersectionWorldToObjectKHR: *hasResult = true; *hasResultType = true; break; case Op::OpAtomicFAddEXT: *hasResult = true; *hasResultType = true; break; + case Op::OpTypeBufferSurfaceINTEL: *hasResult = true; *hasResultType = false; break; + case Op::OpTypeStructContinuedINTEL: *hasResult = false; *hasResultType = false; break; + case Op::OpConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; + case Op::OpSpecConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; } } #endif /* SPV_ENABLE_UTILITY_CODE */ diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.json b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.json index 835327487c..1c63036f36 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.json +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.json @@ -71,7 +71,8 @@ "GLSL": 2, "OpenCL_C": 3, "OpenCL_CPP": 4, - "HLSL": 5 + "HLSL": 5, + "CPP_for_OpenCL": 6 } }, { @@ -169,6 +170,7 @@ "SubgroupsPerWorkgroupId": 37, "LocalSizeId": 38, "LocalSizeHintId": 39, + "SubgroupUniformControlFlowKHR": 4421, "PostDepthCoverage": 4446, "DenormPreserve": 4459, "DenormFlushToZero": 4460, @@ -187,10 +189,16 @@ "SampleInterlockUnorderedEXT": 5369, "ShadingRateInterlockOrderedEXT": 5370, "ShadingRateInterlockUnorderedEXT": 5371, + "SharedLocalMemorySizeINTEL": 5618, + "RoundingModeRTPINTEL": 5620, + "RoundingModeRTNINTEL": 5621, + "FloatingPointModeALTINTEL": 5622, + "FloatingPointModeIEEEINTEL": 5623, "MaxWorkgroupSizeINTEL": 5893, "MaxWorkDimINTEL": 5894, "NoGlobalOffsetINTEL": 5895, - "NumSIMDWorkitemsINTEL": 5896 + "NumSIMDWorkitemsINTEL": 5896, + "SchedulerTargetFmaxMhzINTEL": 5903 } }, { @@ -225,7 +233,9 @@ "ShaderRecordBufferNV": 5343, "PhysicalStorageBuffer": 5349, "PhysicalStorageBufferEXT": 5349, - "CodeSectionINTEL": 5605 + "CodeSectionINTEL": 5605, + "DeviceOnlyINTEL": 5936, + "HostOnlyINTEL": 5937 } }, { @@ -397,7 +407,9 @@ "NotInf": 1, "NSZ": 2, "AllowRecip": 3, - "Fast": 4 + "Fast": 4, + "AllowContractFastINTEL": 16, + "AllowReassocINTEL": 17 } }, { @@ -417,7 +429,8 @@ "Values": { "Export": 0, - "Import": 1 + "Import": 1, + "LinkOnceODR": 2 } }, { @@ -514,12 +527,22 @@ "RestrictPointerEXT": 5355, "AliasedPointer": 5356, "AliasedPointerEXT": 5356, + "SIMTCallINTEL": 5599, "ReferencedIndirectlyINTEL": 5602, + "ClobberINTEL": 5607, + "SideEffectsINTEL": 5608, + "VectorComputeVariableINTEL": 5624, + "FuncParamIOKindINTEL": 5625, + "VectorComputeFunctionINTEL": 5626, + "StackCallINTEL": 5627, + "GlobalVariableOffsetINTEL": 5628, "CounterBuffer": 5634, "HlslCounterBufferGOOGLE": 5634, "HlslSemanticGOOGLE": 5635, "UserSemantic": 5635, "UserTypeGOOGLE": 5636, + "FunctionRoundingModeINTEL": 5822, + "FunctionDenormModeINTEL": 5823, "RegisterINTEL": 5825, "MemoryINTEL": 5826, "NumbanksINTEL": 5827, @@ -531,7 +554,18 @@ "SimpleDualPortINTEL": 5833, "MergeINTEL": 5834, "BankBitsINTEL": 5835, - "ForcePow2DepthINTEL": 5836 + "ForcePow2DepthINTEL": 5836, + "BurstCoalesceINTEL": 5899, + "CacheSizeINTEL": 5900, + "DontStaticallyCoalesceINTEL": 5901, + "PrefetchINTEL": 5902, + "StallEnableINTEL": 5905, + "FuseLoopsInFunctionINTEL": 5907, + "BufferLocationINTEL": 5921, + "IOPipeStorageINTEL": 5944, + "FunctionFloatingPointModeINTEL": 6080, + "SingleElementVectorINTEL": 6085, + "VectorComputeCallableFunctionINTEL": 6087 } }, { @@ -647,7 +681,6 @@ "ObjectToWorldNV": 5330, "WorldToObjectKHR": 5331, "WorldToObjectNV": 5331, - "HitTKHR": 5332, "HitTNV": 5332, "HitKindKHR": 5333, "HitKindNV": 5333, @@ -689,7 +722,8 @@ "PipelineEnableINTEL": 19, "LoopCoalesceINTEL": 20, "MaxInterleavingINTEL": 21, - "SpeculatedIterationsINTEL": 22 + "SpeculatedIterationsINTEL": 22, + "NoFusionINTEL": 23 } }, { @@ -867,6 +901,9 @@ "FragmentShadingRateKHR": 4422, "SubgroupBallotKHR": 4423, "DrawParameters": 4427, + "WorkgroupMemoryExplicitLayoutKHR": 4428, + "WorkgroupMemoryExplicitLayout8BitAccessKHR": 4429, + "WorkgroupMemoryExplicitLayout16BitAccessKHR": 4430, "SubgroupVoteKHR": 4431, "StorageBuffer16BitAccess": 4433, "StorageUniformBufferBlock16": 4433, @@ -889,7 +926,9 @@ "RoundingModeRTE": 4467, "RoundingModeRTZ": 4468, "RayQueryProvisionalKHR": 4471, - "RayTraversalPrimitiveCullingProvisionalKHR": 4478, + "RayQueryKHR": 4472, + "RayTraversalPrimitiveCullingKHR": 4478, + "RayTracingKHR": 4479, "Float16ImageAMD": 5008, "ImageGatherBiasLodAMD": 5009, "FragmentMaskAMD": 5010, @@ -955,21 +994,50 @@ "SubgroupBufferBlockIOINTEL": 5569, "SubgroupImageBlockIOINTEL": 5570, "SubgroupImageMediaBlockIOINTEL": 5579, + "RoundToInfinityINTEL": 5582, + "FloatingPointModeINTEL": 5583, "IntegerFunctions2INTEL": 5584, "FunctionPointersINTEL": 5603, "IndirectReferencesINTEL": 5604, + "AsmINTEL": 5606, + "AtomicFloat32MinMaxEXT": 5612, + "AtomicFloat64MinMaxEXT": 5613, + "AtomicFloat16MinMaxEXT": 5616, + "VectorComputeINTEL": 5617, + "VectorAnyINTEL": 5619, + "ExpectAssumeKHR": 5629, "SubgroupAvcMotionEstimationINTEL": 5696, "SubgroupAvcMotionEstimationIntraINTEL": 5697, "SubgroupAvcMotionEstimationChromaINTEL": 5698, + "VariableLengthArrayINTEL": 5817, + "FunctionFloatControlINTEL": 5821, "FPGAMemoryAttributesINTEL": 5824, + "FPFastMathModeINTEL": 5837, + "ArbitraryPrecisionIntegersINTEL": 5844, + "ArbitraryPrecisionFloatingPointINTEL": 5845, "UnstructuredLoopControlsINTEL": 5886, "FPGALoopControlsINTEL": 5888, "KernelAttributesINTEL": 5892, "FPGAKernelAttributesINTEL": 5897, + "FPGAMemoryAccessesINTEL": 5898, + "FPGAClusterAttributesINTEL": 5904, + "LoopFuseINTEL": 5906, + "FPGABufferLocationINTEL": 5920, + "ArbitraryPrecisionFixedPointINTEL": 5922, + "USMStorageClassesINTEL": 5935, + "IOPipesINTEL": 5943, "BlockingPipesINTEL": 5945, "FPGARegINTEL": 5948, + "DotProductInputAllKHR": 6016, + "DotProductInput4x8BitKHR": 6017, + "DotProductInput4x8BitPackedKHR": 6018, + "DotProductKHR": 6019, + "BitInstructions": 6025, "AtomicFloat32AddEXT": 6033, - "AtomicFloat64AddEXT": 6034 + "AtomicFloat64AddEXT": 6034, + "LongConstantCompositeINTEL": 6089, + "AtomicFloat16AddEXT": 6095, + "DebugInfoModuleINTEL": 6114 } }, { @@ -1028,6 +1096,58 @@ "Horizontal4Pixels": 3 } }, + { + "Name": "FPDenormMode", + "Type": "Value", + "Values": + { + "Preserve": 0, + "FlushToZero": 1 + } + }, + { + "Name": "FPOperationMode", + "Type": "Value", + "Values": + { + "IEEE": 0, + "ALT": 1 + } + }, + { + "Name": "QuantizationModes", + "Type": "Value", + "Values": + { + "TRN": 0, + "TRN_ZERO": 1, + "RND": 2, + "RND_ZERO": 3, + "RND_INF": 4, + "RND_MIN_INF": 5, + "RND_CONV": 6, + "RND_CONV_ODD": 7 + } + }, + { + "Name": "OverflowModes", + "Type": "Value", + "Values": + { + "WRAP": 0, + "SAT": 1, + "SAT_ZERO": 2, + "SAT_SYM": 3 + } + }, + { + "Name": "PackedVectorFormat", + "Type": "Value", + "Values": + { + "PackedVectorFormat4x8BitKHR": 0 + } + }, { "Name": "Op", "Type": "Value", @@ -1384,7 +1504,18 @@ "OpSubgroupAnyKHR": 4429, "OpSubgroupAllEqualKHR": 4430, "OpSubgroupReadInvocationKHR": 4432, - "OpTypeRayQueryProvisionalKHR": 4472, + "OpTraceRayKHR": 4445, + "OpExecuteCallableKHR": 4446, + "OpConvertUToAccelerationStructureKHR": 4447, + "OpIgnoreIntersectionKHR": 4448, + "OpTerminateRayKHR": 4449, + "OpSDotKHR": 4450, + "OpUDotKHR": 4451, + "OpSUDotKHR": 4452, + "OpSDotAccSatKHR": 4453, + "OpUDotAccSatKHR": 4454, + "OpSUDotAccSatKHR": 4455, + "OpTypeRayQueryKHR": 4472, "OpRayQueryInitializeKHR": 4473, "OpRayQueryTerminateKHR": 4474, "OpRayQueryGenerateIntersectionKHR": 4475, @@ -1407,15 +1538,11 @@ "OpWritePackedPrimitiveIndices4x8NV": 5299, "OpReportIntersectionKHR": 5334, "OpReportIntersectionNV": 5334, - "OpIgnoreIntersectionKHR": 5335, "OpIgnoreIntersectionNV": 5335, - "OpTerminateRayKHR": 5336, "OpTerminateRayNV": 5336, "OpTraceNV": 5337, - "OpTraceRayKHR": 5337, "OpTypeAccelerationStructureKHR": 5341, "OpTypeAccelerationStructureNV": 5341, - "OpExecuteCallableKHR": 5344, "OpExecuteCallableNV": 5344, "OpTypeCooperativeMatrixNV": 5358, "OpCooperativeMatrixLoadNV": 5359, @@ -1450,8 +1577,15 @@ "OpUSubSatINTEL": 5596, "OpIMul32x16INTEL": 5597, "OpUMul32x16INTEL": 5598, - "OpFunctionPointerINTEL": 5600, + "OpConstFunctionPointerINTEL": 5600, "OpFunctionPointerCallINTEL": 5601, + "OpAsmTargetINTEL": 5609, + "OpAsmINTEL": 5610, + "OpAsmCallINTEL": 5611, + "OpAtomicFMinEXT": 5614, + "OpAtomicFMaxEXT": 5615, + "OpAssumeTrueKHR": 5630, + "OpExpectKHR": 5631, "OpDecorateString": 5632, "OpDecorateStringGOOGLE": 5632, "OpMemberDecorateString": 5633, @@ -1574,7 +1708,64 @@ "OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL": 5814, "OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL": 5815, "OpSubgroupAvcSicGetInterRawSadsINTEL": 5816, + "OpVariableLengthArrayINTEL": 5818, + "OpSaveMemoryINTEL": 5819, + "OpRestoreMemoryINTEL": 5820, + "OpArbitraryFloatSinCosPiINTEL": 5840, + "OpArbitraryFloatCastINTEL": 5841, + "OpArbitraryFloatCastFromIntINTEL": 5842, + "OpArbitraryFloatCastToIntINTEL": 5843, + "OpArbitraryFloatAddINTEL": 5846, + "OpArbitraryFloatSubINTEL": 5847, + "OpArbitraryFloatMulINTEL": 5848, + "OpArbitraryFloatDivINTEL": 5849, + "OpArbitraryFloatGTINTEL": 5850, + "OpArbitraryFloatGEINTEL": 5851, + "OpArbitraryFloatLTINTEL": 5852, + "OpArbitraryFloatLEINTEL": 5853, + "OpArbitraryFloatEQINTEL": 5854, + "OpArbitraryFloatRecipINTEL": 5855, + "OpArbitraryFloatRSqrtINTEL": 5856, + "OpArbitraryFloatCbrtINTEL": 5857, + "OpArbitraryFloatHypotINTEL": 5858, + "OpArbitraryFloatSqrtINTEL": 5859, + "OpArbitraryFloatLogINTEL": 5860, + "OpArbitraryFloatLog2INTEL": 5861, + "OpArbitraryFloatLog10INTEL": 5862, + "OpArbitraryFloatLog1pINTEL": 5863, + "OpArbitraryFloatExpINTEL": 5864, + "OpArbitraryFloatExp2INTEL": 5865, + "OpArbitraryFloatExp10INTEL": 5866, + "OpArbitraryFloatExpm1INTEL": 5867, + "OpArbitraryFloatSinINTEL": 5868, + "OpArbitraryFloatCosINTEL": 5869, + "OpArbitraryFloatSinCosINTEL": 5870, + "OpArbitraryFloatSinPiINTEL": 5871, + "OpArbitraryFloatCosPiINTEL": 5872, + "OpArbitraryFloatASinINTEL": 5873, + "OpArbitraryFloatASinPiINTEL": 5874, + "OpArbitraryFloatACosINTEL": 5875, + "OpArbitraryFloatACosPiINTEL": 5876, + "OpArbitraryFloatATanINTEL": 5877, + "OpArbitraryFloatATanPiINTEL": 5878, + "OpArbitraryFloatATan2INTEL": 5879, + "OpArbitraryFloatPowINTEL": 5880, + "OpArbitraryFloatPowRINTEL": 5881, + "OpArbitraryFloatPowNINTEL": 5882, "OpLoopControlINTEL": 5887, + "OpFixedSqrtINTEL": 5923, + "OpFixedRecipINTEL": 5924, + "OpFixedRsqrtINTEL": 5925, + "OpFixedSinINTEL": 5926, + "OpFixedCosINTEL": 5927, + "OpFixedSinCosINTEL": 5928, + "OpFixedSinPiINTEL": 5929, + "OpFixedCosPiINTEL": 5930, + "OpFixedSinCosPiINTEL": 5931, + "OpFixedLogINTEL": 5932, + "OpFixedExpINTEL": 5933, + "OpPtrCastToCrossWorkgroupINTEL": 5934, + "OpCrossWorkgroupCastToPtrINTEL": 5938, "OpReadPipeBlockingINTEL": 5946, "OpWritePipeBlockingINTEL": 5947, "OpFPGARegINTEL": 5949, @@ -1595,7 +1786,11 @@ "OpRayQueryGetWorldRayOriginKHR": 6030, "OpRayQueryGetIntersectionObjectToWorldKHR": 6031, "OpRayQueryGetIntersectionWorldToObjectKHR": 6032, - "OpAtomicFAddEXT": 6035 + "OpAtomicFAddEXT": 6035, + "OpTypeBufferSurfaceINTEL": 6086, + "OpTypeStructContinuedINTEL": 6090, + "OpConstantCompositeContinuedINTEL": 6091, + "OpSpecConstantCompositeContinuedINTEL": 6092 } } ] diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.lua b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.lua index d97af4180e..afdaec9e25 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.lua +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.lua @@ -56,6 +56,7 @@ spv = { OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, + CPP_for_OpenCL = 6, }, ExecutionModel = { @@ -137,6 +138,7 @@ spv = { SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, + SubgroupUniformControlFlowKHR = 4421, PostDepthCoverage = 4446, DenormPreserve = 4459, DenormFlushToZero = 4460, @@ -155,10 +157,16 @@ spv = { SampleInterlockUnorderedEXT = 5369, ShadingRateInterlockOrderedEXT = 5370, ShadingRateInterlockUnorderedEXT = 5371, + SharedLocalMemorySizeINTEL = 5618, + RoundingModeRTPINTEL = 5620, + RoundingModeRTNINTEL = 5621, + FloatingPointModeALTINTEL = 5622, + FloatingPointModeIEEEINTEL = 5623, MaxWorkgroupSizeINTEL = 5893, MaxWorkDimINTEL = 5894, NoGlobalOffsetINTEL = 5895, NumSIMDWorkitemsINTEL = 5896, + SchedulerTargetFmaxMhzINTEL = 5903, }, StorageClass = { @@ -190,6 +198,8 @@ spv = { PhysicalStorageBuffer = 5349, PhysicalStorageBufferEXT = 5349, CodeSectionINTEL = 5605, + DeviceOnlyINTEL = 5936, + HostOnlyINTEL = 5937, }, Dim = { @@ -352,6 +362,8 @@ spv = { NSZ = 2, AllowRecip = 3, Fast = 4, + AllowContractFastINTEL = 16, + AllowReassocINTEL = 17, }, FPFastMathModeMask = { @@ -361,6 +373,8 @@ spv = { NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, + AllowContractFastINTEL = 0x00010000, + AllowReassocINTEL = 0x00020000, }, FPRoundingMode = { @@ -373,6 +387,7 @@ spv = { LinkageType = { Export = 0, Import = 1, + LinkOnceODR = 2, }, AccessQualifier = { @@ -457,12 +472,22 @@ spv = { RestrictPointerEXT = 5355, AliasedPointer = 5356, AliasedPointerEXT = 5356, + SIMTCallINTEL = 5599, ReferencedIndirectlyINTEL = 5602, + ClobberINTEL = 5607, + SideEffectsINTEL = 5608, + VectorComputeVariableINTEL = 5624, + FuncParamIOKindINTEL = 5625, + VectorComputeFunctionINTEL = 5626, + StackCallINTEL = 5627, + GlobalVariableOffsetINTEL = 5628, CounterBuffer = 5634, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, UserSemantic = 5635, UserTypeGOOGLE = 5636, + FunctionRoundingModeINTEL = 5822, + FunctionDenormModeINTEL = 5823, RegisterINTEL = 5825, MemoryINTEL = 5826, NumbanksINTEL = 5827, @@ -475,6 +500,17 @@ spv = { MergeINTEL = 5834, BankBitsINTEL = 5835, ForcePow2DepthINTEL = 5836, + BurstCoalesceINTEL = 5899, + CacheSizeINTEL = 5900, + DontStaticallyCoalesceINTEL = 5901, + PrefetchINTEL = 5902, + StallEnableINTEL = 5905, + FuseLoopsInFunctionINTEL = 5907, + BufferLocationINTEL = 5921, + IOPipeStorageINTEL = 5944, + FunctionFloatingPointModeINTEL = 6080, + SingleElementVectorINTEL = 6085, + VectorComputeCallableFunctionINTEL = 6087, }, BuiltIn = { @@ -586,7 +622,6 @@ spv = { ObjectToWorldNV = 5330, WorldToObjectKHR = 5331, WorldToObjectNV = 5331, - HitTKHR = 5332, HitTNV = 5332, HitKindKHR = 5333, HitKindNV = 5333, @@ -627,6 +662,7 @@ spv = { LoopCoalesceINTEL = 20, MaxInterleavingINTEL = 21, SpeculatedIterationsINTEL = 22, + NoFusionINTEL = 23, }, LoopControlMask = { @@ -647,6 +683,7 @@ spv = { LoopCoalesceINTEL = 0x00100000, MaxInterleavingINTEL = 0x00200000, SpeculatedIterationsINTEL = 0x00400000, + NoFusionINTEL = 0x00800000, }, FunctionControlShift = { @@ -839,6 +876,9 @@ spv = { FragmentShadingRateKHR = 4422, SubgroupBallotKHR = 4423, DrawParameters = 4427, + WorkgroupMemoryExplicitLayoutKHR = 4428, + WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, + WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, @@ -861,7 +901,9 @@ spv = { RoundingModeRTE = 4467, RoundingModeRTZ = 4468, RayQueryProvisionalKHR = 4471, - RayTraversalPrimitiveCullingProvisionalKHR = 4478, + RayQueryKHR = 4472, + RayTraversalPrimitiveCullingKHR = 4478, + RayTracingKHR = 4479, Float16ImageAMD = 5008, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, @@ -927,21 +969,50 @@ spv = { SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, SubgroupImageMediaBlockIOINTEL = 5579, + RoundToInfinityINTEL = 5582, + FloatingPointModeINTEL = 5583, IntegerFunctions2INTEL = 5584, FunctionPointersINTEL = 5603, IndirectReferencesINTEL = 5604, + AsmINTEL = 5606, + AtomicFloat32MinMaxEXT = 5612, + AtomicFloat64MinMaxEXT = 5613, + AtomicFloat16MinMaxEXT = 5616, + VectorComputeINTEL = 5617, + VectorAnyINTEL = 5619, + ExpectAssumeKHR = 5629, SubgroupAvcMotionEstimationINTEL = 5696, SubgroupAvcMotionEstimationIntraINTEL = 5697, SubgroupAvcMotionEstimationChromaINTEL = 5698, + VariableLengthArrayINTEL = 5817, + FunctionFloatControlINTEL = 5821, FPGAMemoryAttributesINTEL = 5824, + FPFastMathModeINTEL = 5837, + ArbitraryPrecisionIntegersINTEL = 5844, + ArbitraryPrecisionFloatingPointINTEL = 5845, UnstructuredLoopControlsINTEL = 5886, FPGALoopControlsINTEL = 5888, KernelAttributesINTEL = 5892, FPGAKernelAttributesINTEL = 5897, + FPGAMemoryAccessesINTEL = 5898, + FPGAClusterAttributesINTEL = 5904, + LoopFuseINTEL = 5906, + FPGABufferLocationINTEL = 5920, + ArbitraryPrecisionFixedPointINTEL = 5922, + USMStorageClassesINTEL = 5935, + IOPipesINTEL = 5943, BlockingPipesINTEL = 5945, FPGARegINTEL = 5948, + DotProductInputAllKHR = 6016, + DotProductInput4x8BitKHR = 6017, + DotProductInput4x8BitPackedKHR = 6018, + DotProductKHR = 6019, + BitInstructions = 6025, AtomicFloat32AddEXT = 6033, AtomicFloat64AddEXT = 6034, + LongConstantCompositeINTEL = 6089, + AtomicFloat16AddEXT = 6095, + DebugInfoModuleINTEL = 6114, }, RayFlagsShift = { @@ -1002,6 +1073,38 @@ spv = { Horizontal4Pixels = 0x00000008, }, + FPDenormMode = { + Preserve = 0, + FlushToZero = 1, + }, + + FPOperationMode = { + IEEE = 0, + ALT = 1, + }, + + QuantizationModes = { + TRN = 0, + TRN_ZERO = 1, + RND = 2, + RND_ZERO = 3, + RND_INF = 4, + RND_MIN_INF = 5, + RND_CONV = 6, + RND_CONV_ODD = 7, + }, + + OverflowModes = { + WRAP = 0, + SAT = 1, + SAT_ZERO = 2, + SAT_SYM = 3, + }, + + PackedVectorFormat = { + PackedVectorFormat4x8BitKHR = 0, + }, + Op = { OpNop = 0, OpUndef = 1, @@ -1354,7 +1457,18 @@ spv = { OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, - OpTypeRayQueryProvisionalKHR = 4472, + OpTraceRayKHR = 4445, + OpExecuteCallableKHR = 4446, + OpConvertUToAccelerationStructureKHR = 4447, + OpIgnoreIntersectionKHR = 4448, + OpTerminateRayKHR = 4449, + OpSDotKHR = 4450, + OpUDotKHR = 4451, + OpSUDotKHR = 4452, + OpSDotAccSatKHR = 4453, + OpUDotAccSatKHR = 4454, + OpSUDotAccSatKHR = 4455, + OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, @@ -1377,15 +1491,11 @@ spv = { OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionKHR = 5334, OpReportIntersectionNV = 5334, - OpIgnoreIntersectionKHR = 5335, OpIgnoreIntersectionNV = 5335, - OpTerminateRayKHR = 5336, OpTerminateRayNV = 5336, OpTraceNV = 5337, - OpTraceRayKHR = 5337, OpTypeAccelerationStructureKHR = 5341, OpTypeAccelerationStructureNV = 5341, - OpExecuteCallableKHR = 5344, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, @@ -1420,8 +1530,15 @@ spv = { OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, - OpFunctionPointerINTEL = 5600, + OpConstFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, + OpAsmTargetINTEL = 5609, + OpAsmINTEL = 5610, + OpAsmCallINTEL = 5611, + OpAtomicFMinEXT = 5614, + OpAtomicFMaxEXT = 5615, + OpAssumeTrueKHR = 5630, + OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, @@ -1544,7 +1661,64 @@ spv = { OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, + OpVariableLengthArrayINTEL = 5818, + OpSaveMemoryINTEL = 5819, + OpRestoreMemoryINTEL = 5820, + OpArbitraryFloatSinCosPiINTEL = 5840, + OpArbitraryFloatCastINTEL = 5841, + OpArbitraryFloatCastFromIntINTEL = 5842, + OpArbitraryFloatCastToIntINTEL = 5843, + OpArbitraryFloatAddINTEL = 5846, + OpArbitraryFloatSubINTEL = 5847, + OpArbitraryFloatMulINTEL = 5848, + OpArbitraryFloatDivINTEL = 5849, + OpArbitraryFloatGTINTEL = 5850, + OpArbitraryFloatGEINTEL = 5851, + OpArbitraryFloatLTINTEL = 5852, + OpArbitraryFloatLEINTEL = 5853, + OpArbitraryFloatEQINTEL = 5854, + OpArbitraryFloatRecipINTEL = 5855, + OpArbitraryFloatRSqrtINTEL = 5856, + OpArbitraryFloatCbrtINTEL = 5857, + OpArbitraryFloatHypotINTEL = 5858, + OpArbitraryFloatSqrtINTEL = 5859, + OpArbitraryFloatLogINTEL = 5860, + OpArbitraryFloatLog2INTEL = 5861, + OpArbitraryFloatLog10INTEL = 5862, + OpArbitraryFloatLog1pINTEL = 5863, + OpArbitraryFloatExpINTEL = 5864, + OpArbitraryFloatExp2INTEL = 5865, + OpArbitraryFloatExp10INTEL = 5866, + OpArbitraryFloatExpm1INTEL = 5867, + OpArbitraryFloatSinINTEL = 5868, + OpArbitraryFloatCosINTEL = 5869, + OpArbitraryFloatSinCosINTEL = 5870, + OpArbitraryFloatSinPiINTEL = 5871, + OpArbitraryFloatCosPiINTEL = 5872, + OpArbitraryFloatASinINTEL = 5873, + OpArbitraryFloatASinPiINTEL = 5874, + OpArbitraryFloatACosINTEL = 5875, + OpArbitraryFloatACosPiINTEL = 5876, + OpArbitraryFloatATanINTEL = 5877, + OpArbitraryFloatATanPiINTEL = 5878, + OpArbitraryFloatATan2INTEL = 5879, + OpArbitraryFloatPowINTEL = 5880, + OpArbitraryFloatPowRINTEL = 5881, + OpArbitraryFloatPowNINTEL = 5882, OpLoopControlINTEL = 5887, + OpFixedSqrtINTEL = 5923, + OpFixedRecipINTEL = 5924, + OpFixedRsqrtINTEL = 5925, + OpFixedSinINTEL = 5926, + OpFixedCosINTEL = 5927, + OpFixedSinCosINTEL = 5928, + OpFixedSinPiINTEL = 5929, + OpFixedCosPiINTEL = 5930, + OpFixedSinCosPiINTEL = 5931, + OpFixedLogINTEL = 5932, + OpFixedExpINTEL = 5933, + OpPtrCastToCrossWorkgroupINTEL = 5934, + OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, @@ -1566,6 +1740,10 @@ spv = { OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, + OpTypeBufferSurfaceINTEL = 6086, + OpTypeStructContinuedINTEL = 6090, + OpConstantCompositeContinuedINTEL = 6091, + OpSpecConstantCompositeContinuedINTEL = 6092, }, } diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.py b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.py index 869b7f3ba5..09755a2039 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.py +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spirv.py @@ -56,6 +56,7 @@ spv = { 'OpenCL_C' : 3, 'OpenCL_CPP' : 4, 'HLSL' : 5, + 'CPP_for_OpenCL' : 6, }, 'ExecutionModel' : { @@ -137,6 +138,7 @@ spv = { 'SubgroupsPerWorkgroupId' : 37, 'LocalSizeId' : 38, 'LocalSizeHintId' : 39, + 'SubgroupUniformControlFlowKHR' : 4421, 'PostDepthCoverage' : 4446, 'DenormPreserve' : 4459, 'DenormFlushToZero' : 4460, @@ -155,10 +157,16 @@ spv = { 'SampleInterlockUnorderedEXT' : 5369, 'ShadingRateInterlockOrderedEXT' : 5370, 'ShadingRateInterlockUnorderedEXT' : 5371, + 'SharedLocalMemorySizeINTEL' : 5618, + 'RoundingModeRTPINTEL' : 5620, + 'RoundingModeRTNINTEL' : 5621, + 'FloatingPointModeALTINTEL' : 5622, + 'FloatingPointModeIEEEINTEL' : 5623, 'MaxWorkgroupSizeINTEL' : 5893, 'MaxWorkDimINTEL' : 5894, 'NoGlobalOffsetINTEL' : 5895, 'NumSIMDWorkitemsINTEL' : 5896, + 'SchedulerTargetFmaxMhzINTEL' : 5903, }, 'StorageClass' : { @@ -190,6 +198,8 @@ spv = { 'PhysicalStorageBuffer' : 5349, 'PhysicalStorageBufferEXT' : 5349, 'CodeSectionINTEL' : 5605, + 'DeviceOnlyINTEL' : 5936, + 'HostOnlyINTEL' : 5937, }, 'Dim' : { @@ -352,6 +362,8 @@ spv = { 'NSZ' : 2, 'AllowRecip' : 3, 'Fast' : 4, + 'AllowContractFastINTEL' : 16, + 'AllowReassocINTEL' : 17, }, 'FPFastMathModeMask' : { @@ -361,6 +373,8 @@ spv = { 'NSZ' : 0x00000004, 'AllowRecip' : 0x00000008, 'Fast' : 0x00000010, + 'AllowContractFastINTEL' : 0x00010000, + 'AllowReassocINTEL' : 0x00020000, }, 'FPRoundingMode' : { @@ -373,6 +387,7 @@ spv = { 'LinkageType' : { 'Export' : 0, 'Import' : 1, + 'LinkOnceODR' : 2, }, 'AccessQualifier' : { @@ -457,12 +472,22 @@ spv = { 'RestrictPointerEXT' : 5355, 'AliasedPointer' : 5356, 'AliasedPointerEXT' : 5356, + 'SIMTCallINTEL' : 5599, 'ReferencedIndirectlyINTEL' : 5602, + 'ClobberINTEL' : 5607, + 'SideEffectsINTEL' : 5608, + 'VectorComputeVariableINTEL' : 5624, + 'FuncParamIOKindINTEL' : 5625, + 'VectorComputeFunctionINTEL' : 5626, + 'StackCallINTEL' : 5627, + 'GlobalVariableOffsetINTEL' : 5628, 'CounterBuffer' : 5634, 'HlslCounterBufferGOOGLE' : 5634, 'HlslSemanticGOOGLE' : 5635, 'UserSemantic' : 5635, 'UserTypeGOOGLE' : 5636, + 'FunctionRoundingModeINTEL' : 5822, + 'FunctionDenormModeINTEL' : 5823, 'RegisterINTEL' : 5825, 'MemoryINTEL' : 5826, 'NumbanksINTEL' : 5827, @@ -475,6 +500,17 @@ spv = { 'MergeINTEL' : 5834, 'BankBitsINTEL' : 5835, 'ForcePow2DepthINTEL' : 5836, + 'BurstCoalesceINTEL' : 5899, + 'CacheSizeINTEL' : 5900, + 'DontStaticallyCoalesceINTEL' : 5901, + 'PrefetchINTEL' : 5902, + 'StallEnableINTEL' : 5905, + 'FuseLoopsInFunctionINTEL' : 5907, + 'BufferLocationINTEL' : 5921, + 'IOPipeStorageINTEL' : 5944, + 'FunctionFloatingPointModeINTEL' : 6080, + 'SingleElementVectorINTEL' : 6085, + 'VectorComputeCallableFunctionINTEL' : 6087, }, 'BuiltIn' : { @@ -586,7 +622,6 @@ spv = { 'ObjectToWorldNV' : 5330, 'WorldToObjectKHR' : 5331, 'WorldToObjectNV' : 5331, - 'HitTKHR' : 5332, 'HitTNV' : 5332, 'HitKindKHR' : 5333, 'HitKindNV' : 5333, @@ -627,6 +662,7 @@ spv = { 'LoopCoalesceINTEL' : 20, 'MaxInterleavingINTEL' : 21, 'SpeculatedIterationsINTEL' : 22, + 'NoFusionINTEL' : 23, }, 'LoopControlMask' : { @@ -647,6 +683,7 @@ spv = { 'LoopCoalesceINTEL' : 0x00100000, 'MaxInterleavingINTEL' : 0x00200000, 'SpeculatedIterationsINTEL' : 0x00400000, + 'NoFusionINTEL' : 0x00800000, }, 'FunctionControlShift' : { @@ -839,6 +876,9 @@ spv = { 'FragmentShadingRateKHR' : 4422, 'SubgroupBallotKHR' : 4423, 'DrawParameters' : 4427, + 'WorkgroupMemoryExplicitLayoutKHR' : 4428, + 'WorkgroupMemoryExplicitLayout8BitAccessKHR' : 4429, + 'WorkgroupMemoryExplicitLayout16BitAccessKHR' : 4430, 'SubgroupVoteKHR' : 4431, 'StorageBuffer16BitAccess' : 4433, 'StorageUniformBufferBlock16' : 4433, @@ -861,7 +901,9 @@ spv = { 'RoundingModeRTE' : 4467, 'RoundingModeRTZ' : 4468, 'RayQueryProvisionalKHR' : 4471, - 'RayTraversalPrimitiveCullingProvisionalKHR' : 4478, + 'RayQueryKHR' : 4472, + 'RayTraversalPrimitiveCullingKHR' : 4478, + 'RayTracingKHR' : 4479, 'Float16ImageAMD' : 5008, 'ImageGatherBiasLodAMD' : 5009, 'FragmentMaskAMD' : 5010, @@ -927,21 +969,50 @@ spv = { 'SubgroupBufferBlockIOINTEL' : 5569, 'SubgroupImageBlockIOINTEL' : 5570, 'SubgroupImageMediaBlockIOINTEL' : 5579, + 'RoundToInfinityINTEL' : 5582, + 'FloatingPointModeINTEL' : 5583, 'IntegerFunctions2INTEL' : 5584, 'FunctionPointersINTEL' : 5603, 'IndirectReferencesINTEL' : 5604, + 'AsmINTEL' : 5606, + 'AtomicFloat32MinMaxEXT' : 5612, + 'AtomicFloat64MinMaxEXT' : 5613, + 'AtomicFloat16MinMaxEXT' : 5616, + 'VectorComputeINTEL' : 5617, + 'VectorAnyINTEL' : 5619, + 'ExpectAssumeKHR' : 5629, 'SubgroupAvcMotionEstimationINTEL' : 5696, 'SubgroupAvcMotionEstimationIntraINTEL' : 5697, 'SubgroupAvcMotionEstimationChromaINTEL' : 5698, + 'VariableLengthArrayINTEL' : 5817, + 'FunctionFloatControlINTEL' : 5821, 'FPGAMemoryAttributesINTEL' : 5824, + 'FPFastMathModeINTEL' : 5837, + 'ArbitraryPrecisionIntegersINTEL' : 5844, + 'ArbitraryPrecisionFloatingPointINTEL' : 5845, 'UnstructuredLoopControlsINTEL' : 5886, 'FPGALoopControlsINTEL' : 5888, 'KernelAttributesINTEL' : 5892, 'FPGAKernelAttributesINTEL' : 5897, + 'FPGAMemoryAccessesINTEL' : 5898, + 'FPGAClusterAttributesINTEL' : 5904, + 'LoopFuseINTEL' : 5906, + 'FPGABufferLocationINTEL' : 5920, + 'ArbitraryPrecisionFixedPointINTEL' : 5922, + 'USMStorageClassesINTEL' : 5935, + 'IOPipesINTEL' : 5943, 'BlockingPipesINTEL' : 5945, 'FPGARegINTEL' : 5948, + 'DotProductInputAllKHR' : 6016, + 'DotProductInput4x8BitKHR' : 6017, + 'DotProductInput4x8BitPackedKHR' : 6018, + 'DotProductKHR' : 6019, + 'BitInstructions' : 6025, 'AtomicFloat32AddEXT' : 6033, 'AtomicFloat64AddEXT' : 6034, + 'LongConstantCompositeINTEL' : 6089, + 'AtomicFloat16AddEXT' : 6095, + 'DebugInfoModuleINTEL' : 6114, }, 'RayFlagsShift' : { @@ -1002,6 +1073,38 @@ spv = { 'Horizontal4Pixels' : 0x00000008, }, + 'FPDenormMode' : { + 'Preserve' : 0, + 'FlushToZero' : 1, + }, + + 'FPOperationMode' : { + 'IEEE' : 0, + 'ALT' : 1, + }, + + 'QuantizationModes' : { + 'TRN' : 0, + 'TRN_ZERO' : 1, + 'RND' : 2, + 'RND_ZERO' : 3, + 'RND_INF' : 4, + 'RND_MIN_INF' : 5, + 'RND_CONV' : 6, + 'RND_CONV_ODD' : 7, + }, + + 'OverflowModes' : { + 'WRAP' : 0, + 'SAT' : 1, + 'SAT_ZERO' : 2, + 'SAT_SYM' : 3, + }, + + 'PackedVectorFormat' : { + 'PackedVectorFormat4x8BitKHR' : 0, + }, + 'Op' : { 'OpNop' : 0, 'OpUndef' : 1, @@ -1354,7 +1457,18 @@ spv = { 'OpSubgroupAnyKHR' : 4429, 'OpSubgroupAllEqualKHR' : 4430, 'OpSubgroupReadInvocationKHR' : 4432, - 'OpTypeRayQueryProvisionalKHR' : 4472, + 'OpTraceRayKHR' : 4445, + 'OpExecuteCallableKHR' : 4446, + 'OpConvertUToAccelerationStructureKHR' : 4447, + 'OpIgnoreIntersectionKHR' : 4448, + 'OpTerminateRayKHR' : 4449, + 'OpSDotKHR' : 4450, + 'OpUDotKHR' : 4451, + 'OpSUDotKHR' : 4452, + 'OpSDotAccSatKHR' : 4453, + 'OpUDotAccSatKHR' : 4454, + 'OpSUDotAccSatKHR' : 4455, + 'OpTypeRayQueryKHR' : 4472, 'OpRayQueryInitializeKHR' : 4473, 'OpRayQueryTerminateKHR' : 4474, 'OpRayQueryGenerateIntersectionKHR' : 4475, @@ -1377,15 +1491,11 @@ spv = { 'OpWritePackedPrimitiveIndices4x8NV' : 5299, 'OpReportIntersectionKHR' : 5334, 'OpReportIntersectionNV' : 5334, - 'OpIgnoreIntersectionKHR' : 5335, 'OpIgnoreIntersectionNV' : 5335, - 'OpTerminateRayKHR' : 5336, 'OpTerminateRayNV' : 5336, 'OpTraceNV' : 5337, - 'OpTraceRayKHR' : 5337, 'OpTypeAccelerationStructureKHR' : 5341, 'OpTypeAccelerationStructureNV' : 5341, - 'OpExecuteCallableKHR' : 5344, 'OpExecuteCallableNV' : 5344, 'OpTypeCooperativeMatrixNV' : 5358, 'OpCooperativeMatrixLoadNV' : 5359, @@ -1420,8 +1530,15 @@ spv = { 'OpUSubSatINTEL' : 5596, 'OpIMul32x16INTEL' : 5597, 'OpUMul32x16INTEL' : 5598, - 'OpFunctionPointerINTEL' : 5600, + 'OpConstFunctionPointerINTEL' : 5600, 'OpFunctionPointerCallINTEL' : 5601, + 'OpAsmTargetINTEL' : 5609, + 'OpAsmINTEL' : 5610, + 'OpAsmCallINTEL' : 5611, + 'OpAtomicFMinEXT' : 5614, + 'OpAtomicFMaxEXT' : 5615, + 'OpAssumeTrueKHR' : 5630, + 'OpExpectKHR' : 5631, 'OpDecorateString' : 5632, 'OpDecorateStringGOOGLE' : 5632, 'OpMemberDecorateString' : 5633, @@ -1544,7 +1661,64 @@ spv = { 'OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL' : 5814, 'OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL' : 5815, 'OpSubgroupAvcSicGetInterRawSadsINTEL' : 5816, + 'OpVariableLengthArrayINTEL' : 5818, + 'OpSaveMemoryINTEL' : 5819, + 'OpRestoreMemoryINTEL' : 5820, + 'OpArbitraryFloatSinCosPiINTEL' : 5840, + 'OpArbitraryFloatCastINTEL' : 5841, + 'OpArbitraryFloatCastFromIntINTEL' : 5842, + 'OpArbitraryFloatCastToIntINTEL' : 5843, + 'OpArbitraryFloatAddINTEL' : 5846, + 'OpArbitraryFloatSubINTEL' : 5847, + 'OpArbitraryFloatMulINTEL' : 5848, + 'OpArbitraryFloatDivINTEL' : 5849, + 'OpArbitraryFloatGTINTEL' : 5850, + 'OpArbitraryFloatGEINTEL' : 5851, + 'OpArbitraryFloatLTINTEL' : 5852, + 'OpArbitraryFloatLEINTEL' : 5853, + 'OpArbitraryFloatEQINTEL' : 5854, + 'OpArbitraryFloatRecipINTEL' : 5855, + 'OpArbitraryFloatRSqrtINTEL' : 5856, + 'OpArbitraryFloatCbrtINTEL' : 5857, + 'OpArbitraryFloatHypotINTEL' : 5858, + 'OpArbitraryFloatSqrtINTEL' : 5859, + 'OpArbitraryFloatLogINTEL' : 5860, + 'OpArbitraryFloatLog2INTEL' : 5861, + 'OpArbitraryFloatLog10INTEL' : 5862, + 'OpArbitraryFloatLog1pINTEL' : 5863, + 'OpArbitraryFloatExpINTEL' : 5864, + 'OpArbitraryFloatExp2INTEL' : 5865, + 'OpArbitraryFloatExp10INTEL' : 5866, + 'OpArbitraryFloatExpm1INTEL' : 5867, + 'OpArbitraryFloatSinINTEL' : 5868, + 'OpArbitraryFloatCosINTEL' : 5869, + 'OpArbitraryFloatSinCosINTEL' : 5870, + 'OpArbitraryFloatSinPiINTEL' : 5871, + 'OpArbitraryFloatCosPiINTEL' : 5872, + 'OpArbitraryFloatASinINTEL' : 5873, + 'OpArbitraryFloatASinPiINTEL' : 5874, + 'OpArbitraryFloatACosINTEL' : 5875, + 'OpArbitraryFloatACosPiINTEL' : 5876, + 'OpArbitraryFloatATanINTEL' : 5877, + 'OpArbitraryFloatATanPiINTEL' : 5878, + 'OpArbitraryFloatATan2INTEL' : 5879, + 'OpArbitraryFloatPowINTEL' : 5880, + 'OpArbitraryFloatPowRINTEL' : 5881, + 'OpArbitraryFloatPowNINTEL' : 5882, 'OpLoopControlINTEL' : 5887, + 'OpFixedSqrtINTEL' : 5923, + 'OpFixedRecipINTEL' : 5924, + 'OpFixedRsqrtINTEL' : 5925, + 'OpFixedSinINTEL' : 5926, + 'OpFixedCosINTEL' : 5927, + 'OpFixedSinCosINTEL' : 5928, + 'OpFixedSinPiINTEL' : 5929, + 'OpFixedCosPiINTEL' : 5930, + 'OpFixedSinCosPiINTEL' : 5931, + 'OpFixedLogINTEL' : 5932, + 'OpFixedExpINTEL' : 5933, + 'OpPtrCastToCrossWorkgroupINTEL' : 5934, + 'OpCrossWorkgroupCastToPtrINTEL' : 5938, 'OpReadPipeBlockingINTEL' : 5946, 'OpWritePipeBlockingINTEL' : 5947, 'OpFPGARegINTEL' : 5949, @@ -1566,6 +1740,10 @@ spv = { 'OpRayQueryGetIntersectionObjectToWorldKHR' : 6031, 'OpRayQueryGetIntersectionWorldToObjectKHR' : 6032, 'OpAtomicFAddEXT' : 6035, + 'OpTypeBufferSurfaceINTEL' : 6086, + 'OpTypeStructContinuedINTEL' : 6090, + 'OpConstantCompositeContinuedINTEL' : 6091, + 'OpSpecConstantCompositeContinuedINTEL' : 6092, }, } diff --git a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spv.d b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spv.d index 714e77f000..179a6b1604 100644 --- a/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spv.d +++ b/third_party/spirv-tools/external/spirv-headers/include/spirv/unified1/spv.d @@ -64,6 +64,7 @@ enum SourceLanguage : uint OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, + CPP_for_OpenCL = 6, } enum ExecutionModel : uint @@ -149,6 +150,7 @@ enum ExecutionMode : uint SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, + SubgroupUniformControlFlowKHR = 4421, PostDepthCoverage = 4446, DenormPreserve = 4459, DenormFlushToZero = 4460, @@ -167,10 +169,16 @@ enum ExecutionMode : uint SampleInterlockUnorderedEXT = 5369, ShadingRateInterlockOrderedEXT = 5370, ShadingRateInterlockUnorderedEXT = 5371, + SharedLocalMemorySizeINTEL = 5618, + RoundingModeRTPINTEL = 5620, + RoundingModeRTNINTEL = 5621, + FloatingPointModeALTINTEL = 5622, + FloatingPointModeIEEEINTEL = 5623, MaxWorkgroupSizeINTEL = 5893, MaxWorkDimINTEL = 5894, NoGlobalOffsetINTEL = 5895, NumSIMDWorkitemsINTEL = 5896, + SchedulerTargetFmaxMhzINTEL = 5903, } enum StorageClass : uint @@ -203,6 +211,8 @@ enum StorageClass : uint PhysicalStorageBuffer = 5349, PhysicalStorageBufferEXT = 5349, CodeSectionINTEL = 5605, + DeviceOnlyINTEL = 5936, + HostOnlyINTEL = 5937, } enum Dim : uint @@ -374,6 +384,8 @@ enum FPFastMathModeShift : uint NSZ = 2, AllowRecip = 3, Fast = 4, + AllowContractFastINTEL = 16, + AllowReassocINTEL = 17, } enum FPFastMathModeMask : uint @@ -384,6 +396,8 @@ enum FPFastMathModeMask : uint NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, + AllowContractFastINTEL = 0x00010000, + AllowReassocINTEL = 0x00020000, } enum FPRoundingMode : uint @@ -398,6 +412,7 @@ enum LinkageType : uint { Export = 0, Import = 1, + LinkOnceODR = 2, } enum AccessQualifier : uint @@ -485,12 +500,22 @@ enum Decoration : uint RestrictPointerEXT = 5355, AliasedPointer = 5356, AliasedPointerEXT = 5356, + SIMTCallINTEL = 5599, ReferencedIndirectlyINTEL = 5602, + ClobberINTEL = 5607, + SideEffectsINTEL = 5608, + VectorComputeVariableINTEL = 5624, + FuncParamIOKindINTEL = 5625, + VectorComputeFunctionINTEL = 5626, + StackCallINTEL = 5627, + GlobalVariableOffsetINTEL = 5628, CounterBuffer = 5634, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, UserSemantic = 5635, UserTypeGOOGLE = 5636, + FunctionRoundingModeINTEL = 5822, + FunctionDenormModeINTEL = 5823, RegisterINTEL = 5825, MemoryINTEL = 5826, NumbanksINTEL = 5827, @@ -503,6 +528,17 @@ enum Decoration : uint MergeINTEL = 5834, BankBitsINTEL = 5835, ForcePow2DepthINTEL = 5836, + BurstCoalesceINTEL = 5899, + CacheSizeINTEL = 5900, + DontStaticallyCoalesceINTEL = 5901, + PrefetchINTEL = 5902, + StallEnableINTEL = 5905, + FuseLoopsInFunctionINTEL = 5907, + BufferLocationINTEL = 5921, + IOPipeStorageINTEL = 5944, + FunctionFloatingPointModeINTEL = 6080, + SingleElementVectorINTEL = 6085, + VectorComputeCallableFunctionINTEL = 6087, } enum BuiltIn : uint @@ -615,7 +651,6 @@ enum BuiltIn : uint ObjectToWorldNV = 5330, WorldToObjectKHR = 5331, WorldToObjectNV = 5331, - HitTKHR = 5332, HitTNV = 5332, HitKindKHR = 5333, HitKindNV = 5333, @@ -659,6 +694,7 @@ enum LoopControlShift : uint LoopCoalesceINTEL = 20, MaxInterleavingINTEL = 21, SpeculatedIterationsINTEL = 22, + NoFusionINTEL = 23, } enum LoopControlMask : uint @@ -680,6 +716,7 @@ enum LoopControlMask : uint LoopCoalesceINTEL = 0x00100000, MaxInterleavingINTEL = 0x00200000, SpeculatedIterationsINTEL = 0x00400000, + NoFusionINTEL = 0x00800000, } enum FunctionControlShift : uint @@ -884,6 +921,9 @@ enum Capability : uint FragmentShadingRateKHR = 4422, SubgroupBallotKHR = 4423, DrawParameters = 4427, + WorkgroupMemoryExplicitLayoutKHR = 4428, + WorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, + WorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, @@ -906,7 +946,9 @@ enum Capability : uint RoundingModeRTE = 4467, RoundingModeRTZ = 4468, RayQueryProvisionalKHR = 4471, - RayTraversalPrimitiveCullingProvisionalKHR = 4478, + RayQueryKHR = 4472, + RayTraversalPrimitiveCullingKHR = 4478, + RayTracingKHR = 4479, Float16ImageAMD = 5008, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, @@ -972,21 +1014,50 @@ enum Capability : uint SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, SubgroupImageMediaBlockIOINTEL = 5579, + RoundToInfinityINTEL = 5582, + FloatingPointModeINTEL = 5583, IntegerFunctions2INTEL = 5584, FunctionPointersINTEL = 5603, IndirectReferencesINTEL = 5604, + AsmINTEL = 5606, + AtomicFloat32MinMaxEXT = 5612, + AtomicFloat64MinMaxEXT = 5613, + AtomicFloat16MinMaxEXT = 5616, + VectorComputeINTEL = 5617, + VectorAnyINTEL = 5619, + ExpectAssumeKHR = 5629, SubgroupAvcMotionEstimationINTEL = 5696, SubgroupAvcMotionEstimationIntraINTEL = 5697, SubgroupAvcMotionEstimationChromaINTEL = 5698, + VariableLengthArrayINTEL = 5817, + FunctionFloatControlINTEL = 5821, FPGAMemoryAttributesINTEL = 5824, + FPFastMathModeINTEL = 5837, + ArbitraryPrecisionIntegersINTEL = 5844, + ArbitraryPrecisionFloatingPointINTEL = 5845, UnstructuredLoopControlsINTEL = 5886, FPGALoopControlsINTEL = 5888, KernelAttributesINTEL = 5892, FPGAKernelAttributesINTEL = 5897, + FPGAMemoryAccessesINTEL = 5898, + FPGAClusterAttributesINTEL = 5904, + LoopFuseINTEL = 5906, + FPGABufferLocationINTEL = 5920, + ArbitraryPrecisionFixedPointINTEL = 5922, + USMStorageClassesINTEL = 5935, + IOPipesINTEL = 5943, BlockingPipesINTEL = 5945, FPGARegINTEL = 5948, + DotProductInputAllKHR = 6016, + DotProductInput4x8BitKHR = 6017, + DotProductInput4x8BitPackedKHR = 6018, + DotProductKHR = 6019, + BitInstructions = 6025, AtomicFloat32AddEXT = 6033, AtomicFloat64AddEXT = 6034, + LongConstantCompositeINTEL = 6089, + AtomicFloat16AddEXT = 6095, + DebugInfoModuleINTEL = 6114, } enum RayFlagsShift : uint @@ -1054,6 +1125,43 @@ enum FragmentShadingRateMask : uint Horizontal4Pixels = 0x00000008, } +enum FPDenormMode : uint +{ + Preserve = 0, + FlushToZero = 1, +} + +enum FPOperationMode : uint +{ + IEEE = 0, + ALT = 1, +} + +enum QuantizationModes : uint +{ + TRN = 0, + TRN_ZERO = 1, + RND = 2, + RND_ZERO = 3, + RND_INF = 4, + RND_MIN_INF = 5, + RND_CONV = 6, + RND_CONV_ODD = 7, +} + +enum OverflowModes : uint +{ + WRAP = 0, + SAT = 1, + SAT_ZERO = 2, + SAT_SYM = 3, +} + +enum PackedVectorFormat : uint +{ + PackedVectorFormat4x8BitKHR = 0, +} + enum Op : uint { OpNop = 0, @@ -1407,7 +1515,18 @@ enum Op : uint OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, - OpTypeRayQueryProvisionalKHR = 4472, + OpTraceRayKHR = 4445, + OpExecuteCallableKHR = 4446, + OpConvertUToAccelerationStructureKHR = 4447, + OpIgnoreIntersectionKHR = 4448, + OpTerminateRayKHR = 4449, + OpSDotKHR = 4450, + OpUDotKHR = 4451, + OpSUDotKHR = 4452, + OpSDotAccSatKHR = 4453, + OpUDotAccSatKHR = 4454, + OpSUDotAccSatKHR = 4455, + OpTypeRayQueryKHR = 4472, OpRayQueryInitializeKHR = 4473, OpRayQueryTerminateKHR = 4474, OpRayQueryGenerateIntersectionKHR = 4475, @@ -1430,15 +1549,11 @@ enum Op : uint OpWritePackedPrimitiveIndices4x8NV = 5299, OpReportIntersectionKHR = 5334, OpReportIntersectionNV = 5334, - OpIgnoreIntersectionKHR = 5335, OpIgnoreIntersectionNV = 5335, - OpTerminateRayKHR = 5336, OpTerminateRayNV = 5336, OpTraceNV = 5337, - OpTraceRayKHR = 5337, OpTypeAccelerationStructureKHR = 5341, OpTypeAccelerationStructureNV = 5341, - OpExecuteCallableKHR = 5344, OpExecuteCallableNV = 5344, OpTypeCooperativeMatrixNV = 5358, OpCooperativeMatrixLoadNV = 5359, @@ -1473,8 +1588,15 @@ enum Op : uint OpUSubSatINTEL = 5596, OpIMul32x16INTEL = 5597, OpUMul32x16INTEL = 5598, - OpFunctionPointerINTEL = 5600, + OpConstFunctionPointerINTEL = 5600, OpFunctionPointerCallINTEL = 5601, + OpAsmTargetINTEL = 5609, + OpAsmINTEL = 5610, + OpAsmCallINTEL = 5611, + OpAtomicFMinEXT = 5614, + OpAtomicFMaxEXT = 5615, + OpAssumeTrueKHR = 5630, + OpExpectKHR = 5631, OpDecorateString = 5632, OpDecorateStringGOOGLE = 5632, OpMemberDecorateString = 5633, @@ -1597,7 +1719,64 @@ enum Op : uint OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, OpSubgroupAvcSicGetInterRawSadsINTEL = 5816, + OpVariableLengthArrayINTEL = 5818, + OpSaveMemoryINTEL = 5819, + OpRestoreMemoryINTEL = 5820, + OpArbitraryFloatSinCosPiINTEL = 5840, + OpArbitraryFloatCastINTEL = 5841, + OpArbitraryFloatCastFromIntINTEL = 5842, + OpArbitraryFloatCastToIntINTEL = 5843, + OpArbitraryFloatAddINTEL = 5846, + OpArbitraryFloatSubINTEL = 5847, + OpArbitraryFloatMulINTEL = 5848, + OpArbitraryFloatDivINTEL = 5849, + OpArbitraryFloatGTINTEL = 5850, + OpArbitraryFloatGEINTEL = 5851, + OpArbitraryFloatLTINTEL = 5852, + OpArbitraryFloatLEINTEL = 5853, + OpArbitraryFloatEQINTEL = 5854, + OpArbitraryFloatRecipINTEL = 5855, + OpArbitraryFloatRSqrtINTEL = 5856, + OpArbitraryFloatCbrtINTEL = 5857, + OpArbitraryFloatHypotINTEL = 5858, + OpArbitraryFloatSqrtINTEL = 5859, + OpArbitraryFloatLogINTEL = 5860, + OpArbitraryFloatLog2INTEL = 5861, + OpArbitraryFloatLog10INTEL = 5862, + OpArbitraryFloatLog1pINTEL = 5863, + OpArbitraryFloatExpINTEL = 5864, + OpArbitraryFloatExp2INTEL = 5865, + OpArbitraryFloatExp10INTEL = 5866, + OpArbitraryFloatExpm1INTEL = 5867, + OpArbitraryFloatSinINTEL = 5868, + OpArbitraryFloatCosINTEL = 5869, + OpArbitraryFloatSinCosINTEL = 5870, + OpArbitraryFloatSinPiINTEL = 5871, + OpArbitraryFloatCosPiINTEL = 5872, + OpArbitraryFloatASinINTEL = 5873, + OpArbitraryFloatASinPiINTEL = 5874, + OpArbitraryFloatACosINTEL = 5875, + OpArbitraryFloatACosPiINTEL = 5876, + OpArbitraryFloatATanINTEL = 5877, + OpArbitraryFloatATanPiINTEL = 5878, + OpArbitraryFloatATan2INTEL = 5879, + OpArbitraryFloatPowINTEL = 5880, + OpArbitraryFloatPowRINTEL = 5881, + OpArbitraryFloatPowNINTEL = 5882, OpLoopControlINTEL = 5887, + OpFixedSqrtINTEL = 5923, + OpFixedRecipINTEL = 5924, + OpFixedRsqrtINTEL = 5925, + OpFixedSinINTEL = 5926, + OpFixedCosINTEL = 5927, + OpFixedSinCosINTEL = 5928, + OpFixedSinPiINTEL = 5929, + OpFixedCosPiINTEL = 5930, + OpFixedSinCosPiINTEL = 5931, + OpFixedLogINTEL = 5932, + OpFixedExpINTEL = 5933, + OpPtrCastToCrossWorkgroupINTEL = 5934, + OpCrossWorkgroupCastToPtrINTEL = 5938, OpReadPipeBlockingINTEL = 5946, OpWritePipeBlockingINTEL = 5947, OpFPGARegINTEL = 5949, @@ -1619,6 +1798,10 @@ enum Op : uint OpRayQueryGetIntersectionObjectToWorldKHR = 6031, OpRayQueryGetIntersectionWorldToObjectKHR = 6032, OpAtomicFAddEXT = 6035, + OpTypeBufferSurfaceINTEL = 6086, + OpTypeStructContinuedINTEL = 6090, + OpConstantCompositeContinuedINTEL = 6091, + OpSpecConstantCompositeContinuedINTEL = 6092, } diff --git a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/CMakeLists.txt b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/CMakeLists.txt index c6241510ed..fa7ef50fac 100644 --- a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/CMakeLists.txt +++ b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8) +cmake_minimum_required(VERSION 3.0) set(CMAKE_INSTALL_PREFIX "install" CACHE STRING "prefix" FORCE) diff --git a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/bin/makeHeaders b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/bin/makeHeaders index 0ca0b2f251..7b4959ea07 100755 --- a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/bin/makeHeaders +++ b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/bin/makeHeaders @@ -4,4 +4,4 @@ python3 bin/makeExtinstHeaders.py cd ../../include/spirv/unified1 ../../../tools/buildHeaders/build/install/bin/buildSpvHeaders -H spirv.core.grammar.json -dos2unix spirv.* SpirV.* spv.* +dos2unix spirv.* spv.* diff --git a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/header.cpp b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/header.cpp index 926905e9ce..dc780ef372 100644 --- a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/header.cpp +++ b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/header.cpp @@ -500,7 +500,7 @@ namespace { virtual std::string fmtEnumUse(const std::string& opPrefix, const std::string& name) const { return pre() + name; } - virtual void printHasResultType(std::ostream& out) const + virtual void printHasResultType(std::ostream& out) const override { const Json::Value& enums = spvRoot["spv"]["enum"]; @@ -643,7 +643,7 @@ namespace { } // Add type prefix for scoped enum - virtual std::string fmtEnumUse(const std::string& opPrefix, const std::string& name) const { return opPrefix + "::" + name; } + virtual std::string fmtEnumUse(const std::string& opPrefix, const std::string& name) const override { return opPrefix + "::" + name; } std::string headerGuardSuffix() const override { return "HPP"; } }; diff --git a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.cpp b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.cpp index 2118678b0a..67b5bce5c0 100644 --- a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.cpp +++ b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -61,6 +62,10 @@ EnumValues ImageChannelDataTypeParams; EnumValues ImageOperandsParams; EnumValues FPFastMathParams; EnumValues FPRoundingModeParams; +EnumValues FPDenormModeParams; +EnumValues FPOperationModeParams; +EnumValues QuantizationModesParams; +EnumValues OverflowModesParams; EnumValues LinkageTypeParams; EnumValues DecorationParams; EnumValues BuiltInParams; @@ -82,6 +87,7 @@ EnumValues RayQueryIntersectionParams; EnumValues RayQueryCommittedIntersectionTypeParams; EnumValues RayQueryCandidateIntersectionTypeParams; EnumValues FragmentShadingRateParams; +EnumValues PackedVectorFormatParams; std::pair ReadFile(const std::string& path) { @@ -178,6 +184,14 @@ ClassOptionality ToOperandClassAndOptionality(const std::string& operandKind, co type = OperandImageChannelDataType; } else if (operandKind == "FPRoundingMode") { type = OperandFPRoundingMode; + } else if (operandKind == "FPDenormMode") { + type = OperandFPDenormMode; + } else if (operandKind == "FPOperationMode") { + type = OperandFPOperationMode; + } else if (operandKind == "QuantizationModes") { + type = OperandQuantizationModes; + } else if (operandKind == "OverflowModes") { + type = OperandOverflowModes; } else if (operandKind == "LinkageType") { type = OperandLinkageType; } else if (operandKind == "AccessQualifier") { @@ -218,6 +232,8 @@ ClassOptionality ToOperandClassAndOptionality(const std::string& operandKind, co type = OperandRayQueryCandidateIntersectionType; } else if (operandKind == "FragmentShadingRate") { type = OperandFragmentShadingRate; + } else if (operandKind == "PackedVectorFormat") { + type = OperandPackedVectorFormat; } if (type == OperandNone) { @@ -320,6 +336,8 @@ void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders) // process the instructions const Json::Value insts = root["instructions"]; + unsigned maxOpcode = 0; + bool firstOpcode = true; for (const auto& inst : insts) { const auto printingClass = inst["class"].asString(); if (printingClass.size() == 0) { @@ -335,6 +353,19 @@ void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders) } const auto opcode = inst["opcode"].asUInt(); const std::string name = inst["opname"].asString(); + if (firstOpcode) { + maxOpcode = opcode; + firstOpcode = false; + } else { + if (maxOpcode > opcode) { + std::cerr << "Error: " << name + << " is out of order. It follows the instruction with opcode " << maxOpcode + << std::endl; + std::exit(1); + } else { + maxOpcode = opcode; + } + } EnumCaps caps = getCaps(inst); std::string version = inst["version"].asString(); std::string lastVersion = inst["lastVersion"].asString(); @@ -378,12 +409,27 @@ void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders) return result; }; + unsigned maxValue = 0; + bool firstValue = true; for (const auto& enumerant : source["enumerants"]) { unsigned value; bool skip_zero_in_bitfield; std::tie(value, skip_zero_in_bitfield) = getValue(enumerant); if (skip_zero_in_bitfield) continue; + if (firstValue) { + maxValue = value; + firstValue = false; + } else { + if (maxValue > value) { + std::cerr << "Error: " << source["kind"] << " enumerant " << enumerant["enumerant"] + << " is out of order. It has value " << value + << " but follows the enumerant with value " << maxValue << std::endl; + std::exit(1); + } else { + maxValue = value; + } + } EnumCaps caps(getCaps(enumerant)); std::string version = enumerant["version"].asString(); std::string lastVersion = enumerant["lastVersion"].asString(); @@ -452,6 +498,14 @@ void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders) establishOperandClass(enumName, OperandFPFastMath, &FPFastMathParams, operandEnum, category); } else if (enumName == "FPRoundingMode") { establishOperandClass(enumName, OperandFPRoundingMode, &FPRoundingModeParams, operandEnum, category); + } else if (enumName == "FPDenormMode") { + establishOperandClass(enumName, OperandFPDenormMode, &FPDenormModeParams, operandEnum, category); + } else if (enumName == "FPOperationMode") { + establishOperandClass(enumName, OperandFPOperationMode, &FPOperationModeParams, operandEnum, category); + } else if (enumName == "QuantizationModes") { + establishOperandClass(enumName, OperandQuantizationModes, &QuantizationModesParams, operandEnum, category); + } else if (enumName == "OverflowModes") { + establishOperandClass(enumName, OperandOverflowModes, &OverflowModesParams, operandEnum, category); } else if (enumName == "LinkageType") { establishOperandClass(enumName, OperandLinkageType, &LinkageTypeParams, operandEnum, category); } else if (enumName == "FunctionParameterAttribute") { @@ -488,6 +542,8 @@ void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders) establishOperandClass(enumName, OperandRayQueryCandidateIntersectionType, &RayQueryCandidateIntersectionTypeParams, operandEnum, category); } else if (enumName == "FragmentShadingRate") { establishOperandClass(enumName, OperandFragmentShadingRate, &FragmentShadingRateParams, operandEnum, category); + } else if (enumName == "PackedVectorFormat") { + establishOperandClass(enumName, OperandPackedVectorFormat, &PackedVectorFormatParams, operandEnum, category); } } } diff --git a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.h b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.h index 72c7cded98..3be645687b 100644 --- a/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.h +++ b/third_party/spirv-tools/external/spirv-headers/tools/buildHeaders/jsonToSpirv.h @@ -41,6 +41,8 @@ std::pair ReadFile(const std::string& path); void jsonToSpirv(const std::string& jsonPath, bool buildingHeaders); // For parameterizing operands. +// The ordering here affects the printing order in the SPIR-V specification. +// Please add new operand classes at the end. enum OperandClass { OperandNone, OperandId, @@ -89,6 +91,11 @@ enum OperandClass { OperandRayQueryCommittedIntersectionType, OperandRayQueryCandidateIntersectionType, OperandFragmentShadingRate, + OperandFPDenormMode, + OperandFPOperationMode, + OperandQuantizationModes, + OperandOverflowModes, + OperandPackedVectorFormat, OperandOpcode, diff --git a/third_party/spirv-tools/include/spirv-tools/instrument.hpp b/third_party/spirv-tools/include/spirv-tools/instrument.hpp index 9c01cb693e..a19491fd3c 100644 --- a/third_party/spirv-tools/include/spirv-tools/instrument.hpp +++ b/third_party/spirv-tools/include/spirv-tools/instrument.hpp @@ -170,7 +170,15 @@ static const int kInstMaxOutCnt = kInstStageOutCnt + 4; static const int kInstErrorBindlessBounds = 0; static const int kInstErrorBindlessUninit = 1; static const int kInstErrorBuffAddrUnallocRef = 2; -static const int kInstErrorBindlessBuffOOB = 3; +// Deleted: static const int kInstErrorBindlessBuffOOB = 3; +// This comment will will remain for 2 releases to allow +// for the transition of all builds. Buffer OOB is +// generating the following four differentiated codes instead: +static const int kInstErrorBuffOOBUniform = 4; +static const int kInstErrorBuffOOBStorage = 5; +static const int kInstErrorBuffOOBUniformTexel = 6; +static const int kInstErrorBuffOOBStorageTexel = 7; +static const int kInstErrorMax = kInstErrorBuffOOBStorageTexel; // Direct Input Buffer Offsets // diff --git a/third_party/spirv-tools/include/spirv-tools/libspirv.h b/third_party/spirv-tools/include/spirv-tools/libspirv.h index a0114c3f4b..039dab18ae 100644 --- a/third_party/spirv-tools/include/spirv-tools/libspirv.h +++ b/third_party/spirv-tools/include/spirv-tools/libspirv.h @@ -113,6 +113,9 @@ typedef enum spv_endianness_t { // Sometimes we also need to be able to express the fact that an operand // is a member of an optional tuple of values. In that case the first member // would be optional, and the subsequent members would be required. +// +// NOTE: Although we don't promise binary compatibility, as a courtesy, please +// add new enum values at the end. typedef enum spv_operand_type_t { // A sentinel value. SPV_OPERAND_TYPE_NONE = 0, @@ -167,12 +170,8 @@ typedef enum spv_operand_type_t { SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS, // SPIR-V Sec 3.29 SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO, // SPIR-V Sec 3.30 SPV_OPERAND_TYPE_CAPABILITY, // SPIR-V Sec 3.31 - SPV_OPERAND_TYPE_RAY_FLAGS, // SPIR-V Sec 3.RF - SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION, // SPIR-V Sec 3.RQIntersection - SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE, // SPIR-V Sec - // 3.RQCommitted - SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE, // SPIR-V Sec - // 3.RQCandidate + + // NOTE: New concrete enum values should be added at the end. // Set 5: Operands that are a single word bitmask. // Sometimes a set bit indicates the instruction requires still more operands. @@ -184,7 +183,10 @@ typedef enum spv_operand_type_t { SPV_OPERAND_TYPE_MEMORY_ACCESS, // SPIR-V Sec 3.26 SPV_OPERAND_TYPE_FRAGMENT_SHADING_RATE, // SPIR-V Sec 3.FSR -// The remaining operand types are only used internally by the assembler. +// NOTE: New concrete enum values should be added at the end. + +// The "optional" and "variable" operand types are only used internally by +// the assembler and the binary parser. // There are two categories: // Optional : expands to 0 or 1 operand, like ? in regular expressions. // Variable : expands to 0, 1 or many operands or pairs of operands. @@ -260,6 +262,29 @@ typedef enum spv_operand_type_t { SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION, // Sec 3.6 SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY, // Sec 3.7 + // The following are concrete enum types from SPV_INTEL_float_controls2 + // https://github.com/intel/llvm/blob/39fa9b0cbfbae88327118990a05c5b387b56d2ef/sycl/doc/extensions/SPIRV/SPV_INTEL_float_controls2.asciidoc + SPV_OPERAND_TYPE_FPDENORM_MODE, // Sec 3.17 FP Denorm Mode + SPV_OPERAND_TYPE_FPOPERATION_MODE, // Sec 3.18 FP Operation Mode + // A value enum from https://github.com/KhronosGroup/SPIRV-Headers/pull/177 + SPV_OPERAND_TYPE_QUANTIZATION_MODES, + // A value enum from https://github.com/KhronosGroup/SPIRV-Headers/pull/177 + SPV_OPERAND_TYPE_OVERFLOW_MODES, + + // Concrete operand types for the provisional Vulkan ray tracing feature. + SPV_OPERAND_TYPE_RAY_FLAGS, // SPIR-V Sec 3.RF + SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION, // SPIR-V Sec 3.RQIntersection + SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE, // SPIR-V Sec + // 3.RQCommitted + SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE, // SPIR-V Sec + // 3.RQCandidate + + // Concrete operand types for integer dot product. + // Packed vector format + SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT, // SPIR-V Sec 3.x + // An optional packed vector format + SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT, + // This is a sentinel value, and does not represent an operand type. // It should come last. SPV_OPERAND_TYPE_NUM_OPERAND_TYPES, @@ -482,7 +507,7 @@ typedef enum { SPV_ENV_OPENCL_EMBEDDED_2_2, // OpenCL Embedded Profile 2.2 latest revision. SPV_ENV_UNIVERSAL_1_3, // SPIR-V 1.3 latest revision, no other restrictions. SPV_ENV_VULKAN_1_1, // Vulkan 1.1 latest revision. - SPV_ENV_WEBGPU_0, // Work in progress WebGPU 1.0. + SPV_ENV_WEBGPU_0, // DEPRECATED, may be removed in the future. SPV_ENV_UNIVERSAL_1_4, // SPIR-V 1.4 latest revision, no other restrictions. // Vulkan 1.1 with VK_KHR_spirv_1_4, i.e. SPIR-V 1.4 binary. @@ -583,6 +608,8 @@ SPIRV_TOOLS_EXPORT void spvValidatorOptionsSetRelaxLogicalPointer( // 3) Pointers that are actaul parameters on function calls do not have to point // to the same type pointed as the formal parameter. The types just need to // logically match. +// 4) GLSLstd450 Interpolate* instructions can have a load of an interpolant +// for a first argument. SPIRV_TOOLS_EXPORT void spvValidatorOptionsSetBeforeHlslLegalization( spv_validator_options options, bool val); @@ -620,6 +647,12 @@ SPIRV_TOOLS_EXPORT void spvValidatorOptionsSetUniformBufferStandardLayout( SPIRV_TOOLS_EXPORT void spvValidatorOptionsSetScalarBlockLayout( spv_validator_options options, bool val); +// Records whether the validator should use "scalar" block layout +// rules (as defined above) for Workgroup blocks. See Vulkan +// extension VK_KHR_workgroup_memory_explicit_layout. +SPIRV_TOOLS_EXPORT void spvValidatorOptionsSetWorkgroupScalarBlockLayout( + spv_validator_options options, bool val); + // Records whether or not the validator should skip validating standard // uniform/storage block layout. SPIRV_TOOLS_EXPORT void spvValidatorOptionsSetSkipBlockLayout( @@ -660,7 +693,7 @@ SPIRV_TOOLS_EXPORT void spvOptimizerOptionsSetPreserveSpecConstants( // Creates a reducer options object with default options. Returns a valid // options object. The object remains valid until it is passed into // |spvReducerOptionsDestroy|. -SPIRV_TOOLS_EXPORT spv_reducer_options spvReducerOptionsCreate(); +SPIRV_TOOLS_EXPORT spv_reducer_options spvReducerOptionsCreate(void); // Destroys the given reducer options object. SPIRV_TOOLS_EXPORT void spvReducerOptionsDestroy(spv_reducer_options options); @@ -687,7 +720,7 @@ SPIRV_TOOLS_EXPORT void spvReducerOptionsSetTargetFunction( // Creates a fuzzer options object with default options. Returns a valid // options object. The object remains valid until it is passed into // |spvFuzzerOptionsDestroy|. -SPIRV_TOOLS_EXPORT spv_fuzzer_options spvFuzzerOptionsCreate(); +SPIRV_TOOLS_EXPORT spv_fuzzer_options spvFuzzerOptionsCreate(void); // Destroys the given fuzzer options object. SPIRV_TOOLS_EXPORT void spvFuzzerOptionsDestroy(spv_fuzzer_options options); diff --git a/third_party/spirv-tools/include/spirv-tools/libspirv.hpp b/third_party/spirv-tools/include/spirv-tools/libspirv.hpp index 2018e4610c..0c31a18279 100644 --- a/third_party/spirv-tools/include/spirv-tools/libspirv.hpp +++ b/third_party/spirv-tools/include/spirv-tools/libspirv.hpp @@ -104,6 +104,12 @@ class ValidatorOptions { spvValidatorOptionsSetScalarBlockLayout(options_, val); } + // Enables scalar layout when validating Workgroup blocks. See + // VK_KHR_workgroup_memory_explicit_layout. + void SetWorkgroupScalarBlockLayout(bool val) { + spvValidatorOptionsSetWorkgroupScalarBlockLayout(options_, val); + } + // Skips validating standard uniform/storage buffer/push-constant layout. void SetSkipBlockLayout(bool val) { spvValidatorOptionsSetSkipBlockLayout(options_, val); @@ -130,6 +136,8 @@ class ValidatorOptions { // 3) Pointers that are actaul parameters on function calls do not have to // point to the same type pointed as the formal parameter. The types just // need to logically match. + // 4) GLSLstd450 Interpolate* instructions can have a load of an interpolant + // for a first argument. void SetBeforeHlslLegalization(bool val) { spvValidatorOptionsSetBeforeHlslLegalization(options_, val); } diff --git a/third_party/spirv-tools/include/spirv-tools/optimizer.hpp b/third_party/spirv-tools/include/spirv-tools/optimizer.hpp index f12774d6d7..700f59f70f 100644 --- a/third_party/spirv-tools/include/spirv-tools/optimizer.hpp +++ b/third_party/spirv-tools/include/spirv-tools/optimizer.hpp @@ -68,11 +68,6 @@ class Optimizer { // The instance will have an empty message consumer, which ignores all // messages from the library. Use SetMessageConsumer() to supply a consumer // if messages are of concern. - // - // For collections of passes that are meant to transform the input into - // another execution environment, then the source environment should be - // supplied. e.g. for VulkanToWebGPUPasses the environment should be - // SPV_ENV_VULKAN_1_1 not SPV_ENV_WEBGPU_0. explicit Optimizer(spv_target_env env); // Disables copy/move constructor/assignment operations. @@ -106,16 +101,6 @@ class Optimizer { // from time to time. Optimizer& RegisterSizePasses(); - // Registers passes that have been prescribed for converting from Vulkan to - // WebGPU. This sequence of passes is subject to constant review and will - // change from time to time. - Optimizer& RegisterVulkanToWebGPUPasses(); - - // Registers passes that have been prescribed for converting from WebGPU to - // Vulkan. This sequence of passes is subject to constant review and will - // change from time to time. - Optimizer& RegisterWebGPUToVulkanPasses(); - // Registers passes that attempt to legalize the generated code. // // Note: this recipe is specially designed for legalizing SPIR-V. It should be @@ -238,13 +223,6 @@ class Optimizer { // A null pass does nothing to the SPIR-V module to be optimized. Optimizer::PassToken CreateNullPass(); -// Creates a strip-atomic-counter-memory pass. -// A strip-atomic-counter-memory pass removes all usages of the -// AtomicCounterMemory bit in Memory Semantics bitmasks. This bit is a no-op in -// Vulkan, so isn't needed in that env. And the related capability is not -// allowed in WebGPU, so it is not allowed in that env. -Optimizer::PassToken CreateStripAtomicCounterMemoryPass(); - // Creates a strip-debug-info pass. // A strip-debug-info pass removes all debug instructions (as documented in // Section 3.32.2 of the SPIR-V spec) of the SPIR-V module to be optimized. @@ -536,6 +514,13 @@ Optimizer::PassToken CreateDeadInsertElimPass(); // eliminated with standard dead code elimination. Optimizer::PassToken CreateAggressiveDCEPass(); +// Creates a remove-unused-interface-variables pass. +// Removes variables referenced on the |OpEntryPoint| instruction that are not +// referenced in the entry point function or any function in its call tree. Note +// that this could cause the shader interface to no longer match other shader +// stages. +Optimizer::PassToken CreateRemoveUnusedInterfaceVariablesPass(); + // Creates an empty pass. // This is deprecated and will be removed. // TODO(jaebaek): remove this pass after handling glslang's broken unit tests. @@ -747,12 +732,16 @@ Optimizer::PassToken CreateCombineAccessChainsPass(); // The instrumentation will read and write buffers in debug // descriptor set |desc_set|. It will write |shader_id| in each output record // to identify the shader module which generated the record. -// |input_length_enable| controls instrumentation of runtime descriptor array -// references, and |input_init_enable| controls instrumentation of descriptor -// initialization checking, both of which require input buffer support. +// |desc_length_enable| controls instrumentation of runtime descriptor array +// references, |desc_init_enable| controls instrumentation of descriptor +// initialization checking, and |buff_oob_enable| controls instrumentation +// of storage and uniform buffer bounds checking, all of which require input +// buffer support. |texbuff_oob_enable| controls instrumentation of texel +// buffers, which does not require input buffer support. Optimizer::PassToken CreateInstBindlessCheckPass( - uint32_t desc_set, uint32_t shader_id, bool input_length_enable = false, - bool input_init_enable = false, bool input_buff_oob_enable = false); + uint32_t desc_set, uint32_t shader_id, bool desc_length_enable = false, + bool desc_init_enable = false, bool buff_oob_enable = false, + bool texbuff_oob_enable = false); // Create a pass to instrument physical buffer address checking // This pass instruments all physical buffer address references to check that @@ -798,30 +787,11 @@ Optimizer::PassToken CreateUpgradeMemoryModelPass(); // where an instruction is moved into a more deeply nested construct. Optimizer::PassToken CreateCodeSinkingPass(); -// Create a pass to adds initializers for OpVariable calls that require them -// in WebGPU. Currently this pass naively initializes variables that are -// missing an initializer with a null value. In the future it may initialize -// variables to the first value stored in them, if that is a constant. -Optimizer::PassToken CreateGenerateWebGPUInitializersPass(); - // Create a pass to fix incorrect storage classes. In order to make code // generation simpler, DXC may generate code where the storage classes do not // match up correctly. This pass will fix the errors that it can. Optimizer::PassToken CreateFixStorageClassPass(); -// Create a pass to legalize OpVectorShuffle operands going into WebGPU. WebGPU -// forbids using 0xFFFFFFFF, which indicates an undefined result, so this pass -// converts those literals to 0. -Optimizer::PassToken CreateLegalizeVectorShufflePass(); - -// Create a pass to decompose initialized variables into a seperate variable -// declaration and an initial store. -Optimizer::PassToken CreateDecomposeInitializedVariablesPass(); - -// Create a pass to attempt to split up invalid unreachable merge-blocks and -// continue-targets to legalize for WebGPU. -Optimizer::PassToken CreateSplitInvalidUnreachablePass(); - // Creates a graphics robust access pass. // // This pass injects code to clamp indexed accesses to buffers and internal @@ -875,6 +845,15 @@ Optimizer::PassToken CreateWrapOpKillPass(); // capabilities. Optimizer::PassToken CreateAmdExtToKhrPass(); +// Replaces the internal version of GLSLstd450 InterpolateAt* extended +// instructions with the externally valid version. The internal version allows +// an OpLoad of the interpolant for the first argument. This pass removes the +// OpLoad and replaces it with its pointer. glslang and possibly other +// frontends will create the internal version for HLSL. This pass will be part +// of HLSL legalization and should be called after interpolants have been +// propagated into their final positions. +Optimizer::PassToken CreateInterpolateFixupPass(); + } // namespace spvtools #endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ diff --git a/third_party/spirv-tools/kokoro/android/build.sh b/third_party/spirv-tools/kokoro/android/build.sh index c05c139a21..22c9117aaa 100644 --- a/third_party/spirv-tools/kokoro/android/build.sh +++ b/third_party/spirv-tools/kokoro/android/build.sh @@ -20,33 +20,5 @@ set -e # Display commands being run. set -x -BUILD_ROOT=$PWD -SRC=$PWD/github/SPIRV-Tools -TARGET_ARCH="armeabi-v7a with NEON" -export ANDROID_NDK=/opt/android-ndk-r15c - -# Get NINJA. -wget -q https://github.com/ninja-build/ninja/releases/download/v1.8.2/ninja-linux.zip -unzip -q ninja-linux.zip -export PATH="$PWD:$PATH" -git clone --depth=1 https://github.com/taka-no-me/android-cmake.git android-cmake -export TOOLCHAIN_PATH=$PWD/android-cmake/android.toolchain.cmake - - -cd $SRC -git clone --depth=1 https://github.com/KhronosGroup/SPIRV-Headers external/spirv-headers -git clone https://github.com/google/googletest external/googletest -cd external && cd googletest && git reset --hard 1fb1bb23bb8418dc73a5a9a82bbed31dc610fec7 && cd .. && cd .. -git clone --depth=1 https://github.com/google/effcee external/effcee -git clone --depth=1 https://github.com/google/re2 external/re2 - -mkdir build && cd $SRC/build - -# Invoke the build. -BUILD_SHA=${KOKORO_GITHUB_COMMIT:-$KOKORO_GITHUB_PULL_REQUEST_COMMIT} -echo $(date): Starting build... -cmake -DPYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Release -DANDROID_NATIVE_API_LEVEL=android-14 -DANDROID_ABI="armeabi-v7a with NEON" -DSPIRV_SKIP_TESTS=ON -DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_PATH -GNinja -DANDROID_NDK=$ANDROID_NDK .. - -echo $(date): Build everything... -ninja -echo $(date): Build completed. +SCRIPT_DIR=`dirname "$BASH_SOURCE"` +source $SCRIPT_DIR/../scripts/linux/build.sh ASAN clang cmake-android-ndk diff --git a/third_party/spirv-tools/kokoro/check-format/build.sh b/third_party/spirv-tools/kokoro/check-format/build.sh index 0c4b8d1ca7..8a5df9a835 100644 --- a/third_party/spirv-tools/kokoro/check-format/build.sh +++ b/third_party/spirv-tools/kokoro/check-format/build.sh @@ -35,7 +35,8 @@ git clone https://github.com/google/googletest external/googletest cd external && cd googletest && git reset --hard 1fb1bb23bb8418dc73a5a9a82bbed31dc610fec7 && cd .. && cd .. git clone --depth=1 https://github.com/google/effcee external/effcee git clone --depth=1 https://github.com/google/re2 external/re2 -curl -L http://llvm.org/svn/llvm-project/cfe/trunk/tools/clang-format/clang-format-diff.py -o utils/clang-format-diff.py; +# The --fail flag causes the command to fail on HTTP error response codes, like 404. +curl -L --fail https://raw.githubusercontent.com/llvm/llvm-project/main/clang/tools/clang-format/clang-format-diff.py -o utils/clang-format-diff.py echo $(date): Check formatting... ./utils/check_code_format.sh; diff --git a/third_party/spirv-tools/kokoro/linux-clang-asan/build.sh b/third_party/spirv-tools/kokoro/linux-clang-asan/build.sh index 8f86e6ec71..5cca362d32 100644 --- a/third_party/spirv-tools/kokoro/linux-clang-asan/build.sh +++ b/third_party/spirv-tools/kokoro/linux-clang-asan/build.sh @@ -21,4 +21,4 @@ set -e set -x SCRIPT_DIR=`dirname "$BASH_SOURCE"` -source $SCRIPT_DIR/../scripts/linux/build.sh ASAN clang +source $SCRIPT_DIR/../scripts/linux/build.sh ASAN clang cmake diff --git a/third_party/spirv-tools/kokoro/linux-clang-debug/build.sh b/third_party/spirv-tools/kokoro/linux-clang-debug/build.sh index 11b2968a60..785a6e3b62 100644 --- a/third_party/spirv-tools/kokoro/linux-clang-debug/build.sh +++ b/third_party/spirv-tools/kokoro/linux-clang-debug/build.sh @@ -21,4 +21,4 @@ set -e set -x SCRIPT_DIR=`dirname "$BASH_SOURCE"` -source $SCRIPT_DIR/../scripts/linux/build.sh DEBUG clang +source $SCRIPT_DIR/../scripts/linux/build.sh DEBUG clang cmake diff --git a/third_party/spirv-tools/kokoro/linux-clang-release-bazel/build.sh b/third_party/spirv-tools/kokoro/linux-clang-release-bazel/build.sh index 05a9bbb427..238ef52b7e 100644 --- a/third_party/spirv-tools/kokoro/linux-clang-release-bazel/build.sh +++ b/third_party/spirv-tools/kokoro/linux-clang-release-bazel/build.sh @@ -20,24 +20,5 @@ set -e # Display commands being run. set -x -CC=clang -CXX=clang++ -SRC=$PWD/github/SPIRV-Tools - -cd $SRC -git clone --depth=1 https://github.com/KhronosGroup/SPIRV-Headers external/spirv-headers -git clone https://github.com/google/googletest external/googletest -cd external && cd googletest && git reset --hard 1fb1bb23bb8418dc73a5a9a82bbed31dc610fec7 && cd .. && cd .. -git clone --depth=1 https://github.com/google/effcee external/effcee -git clone --depth=1 https://github.com/google/re2 external/re2 - -gsutil cp gs://bazel/0.29.1/release/bazel-0.29.1-linux-x86_64 . -chmod +x bazel-0.29.1-linux-x86_64 - -echo $(date): Build everything... -./bazel-0.29.1-linux-x86_64 build :all -echo $(date): Build completed. - -echo $(date): Starting bazel test... -./bazel-0.29.1-linux-x86_64 test :all -echo $(date): Bazel test completed. +SCRIPT_DIR=`dirname "$BASH_SOURCE"` +source $SCRIPT_DIR/../scripts/linux/build.sh RELEASE clang bazel diff --git a/third_party/spirv-tools/kokoro/linux-clang-release/build.sh b/third_party/spirv-tools/kokoro/linux-clang-release/build.sh index 4764331715..6a9e0136f3 100644 --- a/third_party/spirv-tools/kokoro/linux-clang-release/build.sh +++ b/third_party/spirv-tools/kokoro/linux-clang-release/build.sh @@ -21,4 +21,4 @@ set -e set -x SCRIPT_DIR=`dirname "$BASH_SOURCE"` -source $SCRIPT_DIR/../scripts/linux/build.sh RELEASE clang +source $SCRIPT_DIR/../scripts/linux/build.sh RELEASE clang cmake diff --git a/third_party/spirv-tools/kokoro/linux-gcc-debug/build.sh b/third_party/spirv-tools/kokoro/linux-gcc-debug/build.sh index 3ef1e251b7..c60447e328 100644 --- a/third_party/spirv-tools/kokoro/linux-gcc-debug/build.sh +++ b/third_party/spirv-tools/kokoro/linux-gcc-debug/build.sh @@ -21,4 +21,4 @@ set -e set -x SCRIPT_DIR=`dirname "$BASH_SOURCE"` -source $SCRIPT_DIR/../scripts/linux/build.sh DEBUG gcc +source $SCRIPT_DIR/../scripts/linux/build.sh DEBUG gcc cmake diff --git a/third_party/spirv-tools/kokoro/linux-gcc-release/build.sh b/third_party/spirv-tools/kokoro/linux-gcc-release/build.sh index 3e97d8d3b9..441ab7288c 100644 --- a/third_party/spirv-tools/kokoro/linux-gcc-release/build.sh +++ b/third_party/spirv-tools/kokoro/linux-gcc-release/build.sh @@ -21,4 +21,4 @@ set -e set -x SCRIPT_DIR=`dirname "$BASH_SOURCE"` -source $SCRIPT_DIR/../scripts/linux/build.sh RELEASE gcc +source $SCRIPT_DIR/../scripts/linux/build.sh RELEASE gcc cmake diff --git a/third_party/spirv-tools/kokoro/ndk-build/build.sh b/third_party/spirv-tools/kokoro/ndk-build/build.sh index f1f167d842..89c55659f1 100644 --- a/third_party/spirv-tools/kokoro/ndk-build/build.sh +++ b/third_party/spirv-tools/kokoro/ndk-build/build.sh @@ -20,38 +20,5 @@ set -e # Display commands being run. set -x -BUILD_ROOT=$PWD -SRC=$PWD/github/SPIRV-Tools - -# Get NINJA. -wget -q https://github.com/ninja-build/ninja/releases/download/v1.8.2/ninja-linux.zip -unzip -q ninja-linux.zip -export PATH="$PWD:$PATH" - -# NDK Path -export ANDROID_NDK=/opt/android-ndk-r15c - -# Get the dependencies. -cd $SRC -git clone --depth=1 https://github.com/KhronosGroup/SPIRV-Headers external/spirv-headers -git clone https://github.com/google/googletest external/googletest -cd external && cd googletest && git reset --hard 1fb1bb23bb8418dc73a5a9a82bbed31dc610fec7 && cd .. && cd .. -git clone --depth=1 https://github.com/google/effcee external/effcee -git clone --depth=1 https://github.com/google/re2 external/re2 - -mkdir build && cd $SRC/build -mkdir libs -mkdir app - -# Invoke the build. -BUILD_SHA=${KOKORO_GITHUB_COMMIT:-$KOKORO_GITHUB_PULL_REQUEST_COMMIT} -echo $(date): Starting ndk-build ... -$ANDROID_NDK/ndk-build \ - -C $SRC/android_test \ - NDK_PROJECT_PATH=. \ - NDK_LIBS_OUT=./libs \ - NDK_APP_OUT=./app \ - -j8 - -echo $(date): ndk-build completed. - +SCRIPT_DIR=`dirname "$BASH_SOURCE"` +source $SCRIPT_DIR/../scripts/linux/build.sh ASAN clang android-ndk-build diff --git a/third_party/spirv-tools/kokoro/scripts/linux/build-docker.sh b/third_party/spirv-tools/kokoro/scripts/linux/build-docker.sh new file mode 100755 index 0000000000..ba21698745 --- /dev/null +++ b/third_party/spirv-tools/kokoro/scripts/linux/build-docker.sh @@ -0,0 +1,196 @@ +#!/bin/bash +# Copyright (c) 2018 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Linux Build Script. + +# Fail on any error. +set -e +# Display commands being run. +set -x + +. /bin/using.sh # Declare the bash `using` function for configuring toolchains. + +if [ $COMPILER = "clang" ]; then + using clang-10.0.0 +elif [ $COMPILER = "gcc" ]; then + using gcc-9 +fi + +cd $ROOT_DIR + +function clone_if_missing() { + url=$1 + dir=$2 + if [[ ! -d "$dir" ]]; then + git clone ${@:3} "$url" "$dir" + fi +} + +function clean_dir() { + dir=$1 + if [[ -d "$dir" ]]; then + rm -fr "$dir" + fi + mkdir "$dir" +} + +clone_if_missing https://github.com/KhronosGroup/SPIRV-Headers external/spirv-headers --depth=1 +clone_if_missing https://github.com/google/googletest external/googletest +pushd external/googletest; git reset --hard 1fb1bb23bb8418dc73a5a9a82bbed31dc610fec7; popd +clone_if_missing https://github.com/google/effcee external/effcee --depth=1 +clone_if_missing https://github.com/google/re2 external/re2 --depth=1 +clone_if_missing https://github.com/protocolbuffers/protobuf external/protobuf --branch v3.13.0 + +if [ $TOOL = "cmake" ]; then + using cmake-3.17.2 + using ninja-1.10.0 + + # Possible configurations are: + # ASAN, COVERAGE, RELEASE, DEBUG, DEBUG_EXCEPTION, RELEASE_MINGW + BUILD_TYPE="Debug" + if [ $CONFIG = "RELEASE" ] || [ $CONFIG = "RELEASE_MINGW" ]; then + BUILD_TYPE="RelWithDebInfo" + fi + + SKIP_TESTS="False" + ADDITIONAL_CMAKE_FLAGS="" + if [ $CONFIG = "ASAN" ]; then + ADDITIONAL_CMAKE_FLAGS="-DSPIRV_USE_SANITIZER=address,bounds,null" + [ $COMPILER = "clang" ] || { echo "$CONFIG requires clang"; exit 1; } + elif [ $CONFIG = "COVERAGE" ]; then + ADDITIONAL_CMAKE_FLAGS="-DENABLE_CODE_COVERAGE=ON" + SKIP_TESTS="True" + elif [ $CONFIG = "DEBUG_EXCEPTION" ]; then + ADDITIONAL_CMAKE_FLAGS="-DDISABLE_EXCEPTIONS=ON -DDISABLE_RTTI=ON" + elif [ $CONFIG = "RELEASE_MINGW" ]; then + ADDITIONAL_CMAKE_FLAGS="-Dgtest_disable_pthreads=ON -DCMAKE_TOOLCHAIN_FILE=$SRC/cmake/linux-mingw-toolchain.cmake" + SKIP_TESTS="True" + fi + + clean_dir "$ROOT_DIR/build" + cd "$ROOT_DIR/build" + + # Invoke the build. + BUILD_SHA=${KOKORO_GITHUB_COMMIT:-$KOKORO_GITHUB_PULL_REQUEST_COMMIT} + echo $(date): Starting build... + cmake -DPYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3 -GNinja -DCMAKE_INSTALL_PREFIX=$KOKORO_ARTIFACTS_DIR/install -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DRE2_BUILD_TESTING=OFF -DSPIRV_BUILD_FUZZER=ON $ADDITIONAL_CMAKE_FLAGS .. + + echo $(date): Build everything... + ninja + echo $(date): Build completed. + + if [ $CONFIG = "COVERAGE" ]; then + echo $(date): Check coverage... + ninja report-coverage + echo $(date): Check coverage completed. + fi + + echo $(date): Starting ctest... + if [ $SKIP_TESTS = "False" ]; then + ctest -j4 --output-on-failure --timeout 300 + fi + echo $(date): ctest completed. + + # Package the build. + ninja install + cd $KOKORO_ARTIFACTS_DIR + tar czf install.tgz install +elif [ $TOOL = "cmake-smoketest" ]; then + using cmake-3.17.2 + using ninja-1.10.0 + + # Get shaderc. + SHADERC_DIR=/tmp/shaderc + clean_dir "$SHADERC_DIR" + cd $SHADERC_DIR + git clone https://github.com/google/shaderc.git . + cd $SHADERC_DIR/third_party + + # Get shaderc dependencies. Link the appropriate SPIRV-Tools. + git clone https://github.com/google/googletest.git + git clone https://github.com/KhronosGroup/glslang.git + ln -s $ROOT_DIR spirv-tools + git clone https://github.com/KhronosGroup/SPIRV-Headers.git spirv-headers + git clone https://github.com/google/re2 + git clone https://github.com/google/effcee + + cd $SHADERC_DIR + mkdir build + cd $SHADERC_DIR/build + + # Invoke the build. + echo $(date): Starting build... + cmake -GNinja -DRE2_BUILD_TESTING=OFF -DCMAKE_BUILD_TYPE="Release" .. + + echo $(date): Build glslang... + ninja glslangValidator + + echo $(date): Build everything... + ninja + echo $(date): Build completed. + + echo $(date): Check Shaderc for copyright notices... + ninja check-copyright + + echo $(date): Starting ctest... + ctest --output-on-failure -j4 + echo $(date): ctest completed. +elif [ $TOOL = "cmake-android-ndk" ]; then + using cmake-3.17.2 + using ndk-r21d + using ninja-1.10.0 + + clean_dir "$ROOT_DIR/build" + cd "$ROOT_DIR/build" + + echo $(date): Starting build... + cmake -DCMAKE_BUILD_TYPE=Release \ + -DANDROID_NATIVE_API_LEVEL=android-16 \ + -DANDROID_ABI="armeabi-v7a with NEON" \ + -DSPIRV_SKIP_TESTS=ON \ + -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake" \ + -GNinja \ + -DANDROID_NDK=$ANDROID_NDK \ + .. + + echo $(date): Build everything... + ninja + echo $(date): Build completed. +elif [ $TOOL = "android-ndk-build" ]; then + using ndk-r21d + + clean_dir "$ROOT_DIR/build" + cd "$ROOT_DIR/build" + + echo $(date): Starting ndk-build ... + $ANDROID_NDK_HOME/ndk-build \ + -C $ROOT_DIR/android_test \ + NDK_PROJECT_PATH=. \ + NDK_LIBS_OUT=./libs \ + NDK_APP_OUT=./app \ + -j4 + + echo $(date): ndk-build completed. +elif [ $TOOL = "bazel" ]; then + using bazel-3.1.0 + + echo $(date): Build everything... + bazel build :all + echo $(date): Build completed. + + echo $(date): Starting bazel test... + bazel test :all + echo $(date): Bazel test completed. +fi diff --git a/third_party/spirv-tools/kokoro/scripts/linux/build.sh b/third_party/spirv-tools/kokoro/scripts/linux/build.sh index 347f353ac0..4731ebdc26 100644 --- a/third_party/spirv-tools/kokoro/scripts/linux/build.sh +++ b/third_party/spirv-tools/kokoro/scripts/linux/build.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Copyright (c) 2018 Google LLC. +# Copyright (c) 2021 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,89 +17,38 @@ # Fail on any error. set -e -# Display commands being run. -set -x -BUILD_ROOT=$PWD -SRC=$PWD/github/SPIRV-Tools +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd )" +ROOT_DIR="$( cd "${SCRIPT_DIR}/../../.." >/dev/null 2>&1 && pwd )" + CONFIG=$1 COMPILER=$2 - -SKIP_TESTS="False" -BUILD_TYPE="Debug" - -CMAKE_C_CXX_COMPILER="" -if [ $COMPILER = "clang" ] -then - PATH=/usr/lib/llvm-3.8/bin:$PATH - CMAKE_C_CXX_COMPILER="-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++" -fi - -# Possible configurations are: -# ASAN, COVERAGE, RELEASE, DEBUG, DEBUG_EXCEPTION, RELEASE_MINGW - -if [ $CONFIG = "RELEASE" ] || [ $CONFIG = "RELEASE_MINGW" ] -then - BUILD_TYPE="RelWithDebInfo" -fi - -ADDITIONAL_CMAKE_FLAGS="" -if [ $CONFIG = "ASAN" ] -then - ADDITIONAL_CMAKE_FLAGS="-DSPIRV_USE_SANITIZER=address,bounds,null" - [ $COMPILER = "clang" ] || { echo "$CONFIG requires clang"; exit 1; } -elif [ $CONFIG = "COVERAGE" ] -then - ADDITIONAL_CMAKE_FLAGS="-DENABLE_CODE_COVERAGE=ON" - SKIP_TESTS="True" -elif [ $CONFIG = "DEBUG_EXCEPTION" ] -then - ADDITIONAL_CMAKE_FLAGS="-DDISABLE_EXCEPTIONS=ON -DDISABLE_RTTI=ON" -elif [ $CONFIG = "RELEASE_MINGW" ] -then - ADDITIONAL_CMAKE_FLAGS="-Dgtest_disable_pthreads=ON -DCMAKE_TOOLCHAIN_FILE=$SRC/cmake/linux-mingw-toolchain.cmake" - SKIP_TESTS="True" -fi - -# Get NINJA. -wget -q https://github.com/ninja-build/ninja/releases/download/v1.8.2/ninja-linux.zip -unzip -q ninja-linux.zip -export PATH="$PWD:$PATH" - -cd $SRC -git clone --depth=1 https://github.com/KhronosGroup/SPIRV-Headers external/spirv-headers -git clone https://github.com/google/googletest external/googletest -cd external && cd googletest && git reset --hard 1fb1bb23bb8418dc73a5a9a82bbed31dc610fec7 && cd .. && cd .. -git clone --depth=1 https://github.com/google/effcee external/effcee -git clone --depth=1 https://github.com/google/re2 external/re2 -git clone --depth=1 --branch v3.13.0 https://github.com/protocolbuffers/protobuf external/protobuf - -mkdir build && cd $SRC/build - -# Invoke the build. +TOOL=$3 BUILD_SHA=${KOKORO_GITHUB_COMMIT:-$KOKORO_GITHUB_PULL_REQUEST_COMMIT} -echo $(date): Starting build... -cmake -DPYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3 -GNinja -DCMAKE_INSTALL_PREFIX=$KOKORO_ARTIFACTS_DIR/install -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DRE2_BUILD_TESTING=OFF -DSPIRV_BUILD_FUZZER=ON $ADDITIONAL_CMAKE_FLAGS $CMAKE_C_CXX_COMPILER .. -echo $(date): Build everything... -ninja -echo $(date): Build completed. +docker run --rm -i \ + --volume "${ROOT_DIR}:${ROOT_DIR}" \ + --volume "${KOKORO_ARTIFACTS_DIR}:${KOKORO_ARTIFACTS_DIR}" \ + --workdir "${ROOT_DIR}" \ + --env SCRIPT_DIR=${SCRIPT_DIR} \ + --env ROOT_DIR=${ROOT_DIR} \ + --env CONFIG=${CONFIG} \ + --env COMPILER=${COMPILER} \ + --env TOOL=${TOOL} \ + --env KOKORO_ARTIFACTS_DIR="${KOKORO_ARTIFACTS_DIR}" \ + --env BUILD_SHA="${BUILD_SHA}" \ + --entrypoint "${SCRIPT_DIR}/build-docker.sh" \ + "gcr.io/shaderc-build/radial-build:latest" -if [ $CONFIG = "COVERAGE" ] -then - echo $(date): Check coverage... - ninja report-coverage - echo $(date): Check coverage completed. -fi -echo $(date): Starting ctest... -if [ $SKIP_TESTS = "False" ] -then - ctest -j4 --output-on-failure --timeout 300 -fi -echo $(date): ctest completed. +# chown the given directory to the current user, if it exists. +# Docker creates files with the root user - this can upset the Kokoro artifact copier. +function chown_dir() { + dir=$1 + if [[ -d "$dir" ]]; then + sudo chown -R "$(id -u):$(id -g)" "$dir" + fi +} -# Package the build. -ninja install -cd $KOKORO_ARTIFACTS_DIR -tar czf install.tgz install +chown_dir "${ROOT_DIR}/build" +chown_dir "${ROOT_DIR}/external" diff --git a/third_party/spirv-tools/kokoro/scripts/windows/build.bat b/third_party/spirv-tools/kokoro/scripts/windows/build.bat index fa7a71a044..c964320d7d 100644 --- a/third_party/spirv-tools/kokoro/scripts/windows/build.bat +++ b/third_party/spirv-tools/kokoro/scripts/windows/build.bat @@ -22,7 +22,7 @@ set BUILD_TYPE=%1 set VS_VERSION=%2 :: Force usage of python 3.6 -set PATH=C:\python36;%PATH% +set PATH=C:\python36;"C:\Program Files\CMake\bin";%PATH% cd %SRC% git clone --depth=1 https://github.com/KhronosGroup/SPIRV-Headers external/spirv-headers @@ -41,9 +41,6 @@ if %VS_VERSION% == 2017 ( ) else if %VS_VERSION% == 2015 ( call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64 echo "Using VS 2015..." -) else if %VS_VERSION% == 2013 ( - call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x64 - echo "Using VS 2013..." ) cd %SRC% @@ -62,15 +59,8 @@ if "%KOKORO_GITHUB_COMMIT%." == "." ( set CMAKE_FLAGS=-DCMAKE_INSTALL_PREFIX=%KOKORO_ARTIFACTS_DIR%\install -GNinja -DCMAKE_BUILD_TYPE=%BUILD_TYPE% -DRE2_BUILD_TESTING=OFF -DCMAKE_C_COMPILER=cl.exe -DCMAKE_CXX_COMPILER=cl.exe -:: Skip building tests for VS2013 -if %VS_VERSION% == 2013 ( - set CMAKE_FLAGS=%CMAKE_FLAGS% -DSPIRV_SKIP_TESTS=ON -) - -:: Skip building spirv-fuzz for VS2013; it relies on protobufs which VS2013 cannot handle. -if %VS_VERSION% NEQ 2013 ( - set CMAKE_FLAGS=%CMAKE_FLAGS% -DSPIRV_BUILD_FUZZER=ON -) +:: Build spirv-fuzz +set CMAKE_FLAGS=%CMAKE_FLAGS% -DSPIRV_BUILD_FUZZER=ON cmake %CMAKE_FLAGS% .. @@ -85,13 +75,11 @@ echo "Build Completed %DATE% %TIME%" setlocal ENABLEDELAYEDEXPANSION :: ################################################ -:: Run the tests (We no longer run tests on VS2013) +:: Run the tests :: ################################################ echo "Running Tests... %DATE% %TIME%" -if %VS_VERSION% NEQ 2013 ( - ctest -C %BUILD_TYPE% --output-on-failure --timeout 300 - if !ERRORLEVEL! NEQ 0 exit /b !ERRORLEVEL! -) +ctest -C %BUILD_TYPE% --output-on-failure --timeout 300 +if !ERRORLEVEL! NEQ 0 exit /b !ERRORLEVEL! echo "Tests Completed %DATE% %TIME%" :: ################################################ @@ -105,5 +93,4 @@ zip -r install.zip install rm -rf %SRC%\build rm -rf %SRC%\external -exit /b 0 - +exit /b 0 \ No newline at end of file diff --git a/third_party/spirv-tools/kokoro/shaderc-smoketest/build.sh b/third_party/spirv-tools/kokoro/shaderc-smoketest/build.sh index 0856c9b25f..60c816d4d6 100644 --- a/third_party/spirv-tools/kokoro/shaderc-smoketest/build.sh +++ b/third_party/spirv-tools/kokoro/shaderc-smoketest/build.sh @@ -18,54 +18,5 @@ set -e # Display commands being run. set -x -BUILD_ROOT=$PWD -GITHUB_DIR=$BUILD_ROOT/github - -SKIP_TESTS="False" -BUILD_TYPE="Release" - -# Get NINJA. -wget -q https://github.com/ninja-build/ninja/releases/download/v1.8.2/ninja-linux.zip -unzip -q ninja-linux.zip -export PATH="$PWD:$PATH" - -# Get shaderc. -cd $GITHUB_DIR -git clone https://github.com/google/shaderc.git -SHADERC_DIR=$GITHUB_DIR/shaderc -cd $SHADERC_DIR/third_party - -# Get shaderc dependencies. Link the appropriate SPIRV-Tools. -git clone https://github.com/google/googletest.git -git clone https://github.com/KhronosGroup/glslang.git -ln -s $GITHUB_DIR/SPIRV-Tools spirv-tools -git clone https://github.com/KhronosGroup/SPIRV-Headers.git spirv-headers -git clone https://github.com/google/re2 -git clone https://github.com/google/effcee - -cd $SHADERC_DIR -mkdir build -cd $SHADERC_DIR/build - -# Invoke the build. -BUILD_SHA=${KOKORO_GITHUB_COMMIT:-$KOKORO_GITHUB_PULL_REQUEST_COMMIT} -echo $(date): Starting build... -cmake -GNinja -DRE2_BUILD_TESTING=OFF -DCMAKE_BUILD_TYPE=$BUILD_TYPE .. - -echo $(date): Build glslang... -ninja glslangValidator - -echo $(date): Build everything... -ninja -echo $(date): Build completed. - -echo $(date): Check Shaderc for copyright notices... -ninja check-copyright - -echo $(date): Starting ctest... -if [ $SKIP_TESTS = "False" ] -then - ctest --output-on-failure -j4 -fi -echo $(date): ctest completed. - +SCRIPT_DIR=`dirname "$BASH_SOURCE"` +source $SCRIPT_DIR/../scripts/linux/build.sh RELEASE gcc cmake-smoketest diff --git a/third_party/spirv-tools/kokoro/windows-msvc-2013-release/continuous.cfg b/third_party/spirv-tools/kokoro/windows-msvc-2013-release/continuous.cfg deleted file mode 100644 index 5dfcba63bc..0000000000 --- a/third_party/spirv-tools/kokoro/windows-msvc-2013-release/continuous.cfg +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (c) 2018 Google LLC. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Continuous build configuration. -build_file: "SPIRV-Tools/kokoro/windows-msvc-2013-release/build.bat" diff --git a/third_party/spirv-tools/source/CMakeLists.txt b/third_party/spirv-tools/source/CMakeLists.txt index 38101ab269..5f59045671 100644 --- a/third_party/spirv-tools/source/CMakeLists.txt +++ b/third_party/spirv-tools/source/CMakeLists.txt @@ -359,7 +359,7 @@ function(spirv_tools_default_target_options target) ) set_property(TARGET ${target} PROPERTY FOLDER "SPIRV-Tools libraries") spvtools_check_symbol_exports(${target}) - add_dependencies(${target} core_tables enum_string_mapping extinst_tables) + add_dependencies(${target} spirv-tools-build-version core_tables enum_string_mapping extinst_tables) endfunction() # Always build ${SPIRV_TOOLS}-shared. This is expected distro packages, and @@ -410,6 +410,12 @@ if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") endif() endif() +if (ANDROID) + foreach(target ${SPIRV_TOOLS_TARGETS}) + target_link_libraries(${target} PRIVATE android log) + endforeach() +endif() + if(ENABLE_SPIRV_TOOLS_INSTALL) install(TARGETS ${SPIRV_TOOLS_TARGETS} EXPORT ${SPIRV_TOOLS}Targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} diff --git a/third_party/spirv-tools/source/binary.cpp b/third_party/spirv-tools/source/binary.cpp index 75a997d305..090cccfecd 100644 --- a/third_party/spirv-tools/source/binary.cpp +++ b/third_party/spirv-tools/source/binary.cpp @@ -655,12 +655,20 @@ spv_result_t Parser::parseOperand(size_t inst_offset, case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE: case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER: case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION: - case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: { + case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: + case SPV_OPERAND_TYPE_FPDENORM_MODE: + case SPV_OPERAND_TYPE_FPOPERATION_MODE: + case SPV_OPERAND_TYPE_QUANTIZATION_MODES: + case SPV_OPERAND_TYPE_OVERFLOW_MODES: + case SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT: + case SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT: { // A single word that is a plain enum value. // Map an optional operand type to its corresponding concrete type. if (type == SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER) parsed_operand.type = SPV_OPERAND_TYPE_ACCESS_QUALIFIER; + if (type == SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT) + parsed_operand.type = SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT; spv_operand_desc entry; if (grammar_.lookupOperand(type, word, &entry)) { diff --git a/third_party/spirv-tools/source/diagnostic.cpp b/third_party/spirv-tools/source/diagnostic.cpp index edc27c8fd9..f3aa259431 100644 --- a/third_party/spirv-tools/source/diagnostic.cpp +++ b/third_party/spirv-tools/source/diagnostic.cpp @@ -37,7 +37,7 @@ spv_diagnostic spvDiagnosticCreate(const spv_position position, diagnostic->position = *position; diagnostic->isTextSource = false; memset(diagnostic->error, 0, length); - strncpy(diagnostic->error, message, length); + strcpy(diagnostic->error, message); return diagnostic; } diff --git a/third_party/spirv-tools/source/disassemble.cpp b/third_party/spirv-tools/source/disassemble.cpp index e76325126d..c553988f38 100644 --- a/third_party/spirv-tools/source/disassemble.cpp +++ b/third_party/spirv-tools/source/disassemble.cpp @@ -326,7 +326,11 @@ void Disassembler::EmitOperand(const spv_parsed_instruction_t& inst, case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE: case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER: case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION: - case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: { + case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: + case SPV_OPERAND_TYPE_FPDENORM_MODE: + case SPV_OPERAND_TYPE_FPOPERATION_MODE: + case SPV_OPERAND_TYPE_QUANTIZATION_MODES: + case SPV_OPERAND_TYPE_OVERFLOW_MODES: { spv_operand_desc entry; if (grammar_.lookupOperand(operand.type, word, &entry)) assert(false && "should have caught this earlier"); @@ -343,7 +347,17 @@ void Disassembler::EmitOperand(const spv_parsed_instruction_t& inst, EmitMaskOperand(operand.type, word); break; default: - assert(false && "unhandled or invalid case"); + if (spvOperandIsConcreteMask(operand.type)) { + EmitMaskOperand(operand.type, word); + } else if (spvOperandIsConcrete(operand.type)) { + spv_operand_desc entry; + if (grammar_.lookupOperand(operand.type, word, &entry)) + assert(false && "should have caught this earlier"); + stream_ << entry->name; + } else { + assert(false && "unhandled or invalid case"); + } + break; } ResetColor(); } diff --git a/third_party/spirv-tools/source/ext_inst.cpp b/third_party/spirv-tools/source/ext_inst.cpp index 3471ebe0d2..795cb0f3f7 100644 --- a/third_party/spirv-tools/source/ext_inst.cpp +++ b/third_party/spirv-tools/source/ext_inst.cpp @@ -89,7 +89,6 @@ spv_result_t spvExtInstTableGet(spv_ext_inst_table* pExtInstTable, case SPV_ENV_UNIVERSAL_1_3: case SPV_ENV_VULKAN_1_1: case SPV_ENV_VULKAN_1_1_SPIRV_1_4: - case SPV_ENV_WEBGPU_0: case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_UNIVERSAL_1_5: case SPV_ENV_VULKAN_1_2: diff --git a/third_party/spirv-tools/source/fuzz/CMakeLists.txt b/third_party/spirv-tools/source/fuzz/CMakeLists.txt index d3aa9f1e03..a80616623a 100644 --- a/third_party/spirv-tools/source/fuzz/CMakeLists.txt +++ b/third_party/spirv-tools/source/fuzz/CMakeLists.txt @@ -37,6 +37,7 @@ if(SPIRV_BUILD_FUZZER) set(SPIRV_TOOLS_FUZZ_SOURCES added_function_reducer.h + available_instructions.h call_graph.h comparator_deep_blocks_first.h counter_overflow_id_source.h @@ -100,6 +101,7 @@ if(SPIRV_BUILD_FUZZER) fuzzer_pass_outline_functions.h fuzzer_pass_permute_blocks.h fuzzer_pass_permute_function_parameters.h + fuzzer_pass_permute_function_variables.h fuzzer_pass_permute_instructions.h fuzzer_pass_permute_phi_operands.h fuzzer_pass_propagate_instructions_down.h @@ -119,6 +121,7 @@ if(SPIRV_BUILD_FUZZER) fuzzer_pass_split_blocks.h fuzzer_pass_swap_commutable_operands.h fuzzer_pass_swap_conditional_branch_operands.h + fuzzer_pass_swap_functions.h fuzzer_pass_toggle_access_chain_instruction.h fuzzer_pass_wrap_regions_in_selections.h fuzzer_util.h @@ -221,6 +224,8 @@ if(SPIRV_BUILD_FUZZER) transformation_store.h transformation_swap_commutable_operands.h transformation_swap_conditional_branch_operands.h + transformation_swap_function_variables.h + transformation_swap_two_functions.h transformation_toggle_access_chain_instruction.h transformation_vector_shuffle.h transformation_wrap_early_terminator_in_function.h @@ -229,6 +234,7 @@ if(SPIRV_BUILD_FUZZER) ${CMAKE_CURRENT_BINARY_DIR}/protobufs/spvtoolsfuzz.pb.h added_function_reducer.cpp + available_instructions.cpp call_graph.cpp counter_overflow_id_source.cpp data_descriptor.cpp @@ -290,6 +296,7 @@ if(SPIRV_BUILD_FUZZER) fuzzer_pass_outline_functions.cpp fuzzer_pass_permute_blocks.cpp fuzzer_pass_permute_function_parameters.cpp + fuzzer_pass_permute_function_variables.cpp fuzzer_pass_permute_instructions.cpp fuzzer_pass_permute_phi_operands.cpp fuzzer_pass_propagate_instructions_down.cpp @@ -309,6 +316,7 @@ if(SPIRV_BUILD_FUZZER) fuzzer_pass_split_blocks.cpp fuzzer_pass_swap_commutable_operands.cpp fuzzer_pass_swap_conditional_branch_operands.cpp + fuzzer_pass_swap_functions.cpp fuzzer_pass_toggle_access_chain_instruction.cpp fuzzer_pass_wrap_regions_in_selections.cpp fuzzer_util.cpp @@ -409,6 +417,8 @@ if(SPIRV_BUILD_FUZZER) transformation_store.cpp transformation_swap_commutable_operands.cpp transformation_swap_conditional_branch_operands.cpp + transformation_swap_function_variables.cpp + transformation_swap_two_functions.cpp transformation_toggle_access_chain_instruction.cpp transformation_vector_shuffle.cpp transformation_wrap_early_terminator_in_function.cpp diff --git a/third_party/spirv-tools/source/fuzz/available_instructions.cpp b/third_party/spirv-tools/source/fuzz/available_instructions.cpp new file mode 100644 index 0000000000..0db8b207d8 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/available_instructions.cpp @@ -0,0 +1,191 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/available_instructions.h" +#include "source/fuzz/fuzzer_util.h" + +namespace spvtools { +namespace fuzz { + +AvailableInstructions::AvailableInstructions( + opt::IRContext* ir_context, + const std::function& predicate) + : ir_context_(ir_context) { + // Consider all global declarations + for (auto& global : ir_context->module()->types_values()) { + if (predicate(ir_context, &global)) { + available_globals_.push_back(&global); + } + } + + // Consider every function + for (auto& function : *ir_context->module()) { + // Identify those function parameters that satisfy the predicate. + std::vector available_params_for_function; + function.ForEachParam( + [&predicate, ir_context, + &available_params_for_function](opt::Instruction* param) { + if (predicate(ir_context, param)) { + available_params_for_function.push_back(param); + } + }); + + // Consider every reachable block in the function. + auto dominator_analysis = ir_context->GetDominatorAnalysis(&function); + for (auto& block : function) { + if (!ir_context->IsReachable(block)) { + // The block is not reachable. + continue; + } + if (&block == &*function.begin()) { + // The function entry block is special: only the relevant globals and + // function parameters are available at its entry point. + num_available_at_block_entry_.insert( + {&block, + static_cast(available_params_for_function.size() + + available_globals_.size())}); + } else { + // |block| is not the entry block and is reachable, so it must have an + // immediate dominator. The number of instructions available on entry to + // |block| is thus the number of instructions available on entry to the + // immediate dominator + the number of instructions generated_by_block + // by the immediate dominator. + auto immediate_dominator = + dominator_analysis->ImmediateDominator(&block); + assert(immediate_dominator != nullptr && + "The block is reachable so should have an immediate dominator."); + assert(generated_by_block_.count(immediate_dominator) != 0 && + "Immediate dominator should have already been processed."); + assert(num_available_at_block_entry_.count(immediate_dominator) != 0 && + "Immediate dominator should have already been processed."); + num_available_at_block_entry_.insert( + {&block, + static_cast( + generated_by_block_.at(immediate_dominator).size()) + + num_available_at_block_entry_.at(immediate_dominator)}); + } + // Now consider each instruction in the block. + std::vector generated_by_block; + for (auto& inst : block) { + assert(num_available_at_block_entry_.count(&block) != 0 && + "Block should have already been processed."); + // The number of available instructions before |inst| is the number + // available at the start of the block + the number of relevant + // instructions generated by the block so far. + num_available_before_instruction_.insert( + {&inst, num_available_at_block_entry_.at(&block) + + static_cast(generated_by_block.size())}); + if (predicate(ir_context, &inst)) { + // This instruction satisfies the predicate, so note that it is + // generated by |block|. + generated_by_block.push_back(&inst); + } + } + generated_by_block_.emplace(&block, std::move(generated_by_block)); + } + available_params_.emplace(&function, + std::move(available_params_for_function)); + } +} + +AvailableInstructions::AvailableBeforeInstruction +AvailableInstructions::GetAvailableBeforeInstruction( + opt::Instruction* inst) const { + assert(num_available_before_instruction_.count(inst) != 0 && + "Availability can only be queried for reachable instructions."); + return {*this, inst}; +} + +AvailableInstructions::AvailableBeforeInstruction::AvailableBeforeInstruction( + const AvailableInstructions& available_instructions, opt::Instruction* inst) + : available_instructions_(available_instructions), inst_(inst) {} + +uint32_t AvailableInstructions::AvailableBeforeInstruction::size() const { + return available_instructions_.num_available_before_instruction_.at(inst_); +} + +bool AvailableInstructions::AvailableBeforeInstruction::empty() const { + return size() == 0; +} + +opt::Instruction* AvailableInstructions::AvailableBeforeInstruction::operator[]( + uint32_t index) const { + assert(index < size() && "Index out of bounds."); + + // First, check the cache to see whether we can return the available + // instruction in constant time. + auto cached_result = index_cache.find(index); + if (cached_result != index_cache.end()) { + return cached_result->second; + } + + // Next check whether the index falls into the global region. + if (index < available_instructions_.available_globals_.size()) { + auto result = available_instructions_.available_globals_[index]; + index_cache.insert({index, result}); + return result; + } + + auto block = available_instructions_.ir_context_->get_instr_block(inst_); + auto function = block->GetParent(); + + // Next check whether the index falls into the available instructions that + // correspond to function parameters. + if (index < + available_instructions_.available_globals_.size() + + available_instructions_.available_params_.at(function).size()) { + auto result = available_instructions_.available_params_.at( + function)[index - available_instructions_.available_globals_.size()]; + index_cache.insert({index, result}); + return result; + } + + auto dominator_analysis = + available_instructions_.ir_context_->GetDominatorAnalysis(function); + + // Now the expensive part (which is why we have the cache): walk the dominator + // tree backwards starting from the block containing |inst_| until we get to + // the block in which the instruction corresponding to |index| exists. + for (auto* ancestor = block; true; + ancestor = dominator_analysis->ImmediateDominator(ancestor)) { + uint32_t num_available_at_ancestor_entry = + available_instructions_.num_available_at_block_entry_.at(ancestor); + if (index_cache.count(num_available_at_ancestor_entry) == 0) { + // This is the first time we have traversed this block, so we populate the + // cache with the index of each instruction, so that if a future index + // query relates to indices associated with this block we can return the + // result in constant time. + auto& generated_by_ancestor = + available_instructions_.generated_by_block_.at(ancestor); + for (uint32_t local_index = 0; local_index < generated_by_ancestor.size(); + local_index++) { + index_cache.insert({num_available_at_ancestor_entry + local_index, + generated_by_ancestor[local_index]}); + } + } + if (index >= num_available_at_ancestor_entry) { + // This block contains the instruction we want, so by now it will be in + // the cache. + return index_cache.at(index); + } + assert(ancestor != &*function->begin() && + "By construction we should find a block associated with the index."); + } + + assert(false && "Unreachable."); + return nullptr; +} + +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/available_instructions.h b/third_party/spirv-tools/source/fuzz/available_instructions.h new file mode 100644 index 0000000000..5c0b417592 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/available_instructions.h @@ -0,0 +1,111 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_FUZZ_AVAILABLE_INSTRUCTIONS_H_ +#define SOURCE_FUZZ_AVAILABLE_INSTRUCTIONS_H_ + +#include +#include + +#include "source/opt/instruction.h" +#include "source/opt/ir_context.h" + +namespace spvtools { +namespace fuzz { + +// A class for allowing efficient querying of the instruction that satisfy a +// particular predicate that are available before a given instruction. +// Availability information is only computed for instructions in *reachable* +// basic blocks. +class AvailableInstructions { + public: + // The outer class captures availability information for a whole module, and + // each instance of this inner class captures availability for a particular + // instruction. + class AvailableBeforeInstruction { + public: + AvailableBeforeInstruction( + const AvailableInstructions& available_instructions, + opt::Instruction* inst); + + // Returns the number of instructions that are available before the + // instruction associated with this class. + uint32_t size() const; + + // Returns true if and only if |size()| is 0. + bool empty() const; + + // Requires |index| < |size()|. Returns the ith available instruction. + opt::Instruction* operator[](uint32_t index) const; + + private: + // A references to an instance of the outer class. + const AvailableInstructions& available_instructions_; + + // The instruction for which availability information is captured. + opt::Instruction* inst_; + + // A cache to improve the efficiency of the [] operator. The [] operator + // requires walking the instruction's dominator tree to find an instruction + // at a particular index, which is a linear time operation. By inserting all + // instructions that are traversed during this search into a cache, future + // lookups will take constant time unless they require traversing the + // dominator tree more deeply. + mutable std::unordered_map index_cache; + }; + + // Constructs availability instructions for |ir_context|, where instructions + // are only available if they satisfy |predicate|. + AvailableInstructions( + opt::IRContext* ir_context, + const std::function& predicate); + + // Yields instruction availability for |inst|. + AvailableBeforeInstruction GetAvailableBeforeInstruction( + opt::Instruction* inst) const; + + private: + // The module in which all instructions are contained. + opt::IRContext* ir_context_; + + // The global instructions that satisfy the predicate. + std::vector available_globals_; + + // Per function, the parameters that satisfy the predicate. + std::unordered_map> + available_params_; + + // The number of instructions that satisfy the predicate and that are + // available at the entry to a block. For the entry block of a function this + // is the number of available globals + the number of available function + // parameters. For any other block it is the number of available instructions + // for the blocks immediate dominator + the number of instructions generated + // by the immediate dominator. + std::unordered_map num_available_at_block_entry_; + + // For each block this records those instructions in the block that satisfy + // the predicate. + std::unordered_map> + generated_by_block_; + + // For each instruction this records how many instructions satisfying the + // predicate are available before the instruction. + std::unordered_map + num_available_before_instruction_; +}; + +} // namespace fuzz +} // namespace spvtools + +#endif // SOURCE_FUZZ_AVAILABLE_INSTRUCTIONS_H_ diff --git a/third_party/spirv-tools/source/fuzz/force_render_red.cpp b/third_party/spirv-tools/source/fuzz/force_render_red.cpp index ed60bd0326..3267487ad6 100644 --- a/third_party/spirv-tools/source/fuzz/force_render_red.cpp +++ b/third_party/spirv-tools/source/fuzz/force_render_red.cpp @@ -19,12 +19,10 @@ #include "source/fuzz/protobufs/spirvfuzz_protobufs.h" #include "source/fuzz/transformation_context.h" #include "source/fuzz/transformation_replace_constant_with_uniform.h" -#include "source/fuzz/uniform_buffer_element_descriptor.h" #include "source/opt/build_module.h" #include "source/opt/ir_context.h" #include "source/opt/types.h" #include "source/util/make_unique.h" -#include "tools/util/cli_consumer.h" namespace spvtools { namespace fuzz { @@ -160,8 +158,8 @@ bool ForceRenderRed( const spv_target_env& target_env, spv_validator_options validator_options, const std::vector& binary_in, const spvtools::fuzz::protobufs::FactSequence& initial_facts, + const MessageConsumer& message_consumer, std::vector* binary_out) { - auto message_consumer = spvtools::utils::CLIMessageConsumer; spvtools::SpirvTools tools(target_env); if (!tools.IsValid()) { message_consumer(SPV_MSG_ERROR, nullptr, {}, @@ -212,7 +210,6 @@ bool ForceRenderRed( auto new_exit_block = MakeUnique(std::move(label)); new_exit_block->AddInstruction(MakeUnique( ir_context.get(), SpvOpReturn, 0, 0, opt::Instruction::OperandList())); - new_exit_block->SetParent(entry_point_function); entry_point_function->AddBasicBlock(std::move(new_exit_block)); } diff --git a/third_party/spirv-tools/source/fuzz/force_render_red.h b/third_party/spirv-tools/source/fuzz/force_render_red.h index b51c72b464..5b8eab1b63 100644 --- a/third_party/spirv-tools/source/fuzz/force_render_red.h +++ b/third_party/spirv-tools/source/fuzz/force_render_red.h @@ -41,7 +41,7 @@ bool ForceRenderRed( const spv_target_env& target_env, spv_validator_options validator_options, const std::vector& binary_in, const spvtools::fuzz::protobufs::FactSequence& initial_facts, - std::vector* binary_out); + const MessageConsumer& message_consumer, std::vector* binary_out); } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/fuzzer.cpp b/third_party/spirv-tools/source/fuzz/fuzzer.cpp index 40da497434..fe88a55b02 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer.cpp @@ -17,9 +17,7 @@ #include #include #include -#include -#include "source/fuzz/fact_manager/fact_manager.h" #include "source/fuzz/fuzzer_context.h" #include "source/fuzz/fuzzer_pass_add_access_chains.h" #include "source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.h" @@ -69,6 +67,7 @@ #include "source/fuzz/fuzzer_pass_outline_functions.h" #include "source/fuzz/fuzzer_pass_permute_blocks.h" #include "source/fuzz/fuzzer_pass_permute_function_parameters.h" +#include "source/fuzz/fuzzer_pass_permute_function_variables.h" #include "source/fuzz/fuzzer_pass_permute_instructions.h" #include "source/fuzz/fuzzer_pass_permute_phi_operands.h" #include "source/fuzz/fuzzer_pass_propagate_instructions_down.h" @@ -88,12 +87,10 @@ #include "source/fuzz/fuzzer_pass_split_blocks.h" #include "source/fuzz/fuzzer_pass_swap_commutable_operands.h" #include "source/fuzz/fuzzer_pass_swap_conditional_branch_operands.h" +#include "source/fuzz/fuzzer_pass_swap_functions.h" #include "source/fuzz/fuzzer_pass_toggle_access_chain_instruction.h" #include "source/fuzz/fuzzer_pass_wrap_regions_in_selections.h" #include "source/fuzz/pass_management/repeated_pass_manager.h" -#include "source/fuzz/pass_management/repeated_pass_manager_looped_with_recommendations.h" -#include "source/fuzz/pass_management/repeated_pass_manager_random_with_recommendations.h" -#include "source/fuzz/pass_management/repeated_pass_manager_simple.h" #include "source/fuzz/pass_management/repeated_pass_recommender_standard.h" #include "source/fuzz/protobufs/spirvfuzz_protobufs.h" #include "source/fuzz/transformation_context.h" @@ -104,35 +101,149 @@ namespace spvtools { namespace fuzz { -namespace { -const uint32_t kIdBoundGap = 100; - -} // namespace - -Fuzzer::Fuzzer(spv_target_env target_env, MessageConsumer consumer, - const std::vector& binary_in, - const protobufs::FactSequence& initial_facts, +Fuzzer::Fuzzer(std::unique_ptr ir_context, + std::unique_ptr transformation_context, + std::unique_ptr fuzzer_context, + MessageConsumer consumer, const std::vector& donor_suppliers, - std::unique_ptr random_generator, bool enable_all_passes, RepeatedPassStrategy repeated_pass_strategy, bool validate_after_each_fuzzer_pass, spv_validator_options validator_options) - : target_env_(target_env), - consumer_(std::move(consumer)), - binary_in_(binary_in), - initial_facts_(initial_facts), - donor_suppliers_(donor_suppliers), - random_generator_(std::move(random_generator)), + : consumer_(std::move(consumer)), enable_all_passes_(enable_all_passes), - repeated_pass_strategy_(repeated_pass_strategy), validate_after_each_fuzzer_pass_(validate_after_each_fuzzer_pass), validator_options_(validator_options), num_repeated_passes_applied_(0), - ir_context_(nullptr), - fuzzer_context_(nullptr), - transformation_context_(nullptr), - transformation_sequence_out_() {} + is_valid_(true), + ir_context_(std::move(ir_context)), + transformation_context_(std::move(transformation_context)), + fuzzer_context_(std::move(fuzzer_context)), + transformation_sequence_out_(), + pass_instances_(), + repeated_pass_recommender_(nullptr), + repeated_pass_manager_(nullptr), + final_passes_() { + assert(ir_context_ && "IRContext is not initialized"); + assert(fuzzer_context_ && "FuzzerContext is not initialized"); + assert(transformation_context_ && "TransformationContext is not initialized"); + assert(fuzzerutil::IsValidAndWellFormed(ir_context_.get(), validator_options_, + consumer_) && + "IRContext is invalid"); + + // The following passes are likely to be very useful: many other passes + // introduce synonyms, irrelevant ids and constants that these passes can work + // with. We thus enable them with high probability. + MaybeAddRepeatedPass(90, &pass_instances_); + MaybeAddRepeatedPass(90, &pass_instances_); + MaybeAddRepeatedPass(90, &pass_instances_); + + do { + // Each call to MaybeAddRepeatedPass randomly decides whether the given pass + // should be enabled, and adds an instance of the pass to |pass_instances| + // if it is enabled. + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_, + donor_suppliers); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + MaybeAddRepeatedPass( + &pass_instances_); + MaybeAddRepeatedPass(&pass_instances_); + // There is a theoretical possibility that no pass instances were created + // until now; loop again if so. + } while (pass_instances_.GetPasses().empty()); + + repeated_pass_recommender_ = MakeUnique( + &pass_instances_, fuzzer_context_.get()); + repeated_pass_manager_ = RepeatedPassManager::Create( + repeated_pass_strategy, fuzzer_context_.get(), &pass_instances_, + repeated_pass_recommender_.get()); + + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + if (!fuzzer_context_->IsWgslCompatible()) { + // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/4214): + // this is disabled temporarily due to some issues in the Tint compiler. + // Enable it back when the issues are resolved. + MaybeAddFinalPass( + &final_passes_); + } + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); + MaybeAddFinalPass(&final_passes_); +} Fuzzer::~Fuzzer() = default; @@ -165,240 +276,107 @@ bool Fuzzer::ApplyPassAndCheckValidity(FuzzerPass* pass) const { consumer_); } -Fuzzer::FuzzerResult Fuzzer::Run() { - // Check compatibility between the library version being linked with and the - // header files being used. - GOOGLE_PROTOBUF_VERIFY_VERSION; +opt::IRContext* Fuzzer::GetIRContext() { return ir_context_.get(); } - assert(ir_context_ == nullptr && fuzzer_context_ == nullptr && - transformation_context_ == nullptr && - transformation_sequence_out_.transformation_size() == 0 && - "'Run' must not be invoked more than once."); - - spvtools::SpirvTools tools(target_env_); - tools.SetMessageConsumer(consumer_); - if (!tools.IsValid()) { - consumer_(SPV_MSG_ERROR, nullptr, {}, - "Failed to create SPIRV-Tools interface; stopping."); - return {Fuzzer::FuzzerResultStatus::kFailedToCreateSpirvToolsInterface, - std::vector(), protobufs::TransformationSequence()}; - } - - // Initial binary should be valid. - if (!tools.Validate(&binary_in_[0], binary_in_.size(), validator_options_)) { - consumer_(SPV_MSG_ERROR, nullptr, {}, - "Initial binary is invalid; stopping."); - return {Fuzzer::FuzzerResultStatus::kInitialBinaryInvalid, - std::vector(), protobufs::TransformationSequence()}; - } - - // Build the module from the input binary. - ir_context_ = - BuildModule(target_env_, consumer_, binary_in_.data(), binary_in_.size()); - assert(ir_context_); - - // The fuzzer will introduce new ids into the module. The module's id bound - // gives the smallest id that can be used for this purpose. We add an offset - // to this so that there is a sizeable gap between the ids used in the - // original module and the ids used for fuzzing, as a readability aid. - // - // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541) consider the - // case where the maximum id bound is reached. - auto minimum_fresh_id = ir_context_->module()->id_bound() + kIdBoundGap; - fuzzer_context_ = - MakeUnique(random_generator_.get(), minimum_fresh_id); - - transformation_context_ = MakeUnique( - MakeUnique(ir_context_.get()), validator_options_); - transformation_context_->GetFactManager()->AddInitialFacts(consumer_, - initial_facts_); - - RepeatedPassInstances pass_instances{}; - - // The following passes are likely to be very useful: many other passes - // introduce synonyms, irrelevant ids and constants that these passes can work - // with. We thus enable them with high probability. - MaybeAddRepeatedPass(90, &pass_instances); - MaybeAddRepeatedPass(90, &pass_instances); - MaybeAddRepeatedPass(90, &pass_instances); - - do { - // Each call to MaybeAddRepeatedPass randomly decides whether the given pass - // should be enabled, and adds an instance of the pass to |pass_instances| - // if it is enabled. - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances, - donor_suppliers_); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass(&pass_instances); - MaybeAddRepeatedPass( - &pass_instances); - MaybeAddRepeatedPass(&pass_instances); - // There is a theoretical possibility that no pass instances were created - // until now; loop again if so. - } while (pass_instances.GetPasses().empty()); - - RepeatedPassRecommenderStandard pass_recommender(&pass_instances, - fuzzer_context_.get()); - - std::unique_ptr repeated_pass_manager = nullptr; - switch (repeated_pass_strategy_) { - case RepeatedPassStrategy::kSimple: - repeated_pass_manager = MakeUnique( - fuzzer_context_.get(), &pass_instances); - break; - case RepeatedPassStrategy::kLoopedWithRecommendations: - repeated_pass_manager = - MakeUnique( - fuzzer_context_.get(), &pass_instances, &pass_recommender); - break; - case RepeatedPassStrategy::kRandomWithRecommendations: - repeated_pass_manager = - MakeUnique( - fuzzer_context_.get(), &pass_instances, &pass_recommender); - break; - } - - do { - if (!ApplyPassAndCheckValidity( - repeated_pass_manager->ChoosePass(transformation_sequence_out_))) { - return {Fuzzer::FuzzerResultStatus::kFuzzerPassLedToInvalidModule, - std::vector(), protobufs::TransformationSequence()}; - } - } while (ShouldContinueFuzzing()); - - // Now apply some passes that it does not make sense to apply repeatedly, - // as they do not unlock other passes. - std::vector> final_passes; - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass( - &final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - MaybeAddFinalPass(&final_passes); - for (auto& pass : final_passes) { - if (!ApplyPassAndCheckValidity(pass.get())) { - return {Fuzzer::FuzzerResultStatus::kFuzzerPassLedToInvalidModule, - std::vector(), protobufs::TransformationSequence()}; - } - } - // Encode the module as a binary. - std::vector binary_out; - ir_context_->module()->ToBinary(&binary_out, false); - - return {Fuzzer::FuzzerResultStatus::kComplete, std::move(binary_out), - std::move(transformation_sequence_out_)}; +const protobufs::TransformationSequence& Fuzzer::GetTransformationSequence() + const { + return transformation_sequence_out_; } -bool Fuzzer::ShouldContinueFuzzing() { - // There's a risk that fuzzing could get stuck, if none of the enabled fuzzer - // passes are able to apply any transformations. To guard against this we - // count the number of times some repeated pass has been applied and ensure - // that fuzzing stops if the number of repeated passes hits the limit on the - // number of transformations that can be applied. - assert( - num_repeated_passes_applied_ <= - fuzzer_context_->GetTransformationLimit() && - "The number of repeated passes applied must not exceed its upper limit."); - if (ir_context_->module()->id_bound() >= fuzzer_context_->GetIdBoundLimit()) { - return false; - } - if (num_repeated_passes_applied_ == - fuzzer_context_->GetTransformationLimit()) { - // Stop because fuzzing has got stuck. - return false; - } - auto transformations_applied_so_far = +Fuzzer::Result Fuzzer::Run(uint32_t num_of_transformations_to_apply) { + assert(is_valid_ && "The module was invalidated during the previous fuzzing"); + + const auto initial_num_of_transformations = static_cast(transformation_sequence_out_.transformation_size()); - if (transformations_applied_so_far >= - fuzzer_context_->GetTransformationLimit()) { - // Stop because we have reached the transformation limit. - return false; + + auto status = Status::kComplete; + do { + if (!ApplyPassAndCheckValidity( + repeated_pass_manager_->ChoosePass(transformation_sequence_out_))) { + status = Status::kFuzzerPassLedToInvalidModule; + break; + } + + // Check that the module is small enough. + if (ir_context_->module()->id_bound() >= + fuzzer_context_->GetIdBoundLimit()) { + status = Status::kModuleTooBig; + break; + } + + auto transformations_applied_so_far = static_cast( + transformation_sequence_out_.transformation_size()); + assert(transformations_applied_so_far >= initial_num_of_transformations && + "Number of transformations cannot decrease"); + + // Check if we've already applied the maximum number of transformations. + if (transformations_applied_so_far >= + fuzzer_context_->GetTransformationLimit()) { + status = Status::kTransformationLimitReached; + break; + } + + // Check that we've not got stuck (this can happen if the only available + // fuzzer passes are not able to apply any transformations, or can only + // apply very few transformations). + if (num_repeated_passes_applied_ >= + fuzzer_context_->GetTransformationLimit()) { + status = Status::kFuzzerStuck; + break; + } + + // Check whether we've exceeded the number of transformations we can apply + // in a single call to this method. + if (num_of_transformations_to_apply != 0 && + transformations_applied_so_far - initial_num_of_transformations >= + num_of_transformations_to_apply) { + status = Status::kComplete; + break; + } + + } while (ShouldContinueRepeatedPasses(num_of_transformations_to_apply == 0)); + + if (status != Status::kFuzzerPassLedToInvalidModule) { + // We apply this transformations despite the fact that we might exceed + // |num_of_transformations_to_apply|. This is not a problem for us since + // these fuzzer passes are relatively simple yet might trigger some bugs. + for (auto& pass : final_passes_) { + if (!ApplyPassAndCheckValidity(pass.get())) { + status = Status::kFuzzerPassLedToInvalidModule; + break; + } + } } - // If we have applied T transformations so far, and the limit on the number of - // transformations to apply is L (where T < L), the chance that we will - // continue fuzzing is: - // - // 1 - T/(2*L) - // - // That is, the chance of continuing decreases as more transformations are - // applied. Using 2*L instead of L increases the number of transformations - // that are applied on average. - auto chance_of_continuing = static_cast( - 100.0 * (1.0 - (static_cast(transformations_applied_so_far) / - (2.0 * static_cast( - fuzzer_context_->GetTransformationLimit()))))); - if (!fuzzer_context_->ChoosePercentage(chance_of_continuing)) { - // We have probabilistically decided to stop. - return false; + + is_valid_ = status != Status::kFuzzerPassLedToInvalidModule; + return {status, static_cast( + transformation_sequence_out_.transformation_size()) != + initial_num_of_transformations}; +} + +bool Fuzzer::ShouldContinueRepeatedPasses( + bool continue_fuzzing_probabilistically) { + if (continue_fuzzing_probabilistically) { + // If we have applied T transformations so far, and the limit on the number + // of transformations to apply is L (where T < L), the chance that we will + // continue fuzzing is: + // + // 1 - T/(2*L) + // + // That is, the chance of continuing decreases as more transformations are + // applied. Using 2*L instead of L increases the number of transformations + // that are applied on average. + auto transformations_applied_so_far = static_cast( + transformation_sequence_out_.transformation_size()); + auto chance_of_continuing = static_cast( + 100.0 * + (1.0 - (static_cast(transformations_applied_so_far) / + (2.0 * static_cast( + fuzzer_context_->GetTransformationLimit()))))); + if (!fuzzer_context_->ChoosePercentage(chance_of_continuing)) { + // We have probabilistically decided to stop. + return false; + } } // Continue fuzzing! num_repeated_passes_applied_++; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer.h b/third_party/spirv-tools/source/fuzz/fuzzer.h index 774457f548..1e7d6860c2 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer.h @@ -23,6 +23,7 @@ #include "source/fuzz/fuzzer_pass.h" #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/pass_management/repeated_pass_instances.h" +#include "source/fuzz/pass_management/repeated_pass_manager.h" #include "source/fuzz/pass_management/repeated_pass_recommender.h" #include "source/fuzz/protobufs/spirvfuzz_protobufs.h" #include "source/fuzz/random_generator.h" @@ -37,33 +38,28 @@ namespace fuzz { class Fuzzer { public: // Possible statuses that can result from running the fuzzer. - enum class FuzzerResultStatus { + enum class Status { kComplete, - kFailedToCreateSpirvToolsInterface, + kModuleTooBig, + kTransformationLimitReached, + kFuzzerStuck, kFuzzerPassLedToInvalidModule, - kInitialBinaryInvalid, }; - struct FuzzerResult { - FuzzerResultStatus status; - std::vector transformed_binary; - protobufs::TransformationSequence applied_transformations; + struct Result { + // Status of the fuzzing session. + Status status; + + // Equals to true if new transformations were applied during the previous + // fuzzing session. + bool is_changed; }; - // Each field of this enum corresponds to an available repeated pass - // strategy, and is used to decide which kind of RepeatedPassManager object - // to create. - enum class RepeatedPassStrategy { - kSimple, - kRandomWithRecommendations, - kLoopedWithRecommendations - }; - - Fuzzer(spv_target_env target_env, MessageConsumer consumer, - const std::vector& binary_in, - const protobufs::FactSequence& initial_facts, + Fuzzer(std::unique_ptr ir_context, + std::unique_ptr transformation_context, + std::unique_ptr fuzzer_context, + MessageConsumer consumer, const std::vector& donor_suppliers, - std::unique_ptr random_generator, bool enable_all_passes, RepeatedPassStrategy repeated_pass_strategy, bool validate_after_each_fuzzer_pass, spv_validator_options validator_options); @@ -76,15 +72,23 @@ class Fuzzer { ~Fuzzer(); - // Transforms |binary_in_| by running a number of randomized fuzzer passes. - // Initial facts about the input binary and the context in which it will - // execute are provided via |initial_facts_|. A source of donor modules to be - // used by transformations is provided via |donor_suppliers_|. On success, - // returns a successful result status together with the transformed binary and - // the sequence of transformations that were applied. Otherwise, returns an - // appropriate result status together with an empty binary and empty - // transformation sequence. - FuzzerResult Run(); + // Transforms |ir_context_| by running a number of randomized fuzzer passes. + // Initial facts about the input binary and the context in which it will be + // executed are provided with |transformation_context_|. + // |num_of_transformations| is equal to the maximum number of transformations + // applied in a single call to this method. This parameter is ignored if its + // value is equal to 0. Because fuzzing cannot stop mid way through a fuzzer + // pass, fuzzing will stop after the fuzzer pass that exceeds + // |num_of_transformations| has completed, so that the total number of + // transformations may be somewhat larger than this number. + Result Run(uint32_t num_of_transformations_to_apply); + + // Returns the current IR context. It may be invalid if the Run method + // returned Status::kFuzzerPassLedToInvalidModule previously. + opt::IRContext* GetIRContext(); + + // Returns the sequence of applied transformations. + const protobufs::TransformationSequence& GetTransformationSequence() const; private: // A convenience method to add a repeated fuzzer pass to |pass_instances| with @@ -119,7 +123,9 @@ class Fuzzer { // Decides whether to apply more repeated passes. The probability decreases as // the number of transformations that have been applied increases. - bool ShouldContinueFuzzing(); + // The described probability is only applied if + // |continue_fuzzing_probabilistically| is true. + bool ShouldContinueRepeatedPasses(bool continue_fuzzing_probabilistically); // Applies |pass|, which must be a pass constructed with |ir_context|. // If |validate_after_each_fuzzer_pass_| is not set, true is always returned. @@ -128,57 +134,59 @@ class Fuzzer { // instruction has a distinct unique id. bool ApplyPassAndCheckValidity(FuzzerPass* pass) const; - // Target environment. - const spv_target_env target_env_; - // Message consumer that will be invoked once for each message communicated // from the library. - MessageConsumer consumer_; - - // The initial binary to which fuzzing should be applied. - const std::vector& binary_in_; - - // Initial facts known to hold in advance of applying any transformations. - const protobufs::FactSequence& initial_facts_; - - // A source of modules whose contents can be donated into the module being - // fuzzed. - const std::vector& donor_suppliers_; - - // Random number generator to control decision making during fuzzing. - std::unique_ptr random_generator_; + const MessageConsumer consumer_; // Determines whether all passes should be enabled, vs. having passes be // probabilistically enabled. - bool enable_all_passes_; - - // Controls which type of RepeatedPassManager object to create. - RepeatedPassStrategy repeated_pass_strategy_; + const bool enable_all_passes_; // Determines whether the validator should be invoked after every fuzzer pass. - bool validate_after_each_fuzzer_pass_; + const bool validate_after_each_fuzzer_pass_; // Options to control validation. - spv_validator_options validator_options_; + const spv_validator_options validator_options_; // The number of repeated fuzzer passes that have been applied is kept track // of, in order to enforce a hard limit on the number of times such passes // can be applied. uint32_t num_repeated_passes_applied_; + // We use this to determine whether we can continue fuzzing incrementally + // since the previous call to the Run method could've returned + // kFuzzerPassLedToInvalidModule. + bool is_valid_; + // Intermediate representation for the module being fuzzed, which gets // mutated as fuzzing proceeds. std::unique_ptr ir_context_; + // Contextual information that is required in order to apply + // transformations. + std::unique_ptr transformation_context_; + // Provides probabilities that control the fuzzing process. std::unique_ptr fuzzer_context_; - // Contextual information that is required in order to apply transformations. - std::unique_ptr transformation_context_; - - // The sequence of transformations that have been applied during fuzzing. It + // The sequence of transformations that have been applied during fuzzing. It // is initially empty and grows as fuzzer passes are applied. protobufs::TransformationSequence transformation_sequence_out_; + + // This object contains instances of all fuzzer passes that will participate + // in the fuzzing. + RepeatedPassInstances pass_instances_; + + // This object defines the recommendation logic for fuzzer passes. + std::unique_ptr repeated_pass_recommender_; + + // This object manager a list of fuzzer pass and their available + // recommendations. + std::unique_ptr repeated_pass_manager_; + + // Some passes that it does not make sense to apply repeatedly, as they do not + // unlock other passes. + std::vector> final_passes_; }; } // namespace fuzz diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_context.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_context.cpp index 47bf4e2580..9e9650f646 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_context.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_context.cpp @@ -21,6 +21,12 @@ namespace fuzz { namespace { +// An offset between the the module's id bound and the minimum fresh id. +// +// TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541): consider +// the case where the maximum id bound is reached. +const uint32_t kIdBoundGap = 100; + // Limits to help control the overall fuzzing process and rein in individual // fuzzer passes. const uint32_t kIdBoundLimit = 50000; @@ -114,6 +120,8 @@ const std::pair kChanceOfMovingBlockDown = {20, 50}; const std::pair kChanceOfMutatingPointer = {20, 90}; const std::pair kChanceOfObfuscatingConstant = {10, 90}; const std::pair kChanceOfOutliningFunction = {10, 90}; +const std::pair kChanceOfPermutingFunctionVariables = {30, + 90}; const std::pair kChanceOfPermutingInstructions = {20, 70}; const std::pair kChanceOfPermutingParameters = {30, 90}; const std::pair kChanceOfPermutingPhiOperands = {30, 90}; @@ -145,8 +153,11 @@ const std::pair kChanceOfReplacingParametersWithGlobals = { const std::pair kChanceOfReplacingParametersWithStruct = { 20, 40}; const std::pair kChanceOfSplittingBlock = {40, 95}; +const std::pair + kChanceOfSwappingAnotherPairOfFunctionVariables = {30, 90}; const std::pair kChanceOfSwappingConditionalBranchOperands = {10, 70}; +const std::pair kChanceOfSwappingFunctions = {10, 90}; const std::pair kChanceOfTogglingAccessChainInstruction = { 20, 90}; const std::pair kChanceOfWrappingRegionInSelection = {70, @@ -177,10 +188,11 @@ const std::function } // namespace -FuzzerContext::FuzzerContext(RandomGenerator* random_generator, - uint32_t min_fresh_id) - : random_generator_(random_generator), +FuzzerContext::FuzzerContext(std::unique_ptr random_generator, + uint32_t min_fresh_id, bool is_wgsl_compatible) + : random_generator_(std::move(random_generator)), next_fresh_id_(min_fresh_id), + is_wgsl_compatible_(is_wgsl_compatible), max_equivalence_class_size_for_data_synonym_fact_closure_( kDefaultMaxEquivalenceClassSizeForDataSynonymFactClosure), max_loop_control_partial_count_(kDefaultMaxLoopControlPartialCount), @@ -308,6 +320,8 @@ FuzzerContext::FuzzerContext(RandomGenerator* random_generator, ChooseBetweenMinAndMax(kChanceOfObfuscatingConstant); chance_of_outlining_function_ = ChooseBetweenMinAndMax(kChanceOfOutliningFunction); + chance_of_permuting_function_variables_ = + ChooseBetweenMinAndMax(kChanceOfPermutingFunctionVariables); chance_of_permuting_instructions_ = ChooseBetweenMinAndMax(kChanceOfPermutingInstructions); chance_of_permuting_parameters_ = @@ -345,8 +359,12 @@ FuzzerContext::FuzzerContext(RandomGenerator* random_generator, chance_of_replacing_parameters_with_struct_ = ChooseBetweenMinAndMax(kChanceOfReplacingParametersWithStruct); chance_of_splitting_block_ = ChooseBetweenMinAndMax(kChanceOfSplittingBlock); + chance_of_swapping_another_pair_of_function_variables_ = + ChooseBetweenMinAndMax(kChanceOfSwappingAnotherPairOfFunctionVariables); chance_of_swapping_conditional_branch_operands_ = ChooseBetweenMinAndMax(kChanceOfSwappingConditionalBranchOperands); + chance_of_swapping_functions_ = + ChooseBetweenMinAndMax(kChanceOfSwappingFunctions); chance_of_toggling_access_chain_instruction_ = ChooseBetweenMinAndMax(kChanceOfTogglingAccessChainInstruction); chance_of_wrapping_region_in_selection_ = @@ -403,5 +421,9 @@ uint32_t FuzzerContext::GetTransformationLimit() const { return kTransformationLimit; } +uint32_t FuzzerContext::GetMinFreshId(opt::IRContext* ir_context) { + return ir_context->module()->id_bound() + kIdBoundGap; +} + } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_context.h b/third_party/spirv-tools/source/fuzz/fuzzer_context.h index 8c51041884..ef2cc2c548 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_context.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_context.h @@ -21,6 +21,7 @@ #include "source/fuzz/protobufs/spirvfuzz_protobufs.h" #include "source/fuzz/random_generator.h" #include "source/opt/function.h" +#include "source/opt/ir_context.h" namespace spvtools { namespace fuzz { @@ -32,7 +33,8 @@ class FuzzerContext { public: // Constructs a fuzzer context with a given random generator and the minimum // value that can be used for fresh ids. - FuzzerContext(RandomGenerator* random_generator, uint32_t min_fresh_id); + FuzzerContext(std::unique_ptr random_generator, + uint32_t min_fresh_id, bool is_wgsl_compatible); ~FuzzerContext(); @@ -64,7 +66,7 @@ class FuzzerContext { } // Randomly shuffles a |sequence| between |lo| and |hi| indices inclusively. - // |lo| and |hi| must be valid indices to the |sequence| + // |lo| and |hi| must be valid indices to the |sequence|. template void Shuffle(std::vector* sequence, size_t lo, size_t hi) const { auto& array = *sequence; @@ -89,7 +91,7 @@ class FuzzerContext { } } - // Ramdomly shuffles a |sequence| + // Randomly shuffles a |sequence|. template void Shuffle(std::vector* sequence) const { if (!sequence->empty()) { @@ -102,7 +104,7 @@ class FuzzerContext { uint32_t GetFreshId(); // Returns a vector of |count| fresh ids. - std::vector GetFreshIds(const uint32_t count); + std::vector GetFreshIds(uint32_t count); // A suggested limit on the id bound for the module being fuzzed. This is // useful for deciding when to stop the overall fuzzing process. Furthermore, @@ -115,6 +117,14 @@ class FuzzerContext { // fuzzer passes. uint32_t GetTransformationLimit() const; + // Returns the minimum fresh id that can be used given the |ir_context|. + static uint32_t GetMinFreshId(opt::IRContext* ir_context); + + // Returns true if all transformations should be compatible with WGSL. + bool IsWgslCompatible() const { + return is_wgsl_compatible_; + } + // Probabilities associated with applying various transformations. // Keep them in alphabetical order. uint32_t GetChanceOfAcceptingRepeatedPassRecommendation() const { @@ -293,6 +303,9 @@ class FuzzerContext { uint32_t GetChanceOfOutliningFunction() const { return chance_of_outlining_function_; } + uint32_t GetChanceOfPermutingFunctionVariables() const { + return chance_of_permuting_function_variables_; + } uint32_t GetChanceOfPermutingInstructions() const { return chance_of_permuting_instructions_; } @@ -350,9 +363,17 @@ class FuzzerContext { uint32_t GetChanceOfSplittingBlock() const { return chance_of_splitting_block_; } + uint32_t GetChanceOfSwappingAnotherPairOfFunctionVariables() const { + return chance_of_swapping_another_pair_of_function_variables_; + } uint32_t GetChanceOfSwappingConditionalBranchOperands() const { return chance_of_swapping_conditional_branch_operands_; } + + uint32_t GetChanceOfSwappingFunctions() const { + return chance_of_swapping_functions_; + } + uint32_t GetChanceOfTogglingAccessChainInstruction() const { return chance_of_toggling_access_chain_instruction_; } @@ -442,15 +463,18 @@ class FuzzerContext { return random_generator_->RandomUint32(max_unused_component_count) + 1; } bool GoDeeperInConstantObfuscation(uint32_t depth) { - return go_deeper_in_constant_obfuscation_(depth, random_generator_); + return go_deeper_in_constant_obfuscation_(depth, random_generator_.get()); } private: // The source of randomness. - RandomGenerator* random_generator_; + std::unique_ptr random_generator_; // The next fresh id to be issued. uint32_t next_fresh_id_; + // True if all transformations should be compatible with WGSL spec. + bool is_wgsl_compatible_; + // Probabilities associated with applying various transformations. // Keep them in alphabetical order. uint32_t chance_of_accepting_repeated_pass_recommendation_; @@ -513,6 +537,7 @@ class FuzzerContext { uint32_t chance_of_mutating_pointer_; uint32_t chance_of_obfuscating_constant_; uint32_t chance_of_outlining_function_; + uint32_t chance_of_permuting_function_variables_; uint32_t chance_of_permuting_instructions_; uint32_t chance_of_permuting_parameters_; uint32_t chance_of_permuting_phi_operands_; @@ -532,7 +557,9 @@ class FuzzerContext { uint32_t chance_of_replacing_parameters_with_globals_; uint32_t chance_of_replacing_parameters_with_struct_; uint32_t chance_of_splitting_block_; + uint32_t chance_of_swapping_another_pair_of_function_variables_; uint32_t chance_of_swapping_conditional_branch_operands_; + uint32_t chance_of_swapping_functions_; uint32_t chance_of_toggling_access_chain_instruction_; uint32_t chance_of_wrapping_region_in_selection_; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass.cpp index 486f18fa8c..9e95190c1d 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass.cpp @@ -111,10 +111,8 @@ void FuzzerPass::ForEachInstructionWithInstructionDescriptor( // module. std::vector reachable_blocks; - const auto* dominator_analysis = - GetIRContext()->GetDominatorAnalysis(function); for (auto& block : *function) { - if (dominator_analysis->IsReachable(&block)) { + if (GetIRContext()->IsReachable(block)) { reachable_blocks.push_back(&block); } } @@ -184,6 +182,35 @@ void FuzzerPass::ForEachInstructionWithInstructionDescriptor( } } +void FuzzerPass::ApplyTransformation(const Transformation& transformation) { + assert(transformation.IsApplicable(GetIRContext(), + *GetTransformationContext()) && + "Transformation should be applicable by construction."); + transformation.Apply(GetIRContext(), GetTransformationContext()); + auto transformation_message = transformation.ToMessage(); + assert(transformation_message.transformation_case() != + protobufs::Transformation::TRANSFORMATION_NOT_SET && + "Bad transformation."); + *GetTransformations()->add_transformation() = + std::move(transformation_message); +} + +bool FuzzerPass::MaybeApplyTransformation( + const Transformation& transformation) { + if (transformation.IsApplicable(GetIRContext(), + *GetTransformationContext())) { + transformation.Apply(GetIRContext(), GetTransformationContext()); + auto transformation_message = transformation.ToMessage(); + assert(transformation_message.transformation_case() != + protobufs::Transformation::TRANSFORMATION_NOT_SET && + "Bad transformation."); + *GetTransformations()->add_transformation() = + std::move(transformation_message); + return true; + } + return false; +} + uint32_t FuzzerPass::FindOrCreateBoolType() { if (auto existing_id = fuzzerutil::MaybeGetBoolType(GetIRContext())) { return existing_id; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass.h index da3f239071..ec254855a2 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass.h @@ -106,37 +106,13 @@ class FuzzerPass { // A generic helper for applying a transformation that should be applicable // by construction, and adding it to the sequence of applied transformations. - void ApplyTransformation(const Transformation& transformation) { - assert(transformation.IsApplicable(GetIRContext(), - *GetTransformationContext()) && - "Transformation should be applicable by construction."); - transformation.Apply(GetIRContext(), GetTransformationContext()); - protobufs::Transformation transformation_message = - transformation.ToMessage(); - assert(transformation_message.transformation_case() != - protobufs::Transformation::TRANSFORMATION_NOT_SET && - "Bad transformation."); - *GetTransformations()->add_transformation() = transformation_message; - } + void ApplyTransformation(const Transformation& transformation); // A generic helper for applying a transformation only if it is applicable. // If it is applicable, the transformation is applied and then added to the // sequence of applied transformations and the function returns true. // Otherwise, the function returns false. - bool MaybeApplyTransformation(const Transformation& transformation) { - if (transformation.IsApplicable(GetIRContext(), - *GetTransformationContext())) { - transformation.Apply(GetIRContext(), GetTransformationContext()); - protobufs::Transformation transformation_message = - transformation.ToMessage(); - assert(transformation_message.transformation_case() != - protobufs::Transformation::TRANSFORMATION_NOT_SET && - "Bad transformation."); - *GetTransformations()->add_transformation() = transformation_message; - return true; - } - return false; - } + bool MaybeApplyTransformation(const Transformation& transformation); // Returns the id of an OpTypeBool instruction. If such an instruction does // not exist, a transformation is applied to add it. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.cpp index 11155f23db..c498642c06 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.cpp @@ -27,8 +27,6 @@ FuzzerPassAddAccessChains::FuzzerPassAddAccessChains( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddAccessChains::~FuzzerPassAddAccessChains() = default; - void FuzzerPassAddAccessChains::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.h index 8649296f05..e80c2c6c71 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_access_chains.h @@ -30,8 +30,6 @@ class FuzzerPassAddAccessChains : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddAccessChains(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.cpp index 7b9ac4e28e..78abf5be07 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.cpp @@ -28,9 +28,6 @@ FuzzerPassAddBitInstructionSynonyms::FuzzerPassAddBitInstructionSynonyms( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddBitInstructionSynonyms::~FuzzerPassAddBitInstructionSynonyms() = - default; - void FuzzerPassAddBitInstructionSynonyms::Apply() { for (auto& function : *GetIRContext()->module()) { for (auto& block : function) { @@ -48,22 +45,11 @@ void FuzzerPassAddBitInstructionSynonyms::Apply() { continue; } - // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3557): - // Right now we only support certain operations. When this issue is - // addressed the following conditional can use the function - // |spvOpcodeIsBit|. - if (instruction.opcode() != SpvOpBitwiseOr && - instruction.opcode() != SpvOpBitwiseXor && - instruction.opcode() != SpvOpBitwiseAnd && - instruction.opcode() != SpvOpNot) { - continue; - } - - // Right now, only integer operands are supported. - if (GetIRContext() - ->get_type_mgr() - ->GetType(instruction.type_id()) - ->AsVector()) { + // Make sure fuzzer never applies a transformation to a bitwise + // instruction with differently signed operands, only integer operands + // are supported and bitwise operations are supported only. + if (!TransformationAddBitInstructionSynonym::IsInstructionSupported( + GetIRContext(), &instruction)) { continue; } diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.h index 0194425d86..28f95779cc 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_bit_instruction_synonyms.h @@ -30,8 +30,6 @@ class FuzzerPassAddBitInstructionSynonyms : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddBitInstructionSynonyms(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.cpp index 132a49dace..19f9902435 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.cpp @@ -14,6 +14,7 @@ #include "source/fuzz/fuzzer_pass_add_composite_extract.h" +#include "source/fuzz/available_instructions.h" #include "source/fuzz/fuzzer_context.h" #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/instruction_descriptor.h" @@ -29,8 +30,6 @@ FuzzerPassAddCompositeExtract::FuzzerPassAddCompositeExtract( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddCompositeExtract::~FuzzerPassAddCompositeExtract() = default; - void FuzzerPassAddCompositeExtract::Apply() { std::vector composite_synonyms; for (const auto* dd : @@ -41,14 +40,16 @@ void FuzzerPassAddCompositeExtract::Apply() { } } - // We don't want to invalidate the module every time we apply this - // transformation since rebuilding DominatorAnalysis can be expensive, so we - // collect up the transformations we wish to apply and apply them all later. - std::vector transformations; + AvailableInstructions available_composites( + GetIRContext(), [](opt::IRContext* ir_context, opt::Instruction* inst) { + return inst->type_id() && inst->result_id() && + fuzzerutil::IsCompositeType( + ir_context->get_type_mgr()->GetType(inst->type_id())); + }); ForEachInstructionWithInstructionDescriptor( - [this, &composite_synonyms, &transformations]( - opt::Function* function, opt::BasicBlock* block, + [this, &available_composites, &composite_synonyms]( + opt::Function* /*unused*/, opt::BasicBlock* /*unused*/, opt::BasicBlock::iterator inst_it, const protobufs::InstructionDescriptor& instruction_descriptor) { if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract, @@ -61,14 +62,6 @@ void FuzzerPassAddCompositeExtract::Apply() { return; } - auto available_composites = FindAvailableInstructions( - function, block, inst_it, - [](opt::IRContext* ir_context, opt::Instruction* inst) { - return inst->type_id() && inst->result_id() && - fuzzerutil::IsCompositeType( - ir_context->get_type_mgr()->GetType(inst->type_id())); - }); - std::vector available_synonyms; for (const auto* dd : composite_synonyms) { if (fuzzerutil::IdIsAvailableBeforeInstruction( @@ -77,18 +70,21 @@ void FuzzerPassAddCompositeExtract::Apply() { } } - if (available_synonyms.empty() && available_composites.empty()) { + auto candidate_composites = + available_composites.GetAvailableBeforeInstruction(&*inst_it); + + if (available_synonyms.empty() && candidate_composites.empty()) { return; } uint32_t composite_id = 0; std::vector indices; - if (available_synonyms.empty() || (!available_composites.empty() && + if (available_synonyms.empty() || (!candidate_composites.empty() && GetFuzzerContext()->ChooseEven())) { const auto* inst = - available_composites[GetFuzzerContext()->RandomIndex( - available_composites)]; + candidate_composites[GetFuzzerContext()->RandomIndex( + candidate_composites)]; composite_id = inst->result_id(); auto type_id = inst->type_id(); @@ -153,14 +149,10 @@ void FuzzerPassAddCompositeExtract::Apply() { assert(composite_id != 0 && !indices.empty() && "Composite object should have been chosen correctly"); - transformations.emplace_back(instruction_descriptor, - GetFuzzerContext()->GetFreshId(), - composite_id, indices); + ApplyTransformation(TransformationCompositeExtract( + instruction_descriptor, GetFuzzerContext()->GetFreshId(), + composite_id, indices)); }); - - for (const auto& transformation : transformations) { - ApplyTransformation(transformation); - } } } // namespace fuzz diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.h index 8bcb825fb1..32ac190a53 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_extract.h @@ -29,8 +29,6 @@ class FuzzerPassAddCompositeExtract : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddCompositeExtract() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.cpp index e58c754c28..cf314d30bc 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.cpp @@ -29,8 +29,6 @@ FuzzerPassAddCompositeInserts::FuzzerPassAddCompositeInserts( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddCompositeInserts::~FuzzerPassAddCompositeInserts() = default; - void FuzzerPassAddCompositeInserts::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.h index c4f510346f..4d511f6c75 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_inserts.h @@ -29,7 +29,6 @@ class FuzzerPassAddCompositeInserts : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddCompositeInserts(); void Apply() override; // Checks if any component of a composite is a pointer. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.cpp index c4d8d1c9cf..3dfbd690f7 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.cpp @@ -28,8 +28,6 @@ FuzzerPassAddCompositeTypes::FuzzerPassAddCompositeTypes( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddCompositeTypes::~FuzzerPassAddCompositeTypes() = default; - void FuzzerPassAddCompositeTypes::Apply() { MaybeAddMissingVectorTypes(); MaybeAddMissingMatrixTypes(); @@ -125,7 +123,9 @@ uint32_t FuzzerPassAddCompositeTypes::ChooseScalarOrCompositeType() { break; case SpvOpTypeStruct: { if (!fuzzerutil::MembersHaveBuiltInDecoration(GetIRContext(), - inst.result_id())) { + inst.result_id()) && + !fuzzerutil::HasBlockOrBufferBlockDecoration(GetIRContext(), + inst.result_id())) { candidates.push_back(inst.result_id()); } } break; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.h index 87bc0ff3f5..89d48f8ab0 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_composite_types.h @@ -29,8 +29,6 @@ class FuzzerPassAddCompositeTypes : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddCompositeTypes(); - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.cpp index d98619c26b..b654927f6e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.cpp @@ -29,8 +29,6 @@ FuzzerPassAddCopyMemory::FuzzerPassAddCopyMemory( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddCopyMemory::~FuzzerPassAddCopyMemory() = default; - void FuzzerPassAddCopyMemory::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.h index 321e4a1d6a..0f7db0c7e5 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_copy_memory.h @@ -29,8 +29,6 @@ class FuzzerPassAddCopyMemory : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddCopyMemory() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.cpp index 84ed1fb99b..8c166a2033 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.cpp @@ -14,12 +14,20 @@ #include "source/fuzz/fuzzer_pass_add_dead_blocks.h" +#include + #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/transformation_add_dead_block.h" namespace spvtools { namespace fuzz { +namespace { + +const size_t kMaxTransformationsInOnePass = 100U; + +} // namespace + FuzzerPassAddDeadBlocks::FuzzerPassAddDeadBlocks( opt::IRContext* ir_context, TransformationContext* transformation_context, FuzzerContext* fuzzer_context, @@ -27,8 +35,6 @@ FuzzerPassAddDeadBlocks::FuzzerPassAddDeadBlocks( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddDeadBlocks::~FuzzerPassAddDeadBlocks() = default; - void FuzzerPassAddDeadBlocks::Apply() { // We iterate over all blocks in the module collecting up those at which we // might add a branch to a new dead block. We then loop over all such @@ -57,9 +63,18 @@ void FuzzerPassAddDeadBlocks::Apply() { GetFuzzerContext()->GetFreshId(), block.id(), condition_value)); } } - // Apply all those transformations that are in fact applicable. - for (auto& transformation : candidate_transformations) { - MaybeApplyTransformation(transformation); + // Applying transformations can be expensive as each transformation requires + // dominator information and also invalidates dominator information. We thus + // limit the number of transformations that one application of this fuzzer + // pass can apply. We choose to do this after identifying all the + // transformations that we *might* want to apply, rather than breaking the + // above loops once the limit is reached, to avoid biasing towards + // transformations that target early parts of the module. + GetFuzzerContext()->Shuffle(&candidate_transformations); + for (size_t i = 0; i < std::min(kMaxTransformationsInOnePass, + candidate_transformations.size()); + i++) { + MaybeApplyTransformation(candidate_transformations[i]); } } diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.h index d78f08836c..a87c05c385 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_blocks.h @@ -29,8 +29,6 @@ class FuzzerPassAddDeadBlocks : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddDeadBlocks(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.cpp index e726c63e91..0c18da9099 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.cpp @@ -28,8 +28,6 @@ FuzzerPassAddDeadBreaks::FuzzerPassAddDeadBreaks( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddDeadBreaks::~FuzzerPassAddDeadBreaks() = default; - void FuzzerPassAddDeadBreaks::Apply() { // We first collect up lots of possibly-applicable transformations. std::vector candidate_transformations; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.h index c379eed51c..d1086fc4fb 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_breaks.h @@ -28,8 +28,6 @@ class FuzzerPassAddDeadBreaks : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddDeadBreaks(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.cpp index 24617ae36e..1ab40b7371 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.cpp @@ -28,8 +28,6 @@ FuzzerPassAddDeadContinues::FuzzerPassAddDeadContinues( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddDeadContinues::~FuzzerPassAddDeadContinues() = default; - void FuzzerPassAddDeadContinues::Apply() { // Consider every block in every function. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.h index b2acb935e7..bf0009e444 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_dead_continues.h @@ -28,8 +28,6 @@ class FuzzerPassAddDeadContinues : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddDeadContinues(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.cpp index 6376c9fc1f..15554b7a63 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.cpp @@ -49,9 +49,6 @@ FuzzerPassAddEquationInstructions::FuzzerPassAddEquationInstructions( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddEquationInstructions::~FuzzerPassAddEquationInstructions() = - default; - void FuzzerPassAddEquationInstructions::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.h index 9ce581eb30..dbec5bacd1 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_equation_instructions.h @@ -31,8 +31,6 @@ class FuzzerPassAddEquationInstructions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddEquationInstructions(); - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.cpp index 74005579c4..2240696b94 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.cpp @@ -30,8 +30,6 @@ FuzzerPassAddFunctionCalls::FuzzerPassAddFunctionCalls( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddFunctionCalls::~FuzzerPassAddFunctionCalls() = default; - void FuzzerPassAddFunctionCalls::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.h index 4ed8791160..081510c1ad 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_function_calls.h @@ -29,8 +29,6 @@ class FuzzerPassAddFunctionCalls : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddFunctionCalls(); - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.cpp index 9a45a374d4..067974134e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.cpp @@ -27,8 +27,6 @@ FuzzerPassAddGlobalVariables::FuzzerPassAddGlobalVariables( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddGlobalVariables::~FuzzerPassAddGlobalVariables() = default; - void FuzzerPassAddGlobalVariables::Apply() { SpvStorageClass variable_storage_class = SpvStorageClassPrivate; for (auto& entry_point : GetIRContext()->module()->entry_points()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.h index a907d360c7..3745c5c387 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_global_variables.h @@ -29,8 +29,6 @@ class FuzzerPassAddGlobalVariables : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddGlobalVariables(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.cpp index 3095bb6e5c..c10db720e5 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.cpp @@ -31,9 +31,6 @@ FuzzerPassAddImageSampleUnusedComponents:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddImageSampleUnusedComponents:: - ~FuzzerPassAddImageSampleUnusedComponents() = default; - void FuzzerPassAddImageSampleUnusedComponents::Apply() { // SPIR-V module to help understand the transformation. // diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.h index 26374c326d..f5dea8bfbc 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_image_sample_unused_components.h @@ -30,8 +30,6 @@ class FuzzerPassAddImageSampleUnusedComponents : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddImageSampleUnusedComponents(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.cpp index 256255bcd6..2e50da2628 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.cpp @@ -27,8 +27,6 @@ FuzzerPassAddLoads::FuzzerPassAddLoads( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddLoads::~FuzzerPassAddLoads() = default; - void FuzzerPassAddLoads::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.h index c4d5b27e23..3913c6246c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loads.h @@ -28,8 +28,6 @@ class FuzzerPassAddLoads : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddLoads(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.cpp index ef8b5d0e90..a50b0b072d 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.cpp @@ -28,8 +28,6 @@ FuzzerPassAddLocalVariables::FuzzerPassAddLocalVariables( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddLocalVariables::~FuzzerPassAddLocalVariables() = default; - void FuzzerPassAddLocalVariables::Apply() { auto basic_type_ids_and_pointers = GetAvailableBasicTypesAndPointers(SpvStorageClassFunction); diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.h index 08d26d8c38..d73dae29ce 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_local_variables.h @@ -29,8 +29,6 @@ class FuzzerPassAddLocalVariables : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddLocalVariables(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.cpp index bdc315136f..1cfed866ca 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.cpp @@ -27,8 +27,6 @@ FuzzerPassAddLoopPreheaders::FuzzerPassAddLoopPreheaders( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddLoopPreheaders::~FuzzerPassAddLoopPreheaders() = default; - void FuzzerPassAddLoopPreheaders::Apply() { for (auto& function : *GetIRContext()->module()) { // Keep track of all the loop headers we want to add a preheader to. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.h index a8350567a4..8ac2dac8c2 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loop_preheaders.h @@ -32,8 +32,6 @@ class FuzzerPassAddLoopPreheaders : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddLoopPreheaders(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.cpp index 31a57798e5..69e0697f87 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.cpp @@ -33,9 +33,6 @@ FuzzerPassAddLoopsToCreateIntConstantSynonyms:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddLoopsToCreateIntConstantSynonyms:: - ~FuzzerPassAddLoopsToCreateIntConstantSynonyms() = default; - void FuzzerPassAddLoopsToCreateIntConstantSynonyms::Apply() { std::vector constants; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.h index ee98c4e7fd..2eacef5fc7 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_loops_to_create_int_constant_synonyms.h @@ -30,8 +30,6 @@ class FuzzerPassAddLoopsToCreateIntConstantSynonyms : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddLoopsToCreateIntConstantSynonyms(); - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.cpp index 09627d0986..d0753100ca 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.cpp @@ -26,9 +26,6 @@ FuzzerPassAddNoContractionDecorations::FuzzerPassAddNoContractionDecorations( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddNoContractionDecorations:: - ~FuzzerPassAddNoContractionDecorations() = default; - void FuzzerPassAddNoContractionDecorations::Apply() { // Consider every instruction in every block in every function. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.h index c0c1e09da9..74212d8719 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_no_contraction_decorations.h @@ -28,8 +28,6 @@ class FuzzerPassAddNoContractionDecorations : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddNoContractionDecorations() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.cpp index 2b339ca039..be6e7ea1aa 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.cpp @@ -27,8 +27,6 @@ FuzzerPassAddOpPhiSynonyms::FuzzerPassAddOpPhiSynonyms( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddOpPhiSynonyms::~FuzzerPassAddOpPhiSynonyms() = default; - void FuzzerPassAddOpPhiSynonyms::Apply() { // Get a list of synonymous ids with the same type that can be used in the // same OpPhi instruction. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.h index 6c7d752221..9077118e25 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_opphi_synonyms.h @@ -30,8 +30,6 @@ class FuzzerPassAddOpPhiSynonyms : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddOpPhiSynonyms() override; - void Apply() override; // Computes the equivalence classes for the non-pointer and non-irrelevant ids diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.cpp index 35532e9067..784653d8ec 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.cpp @@ -29,8 +29,6 @@ FuzzerPassAddParameters::FuzzerPassAddParameters( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddParameters::~FuzzerPassAddParameters() = default; - void FuzzerPassAddParameters::Apply() { // Compute type candidates for the new parameter. std::vector type_candidates; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.h index f1261ae516..47dde390e3 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_parameters.h @@ -32,8 +32,6 @@ class FuzzerPassAddParameters : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddParameters() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.cpp index a2497df789..58c6d1b2a0 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.cpp @@ -26,8 +26,6 @@ FuzzerPassAddRelaxedDecorations::FuzzerPassAddRelaxedDecorations( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddRelaxedDecorations::~FuzzerPassAddRelaxedDecorations() = default; - void FuzzerPassAddRelaxedDecorations::Apply() { // Consider every instruction in every block in every function. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.h index 897b8216c2..723c4a0afe 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_relaxed_decorations.h @@ -28,8 +28,6 @@ class FuzzerPassAddRelaxedDecorations : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddRelaxedDecorations() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.cpp index 46efc6431f..f89428d3d4 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.cpp @@ -27,8 +27,6 @@ FuzzerPassAddStores::FuzzerPassAddStores( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddStores::~FuzzerPassAddStores() = default; - void FuzzerPassAddStores::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.h index 55ec67f2bf..9519c385bb 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_stores.h @@ -30,8 +30,6 @@ class FuzzerPassAddStores : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddStores(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.cpp index 2fa0700040..fd866f985b 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.cpp @@ -29,8 +29,6 @@ FuzzerPassAddSynonyms::FuzzerPassAddSynonyms( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddSynonyms::~FuzzerPassAddSynonyms() = default; - void FuzzerPassAddSynonyms::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, @@ -81,6 +79,8 @@ void FuzzerPassAddSynonyms::Apply() { case protobufs::TransformationAddSynonym::ADD_ZERO: case protobufs::TransformationAddSynonym::SUB_ZERO: case protobufs::TransformationAddSynonym::LOGICAL_OR: + case protobufs::TransformationAddSynonym::BITWISE_OR: + case protobufs::TransformationAddSynonym::BITWISE_XOR: // Create a zero constant to be used as an operand of the synonymous // instruction. FindOrCreateZeroConstant(existing_synonym->type_id(), false); diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.h index dcfb938983..ccf4a88671 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_synonyms.h @@ -29,8 +29,6 @@ class FuzzerPassAddSynonyms : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddSynonyms() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.cpp index 453448ba2f..e2eaaa0a48 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.cpp @@ -28,9 +28,6 @@ FuzzerPassAddVectorShuffleInstructions::FuzzerPassAddVectorShuffleInstructions( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAddVectorShuffleInstructions:: - ~FuzzerPassAddVectorShuffleInstructions() = default; - void FuzzerPassAddVectorShuffleInstructions::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.h index 99b9f244c1..c5af374cd3 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_add_vector_shuffle_instructions.h @@ -28,8 +28,6 @@ class FuzzerPassAddVectorShuffleInstructions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAddVectorShuffleInstructions(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.cpp index 1d6d4347ff..3c4f3803d7 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.cpp @@ -28,8 +28,6 @@ FuzzerPassAdjustBranchWeights::FuzzerPassAdjustBranchWeights( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAdjustBranchWeights::~FuzzerPassAdjustBranchWeights() = default; - void FuzzerPassAdjustBranchWeights::Apply() { // For all OpBranchConditional instructions, // randomly applies the transformation. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.h index 5b2b33f1ca..de2f33d3b2 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_branch_weights.h @@ -30,8 +30,6 @@ class FuzzerPassAdjustBranchWeights : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAdjustBranchWeights(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.cpp index aa62d2f895..b38bd212c7 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.cpp @@ -26,8 +26,6 @@ FuzzerPassAdjustFunctionControls::FuzzerPassAdjustFunctionControls( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAdjustFunctionControls::~FuzzerPassAdjustFunctionControls() = default; - void FuzzerPassAdjustFunctionControls::Apply() { // Consider every function in the module. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.h index 5fdbe4321e..5ef32a180c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_function_controls.h @@ -28,8 +28,6 @@ class FuzzerPassAdjustFunctionControls : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAdjustFunctionControls() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.cpp index f7addffe1c..0f7cf037ec 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.cpp @@ -26,8 +26,6 @@ FuzzerPassAdjustLoopControls::FuzzerPassAdjustLoopControls( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAdjustLoopControls::~FuzzerPassAdjustLoopControls() = default; - void FuzzerPassAdjustLoopControls::Apply() { // Consider every merge instruction in the module (via looking through all // functions and blocks). diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.h index f133b2d19b..4ca670b780 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_loop_controls.h @@ -28,8 +28,6 @@ class FuzzerPassAdjustLoopControls : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAdjustLoopControls() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.cpp index 68f0ca7e44..778d43ff0e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.cpp @@ -27,9 +27,6 @@ FuzzerPassAdjustMemoryOperandsMasks::FuzzerPassAdjustMemoryOperandsMasks( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAdjustMemoryOperandsMasks::~FuzzerPassAdjustMemoryOperandsMasks() = - default; - void FuzzerPassAdjustMemoryOperandsMasks::Apply() { // Consider every block in every function. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.h index 699dcb5a1f..a068b8dd94 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_memory_operands_masks.h @@ -29,8 +29,6 @@ class FuzzerPassAdjustMemoryOperandsMasks : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAdjustMemoryOperandsMasks(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.cpp index 83b1854e16..d9b4e2939d 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.cpp @@ -26,9 +26,6 @@ FuzzerPassAdjustSelectionControls::FuzzerPassAdjustSelectionControls( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassAdjustSelectionControls::~FuzzerPassAdjustSelectionControls() = - default; - void FuzzerPassAdjustSelectionControls::Apply() { // Consider every merge instruction in the module (via looking through all // functions and blocks). diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.h index 910b40d6ba..6931f942c7 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_adjust_selection_controls.h @@ -28,8 +28,6 @@ class FuzzerPassAdjustSelectionControls : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassAdjustSelectionControls() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.cpp index 38553d2554..712083132c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.cpp @@ -32,8 +32,6 @@ FuzzerPassApplyIdSynonyms::FuzzerPassApplyIdSynonyms( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassApplyIdSynonyms::~FuzzerPassApplyIdSynonyms() = default; - void FuzzerPassApplyIdSynonyms::Apply() { // Compute a closure of data synonym facts, to enrich the pool of synonyms // that are available. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.h index 5deac105e9..b402b50924 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_apply_id_synonyms.h @@ -30,8 +30,6 @@ class FuzzerPassApplyIdSynonyms : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassApplyIdSynonyms() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.cpp index 584fa1a95b..1a174cf16b 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.cpp @@ -16,6 +16,7 @@ #include +#include "source/fuzz/available_instructions.h" #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/transformation_composite_construct.h" @@ -29,8 +30,6 @@ FuzzerPassConstructComposites::FuzzerPassConstructComposites( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassConstructComposites::~FuzzerPassConstructComposites() = default; - void FuzzerPassConstructComposites::Apply() { // Gather up the ids of all composite types, but skip block-/buffer // block-decorated struct types. @@ -44,12 +43,40 @@ void FuzzerPassConstructComposites::Apply() { } } + if (composite_type_ids.empty()) { + // There are no composite types, so this fuzzer pass cannot do anything. + return; + } + + AvailableInstructions available_composite_constituents( + GetIRContext(), + [this](opt::IRContext* ir_context, opt::Instruction* inst) -> bool { + if (!inst->result_id() || !inst->type_id()) { + return false; + } + + // If the id is irrelevant, we can use it since it will not + // participate in DataSynonym fact. Otherwise, we should be able + // to produce a synonym out of the id. + return GetTransformationContext()->GetFactManager()->IdIsIrrelevant( + inst->result_id()) || + fuzzerutil::CanMakeSynonymOf(ir_context, + *GetTransformationContext(), inst); + }); + ForEachInstructionWithInstructionDescriptor( - [this, &composite_type_ids]( - opt::Function* function, opt::BasicBlock* block, + [this, &available_composite_constituents, &composite_type_ids]( + opt::Function* /*unused*/, opt::BasicBlock* /*unused*/, opt::BasicBlock::iterator inst_it, const protobufs::InstructionDescriptor& instruction_descriptor) -> void { + // Randomly decide whether to try inserting a composite construction + // here. + if (!GetFuzzerContext()->ChoosePercentage( + GetFuzzerContext()->GetChanceOfConstructingComposite())) { + return; + } + // Check whether it is legitimate to insert a composite construction // before the instruction. if (!fuzzerutil::CanInsertOpcodeBeforeInstruction( @@ -57,36 +84,21 @@ void FuzzerPassConstructComposites::Apply() { return; } - // Randomly decide whether to try inserting an object copy here. - if (!GetFuzzerContext()->ChoosePercentage( - GetFuzzerContext()->GetChanceOfConstructingComposite())) { - return; - } - // For each instruction that is available at this program point (i.e. an // instruction that is global or whose definition strictly dominates the // program point) and suitable for making a synonym of, associate it // with the id of its result type. TypeIdToInstructions type_id_to_available_instructions; - auto available_instructions = FindAvailableInstructions( - function, block, inst_it, - [this](opt::IRContext* ir_context, opt::Instruction* inst) { - if (!inst->result_id() || !inst->type_id()) { - return false; - } - - // If the id is irrelevant, we can use it since it will not - // participate in DataSynonym fact. Otherwise, we should be able - // to produce a synonym out of the id. - return GetTransformationContext() - ->GetFactManager() - ->IdIsIrrelevant(inst->result_id()) || - fuzzerutil::CanMakeSynonymOf( - ir_context, *GetTransformationContext(), inst); - }); - for (auto instruction : available_instructions) { - RecordAvailableInstruction(instruction, - &type_id_to_available_instructions); + auto available_instructions = + available_composite_constituents.GetAvailableBeforeInstruction( + &*inst_it); + for (uint32_t available_instruction_index = 0; + available_instruction_index < available_instructions.size(); + available_instruction_index++) { + opt::Instruction* inst = + available_instructions[available_instruction_index]; + type_id_to_available_instructions[inst->type_id()].push_back( + inst->result_id()); } // At this point, |composite_type_ids| captures all the composite types @@ -94,68 +106,41 @@ void FuzzerPassConstructComposites::Apply() { // captures all the available result ids we might use, organized by // type. - // Now we try to find a composite that we can construct. We might not - // manage, if there is a paucity of available ingredients in the module - // (e.g. if our only available composite was a boolean vector and we had - // no instructions generating boolean result types available). - // - // If we succeed, |chosen_composite_type| will end up being non-zero, - // and |constructor_arguments| will end up giving us result ids suitable - // for constructing a composite of that type. Otherwise these variables - // will remain 0 and null respectively. - uint32_t chosen_composite_type = 0; + // Now we choose a composite type to construct, building it from + // available constituent components and using zero constants if suitable + // components are not available. + std::vector constructor_arguments; + uint32_t chosen_composite_type = + composite_type_ids[GetFuzzerContext()->RandomIndex( + composite_type_ids)]; - // Initially, all composite type ids are available for us to try. Keep - // trying until we run out of options. - auto composites_to_try_constructing = composite_type_ids; - while (!composites_to_try_constructing.empty()) { - // Remove a composite type from the composite types left for us to - // try. - auto next_composite_to_try_constructing = - GetFuzzerContext()->RemoveAtRandomIndex( - &composites_to_try_constructing); - - // Now try to construct a composite of this type, using an appropriate - // helper method depending on the kind of composite type. - auto composite_type_inst = GetIRContext()->get_def_use_mgr()->GetDef( - next_composite_to_try_constructing); - switch (composite_type_inst->opcode()) { - case SpvOpTypeArray: - constructor_arguments = FindComponentsToConstructArray( - *composite_type_inst, type_id_to_available_instructions); - break; - case SpvOpTypeMatrix: - constructor_arguments = FindComponentsToConstructMatrix( - *composite_type_inst, type_id_to_available_instructions); - break; - case SpvOpTypeStruct: - constructor_arguments = FindComponentsToConstructStruct( - *composite_type_inst, type_id_to_available_instructions); - break; - case SpvOpTypeVector: - constructor_arguments = FindComponentsToConstructVector( - *composite_type_inst, type_id_to_available_instructions); - break; - default: - assert(false && - "The space of possible composite types should be covered " - "by the above cases."); - break; - } - if (!constructor_arguments.empty()) { - // We succeeded! Note the composite type we finally settled on, and - // exit from the loop. - chosen_composite_type = next_composite_to_try_constructing; + // Construct a composite of this type, using an appropriate helper + // method depending on the kind of composite type. + auto composite_type_inst = + GetIRContext()->get_def_use_mgr()->GetDef(chosen_composite_type); + switch (composite_type_inst->opcode()) { + case SpvOpTypeArray: + constructor_arguments = FindComponentsToConstructArray( + *composite_type_inst, type_id_to_available_instructions); + break; + case SpvOpTypeMatrix: + constructor_arguments = FindComponentsToConstructMatrix( + *composite_type_inst, type_id_to_available_instructions); + break; + case SpvOpTypeStruct: + constructor_arguments = FindComponentsToConstructStruct( + *composite_type_inst, type_id_to_available_instructions); + break; + case SpvOpTypeVector: + constructor_arguments = FindComponentsToConstructVector( + *composite_type_inst, type_id_to_available_instructions); + break; + default: + assert(false && + "The space of possible composite types should be covered " + "by the above cases."); break; - } - } - - if (!chosen_composite_type) { - // We did not manage to make a composite; return 0 to indicate that no - // instructions were added. - assert(constructor_arguments.empty()); - return; } assert(!constructor_arguments.empty()); @@ -166,15 +151,6 @@ void FuzzerPassConstructComposites::Apply() { }); } -void FuzzerPassConstructComposites::RecordAvailableInstruction( - opt::Instruction* inst, - TypeIdToInstructions* type_id_to_available_instructions) { - if (type_id_to_available_instructions->count(inst->type_id()) == 0) { - (*type_id_to_available_instructions)[inst->type_id()] = {}; - } - type_id_to_available_instructions->at(inst->type_id()).push_back(inst); -} - std::vector FuzzerPassConstructComposites::FindComponentsToConstructArray( const opt::Instruction& array_type_instruction, @@ -190,13 +166,6 @@ FuzzerPassConstructComposites::FindComponentsToConstructArray( auto available_instructions = type_id_to_available_instructions.find(element_type_id); - if (available_instructions == type_id_to_available_instructions.cend()) { - // If there are not any instructions available that compute the element type - // of the array then we are not in a position to construct a composite with - // this array type. - return {}; - } - uint32_t array_length = GetIRContext() ->get_def_use_mgr() @@ -205,10 +174,14 @@ FuzzerPassConstructComposites::FindComponentsToConstructArray( std::vector result; for (uint32_t index = 0; index < array_length; index++) { - result.push_back(available_instructions - ->second[GetFuzzerContext()->RandomIndex( - available_instructions->second)] - ->result_id()); + if (available_instructions == type_id_to_available_instructions.cend()) { + // No suitable instructions are available, so use a zero constant + result.push_back(FindOrCreateZeroConstant(element_type_id, true)); + } else { + result.push_back( + available_instructions->second[GetFuzzerContext()->RandomIndex( + available_instructions->second)]); + } } return result; } @@ -228,19 +201,17 @@ FuzzerPassConstructComposites::FindComponentsToConstructMatrix( auto available_instructions = type_id_to_available_instructions.find(element_type_id); - if (available_instructions == type_id_to_available_instructions.cend()) { - // If there are not any instructions available that compute the element type - // of the matrix then we are not in a position to construct a composite with - // this matrix type. - return {}; - } std::vector result; for (uint32_t index = 0; index < matrix_type_instruction.GetSingleWordInOperand(1); index++) { - result.push_back(available_instructions - ->second[GetFuzzerContext()->RandomIndex( - available_instructions->second)] - ->result_id()); + if (available_instructions == type_id_to_available_instructions.cend()) { + // No suitable components are available, so use a zero constant. + result.push_back(FindOrCreateZeroConstant(element_type_id, true)); + } else { + result.push_back( + available_instructions->second[GetFuzzerContext()->RandomIndex( + available_instructions->second)]); + } } return result; } @@ -263,14 +234,14 @@ FuzzerPassConstructComposites::FindComponentsToConstructStruct( auto available_instructions = type_id_to_available_instructions.find(element_type_id); if (available_instructions == type_id_to_available_instructions.cend()) { - // If there are no such instructions, we cannot construct a composite of - // this struct type. - return {}; + // No suitable component is available for this element type, so use a zero + // constant. + result.push_back(FindOrCreateZeroConstant(element_type_id, true)); + } else { + result.push_back( + available_instructions->second[GetFuzzerContext()->RandomIndex( + available_instructions->second)]); } - result.push_back(available_instructions - ->second[GetFuzzerContext()->RandomIndex( - available_instructions->second)] - ->result_id()); } return result; } @@ -325,12 +296,13 @@ FuzzerPassConstructComposites::FindComponentsToConstructVector( // (otherwise there will not be space left for a vec3). uint32_t vector_slots_used = 0; - // The instructions we will use to construct the vector, in no particular - // order at this stage. - std::vector instructions_to_use; + + // The instructions result ids we will use to construct the vector, in no + // particular order at this stage. + std::vector result; while (vector_slots_used < element_count) { - std::vector instructions_to_choose_from; + std::vector instructions_to_choose_from; for (auto& entry : smaller_vector_type_id_to_width) { if (entry.second > std::min(element_count - 1, element_count - vector_slots_used)) { @@ -345,19 +317,16 @@ FuzzerPassConstructComposites::FindComponentsToConstructVector( available_instructions->second.begin(), available_instructions->second.end()); } - if (instructions_to_choose_from.empty()) { - // We may get unlucky and find that there are not any instructions to - // choose from. In this case we give up constructing a composite of this - // vector type. It might be that we could construct the composite in - // another manner, so we could opt to retry a few times here, but it is - // simpler to just give up on the basis that this will not happen - // frequently. - return {}; - } - auto instruction_to_use = - instructions_to_choose_from[GetFuzzerContext()->RandomIndex( - instructions_to_choose_from)]; - instructions_to_use.push_back(instruction_to_use); + // If there are no instructions to choose from then use a zero constant, + // otherwise select one of the instructions at random. + uint32_t id_of_instruction_to_use = + instructions_to_choose_from.empty() + ? FindOrCreateZeroConstant(element_type_id, true) + : instructions_to_choose_from[GetFuzzerContext()->RandomIndex( + instructions_to_choose_from)]; + opt::Instruction* instruction_to_use = + GetIRContext()->get_def_use_mgr()->GetDef(id_of_instruction_to_use); + result.push_back(instruction_to_use->result_id()); auto chosen_type = GetIRContext()->get_type_mgr()->GetType(instruction_to_use->type_id()); if (chosen_type->AsVector()) { @@ -373,14 +342,7 @@ FuzzerPassConstructComposites::FindComponentsToConstructVector( } assert(vector_slots_used == element_count); - std::vector result; - std::vector operands; - while (!instructions_to_use.empty()) { - auto index = GetFuzzerContext()->RandomIndex(instructions_to_use); - result.push_back(instructions_to_use[index]->result_id()); - instructions_to_use.erase(instructions_to_use.begin() + index); - } - assert(result.size() > 1); + GetFuzzerContext()->Shuffle(&result); return result; } diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.h index c140bdede9..333ac93160 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_construct_composites.h @@ -15,7 +15,7 @@ #ifndef SOURCE_FUZZ_FUZZER_PASS_CONSTRUCT_COMPOSITES_H_ #define SOURCE_FUZZ_FUZZER_PASS_CONSTRUCT_COMPOSITES_H_ -#include +#include #include #include "source/fuzz/fuzzer_pass.h" @@ -31,23 +31,12 @@ class FuzzerPassConstructComposites : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassConstructComposites(); - void Apply() override; private: - // Used to map a type id to relevant instructions whose result type matches - // the type id. - typedef std::map> - TypeIdToInstructions; - - // Considers all instructions that are available at |inst| - instructions - // whose results could be packed into a composite - and updates - // |type_id_to_available_instructions| so that each such instruction is - // associated with its the id of its result type. - void RecordAvailableInstruction( - opt::Instruction* inst, - TypeIdToInstructions* type_id_to_available_instructions); + // Used to map a type id to the ids of relevant instructions of the type. + using TypeIdToInstructions = + std::unordered_map>; // Requires that |array_type_instruction| has opcode OpTypeArray. // Attempts to find suitable instruction result ids from the values of diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.cpp index 9f7bbd63f5..09b5368a4c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.cpp @@ -28,8 +28,6 @@ FuzzerPassCopyObjects::FuzzerPassCopyObjects( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassCopyObjects::~FuzzerPassCopyObjects() = default; - void FuzzerPassCopyObjects::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.h index 8de382e7f9..461cd97927 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_copy_objects.h @@ -28,8 +28,6 @@ class FuzzerPassCopyObjects : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassCopyObjects(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.cpp index 4cd4804531..2f2ed50a72 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.cpp @@ -50,8 +50,6 @@ FuzzerPassDonateModules::FuzzerPassDonateModules( transformations), donor_suppliers_(donor_suppliers) {} -FuzzerPassDonateModules::~FuzzerPassDonateModules() = default; - void FuzzerPassDonateModules::Apply() { // If there are no donor suppliers, this fuzzer pass is a no-op. if (donor_suppliers_.empty()) { @@ -1202,11 +1200,14 @@ bool FuzzerPassDonateModules::MaybeAddLivesafeFunction( false); } - // Add the function in a livesafe manner. - ApplyTransformation(TransformationAddFunction( + // Try to add the function in a livesafe manner. This may fail due to edge + // cases, e.g. where adding loop limiters changes dominance such that the + // module becomes invalid. It would be ideal to handle all such edge cases, + // but as they are rare it is more pragmatic to bail out of making the + // function livesafe if the transformation's precondition fails to hold. + return MaybeApplyTransformation(TransformationAddFunction( donated_instructions, loop_limiter_variable_id, loop_limit, loop_limiters, kill_unreachable_return_value_id, access_chain_clamping_info)); - return true; } } // namespace fuzz diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.h index 0424cece21..1581a8a4a7 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_donate_modules.h @@ -33,8 +33,6 @@ class FuzzerPassDonateModules : public FuzzerPass { protobufs::TransformationSequence* transformations, const std::vector& donor_suppliers); - ~FuzzerPassDonateModules(); - void Apply() override; // Donates the global declarations and functions of |donor_ir_context| into diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.cpp index 1651a9d5dc..e08d65b121 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.cpp @@ -29,9 +29,6 @@ FuzzerPassDuplicateRegionsWithSelections:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassDuplicateRegionsWithSelections:: - ~FuzzerPassDuplicateRegionsWithSelections() = default; - void FuzzerPassDuplicateRegionsWithSelections::Apply() { // Iterate over all of the functions in the module. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.h index 3fae69836a..7cb1197db0 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_duplicate_regions_with_selections.h @@ -31,8 +31,6 @@ class FuzzerPassDuplicateRegionsWithSelections : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassDuplicateRegionsWithSelections() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.cpp index 1416fe0b67..e25dcbc3eb 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.cpp @@ -28,8 +28,6 @@ FuzzerPassExpandVectorReductions::FuzzerPassExpandVectorReductions( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassExpandVectorReductions::~FuzzerPassExpandVectorReductions() = default; - void FuzzerPassExpandVectorReductions::Apply() { for (auto& function : *GetIRContext()->module()) { for (auto& block : function) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.h index ae3238b638..ed0225df1d 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_expand_vector_reductions.h @@ -30,8 +30,6 @@ class FuzzerPassExpandVectorReductions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassExpandVectorReductions(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.cpp index 1e21aa5062..84da7a749e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.cpp @@ -30,9 +30,6 @@ FuzzerPassFlattenConditionalBranches::FuzzerPassFlattenConditionalBranches( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassFlattenConditionalBranches::~FuzzerPassFlattenConditionalBranches() = - default; - void FuzzerPassFlattenConditionalBranches::Apply() { for (auto& function : *GetIRContext()->module()) { // Get all the selection headers that we want to flatten. We need to collect diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.h index 76f7782cff..e7d7dc36ab 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_flatten_conditional_branches.h @@ -27,8 +27,6 @@ class FuzzerPassFlattenConditionalBranches : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassFlattenConditionalBranches() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.cpp index 90160d83ae..405afd8b16 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.cpp @@ -29,8 +29,6 @@ FuzzerPassInlineFunctions::FuzzerPassInlineFunctions( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassInlineFunctions::~FuzzerPassInlineFunctions() = default; - void FuzzerPassInlineFunctions::Apply() { // |function_call_instructions| are the instructions that will be inlined. // First, they will be collected and then do the inlining in another loop. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.h index 37295d1c2e..a6ed8cad55 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_inline_functions.h @@ -30,8 +30,6 @@ class FuzzerPassInlineFunctions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassInlineFunctions() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.cpp index 0e40b4963c..675cae9ade 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.cpp @@ -31,10 +31,10 @@ FuzzerPassInterchangeSignednessOfIntegerOperands:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassInterchangeSignednessOfIntegerOperands:: - ~FuzzerPassInterchangeSignednessOfIntegerOperands() = default; - void FuzzerPassInterchangeSignednessOfIntegerOperands::Apply() { + assert(!GetFuzzerContext()->IsWgslCompatible() && + "Cannot interchange signedness in WGSL"); + // Make vector keeping track of all the uses we want to replace. // This is a vector of pairs, where the first element is an id use descriptor // identifying the use of a constant id and the second is the id that should diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.h index 06882f47dc..11b8fb6e8b 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_signedness_of_integer_operands.h @@ -34,8 +34,6 @@ class FuzzerPassInterchangeSignednessOfIntegerOperands : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassInterchangeSignednessOfIntegerOperands() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.cpp index 20575e1157..5d0a222377 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.cpp @@ -29,9 +29,6 @@ FuzzerPassInterchangeZeroLikeConstants::FuzzerPassInterchangeZeroLikeConstants( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassInterchangeZeroLikeConstants:: - ~FuzzerPassInterchangeZeroLikeConstants() = default; - uint32_t FuzzerPassInterchangeZeroLikeConstants::FindOrCreateToggledConstant( opt::Instruction* declaration) { // |declaration| must not be a specialization constant because we do not know diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.h index ef0f765585..012f03d3b5 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_interchange_zero_like_constants.h @@ -35,8 +35,6 @@ class FuzzerPassInterchangeZeroLikeConstants : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassInterchangeZeroLikeConstants() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.cpp index de4ff1de37..542748e95d 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.cpp @@ -28,9 +28,6 @@ FuzzerPassInvertComparisonOperators::FuzzerPassInvertComparisonOperators( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassInvertComparisonOperators::~FuzzerPassInvertComparisonOperators() = - default; - void FuzzerPassInvertComparisonOperators::Apply() { GetIRContext()->module()->ForEachInst([this](const opt::Instruction* inst) { if (!TransformationInvertComparisonOperator::IsInversionSupported( diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.h index 9c80bbbb0b..5f015c28dc 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_invert_comparison_operators.h @@ -29,8 +29,6 @@ class FuzzerPassInvertComparisonOperators : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassInvertComparisonOperators() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.cpp index f4f2a80269..7bf07a4952 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.cpp @@ -28,9 +28,6 @@ FuzzerPassMakeVectorOperationsDynamic::FuzzerPassMakeVectorOperationsDynamic( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassMakeVectorOperationsDynamic:: - ~FuzzerPassMakeVectorOperationsDynamic() = default; - void FuzzerPassMakeVectorOperationsDynamic::Apply() { for (auto& function : *GetIRContext()->module()) { for (auto& block : function) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.h index dd51cde73a..da27825a41 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_make_vector_operations_dynamic.h @@ -29,8 +29,6 @@ class FuzzerPassMakeVectorOperationsDynamic : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassMakeVectorOperationsDynamic() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.cpp index e66fc44475..a8ec784c9c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.cpp @@ -28,8 +28,6 @@ FuzzerPassMergeBlocks::FuzzerPassMergeBlocks( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassMergeBlocks::~FuzzerPassMergeBlocks() = default; - void FuzzerPassMergeBlocks::Apply() { // First we populate a sequence of transformations that we might consider // applying. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.h index 1a6c2c2717..66cf4c64c1 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_blocks.h @@ -28,8 +28,6 @@ class FuzzerPassMergeBlocks : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassMergeBlocks(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.cpp index fc9c74d08a..ee82eca5e3 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.cpp @@ -30,8 +30,6 @@ FuzzerPassMergeFunctionReturns::FuzzerPassMergeFunctionReturns( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassMergeFunctionReturns::~FuzzerPassMergeFunctionReturns() = default; - void FuzzerPassMergeFunctionReturns::Apply() { // The pass might add new functions to the module (due to wrapping early // terminator instructions in function calls), so we record the functions that @@ -174,8 +172,9 @@ void FuzzerPassMergeFunctionReturns::Apply() { } // Get the ids needed by the transformation. - uint32_t outer_header_id = GetFuzzerContext()->GetFreshId(); - uint32_t outer_return_id = GetFuzzerContext()->GetFreshId(); + const uint32_t outer_header_id = GetFuzzerContext()->GetFreshId(); + const uint32_t unreachable_continue_id = GetFuzzerContext()->GetFreshId(); + const uint32_t outer_return_id = GetFuzzerContext()->GetFreshId(); bool function_is_void = GetIRContext()->get_type_mgr()->GetType(function->type_id())->AsVoid(); @@ -211,8 +210,8 @@ void FuzzerPassMergeFunctionReturns::Apply() { // Apply the transformation if it is applicable (it could be inapplicable if // adding new predecessors to merge blocks breaks dominance rules). MaybeApplyTransformation(TransformationMergeFunctionReturns( - function->result_id(), outer_header_id, outer_return_id, return_val_id, - returnable_val_id, merge_blocks_info)); + function->result_id(), outer_header_id, unreachable_continue_id, + outer_return_id, return_val_id, returnable_val_id, merge_blocks_info)); } } diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.h index 3b5a668f39..ddd2c9dc38 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_merge_function_returns.h @@ -33,8 +33,6 @@ class FuzzerPassMergeFunctionReturns : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassMergeFunctionReturns(); - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.cpp index 89f5f5c068..f021a978ac 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.cpp @@ -28,8 +28,6 @@ FuzzerPassMutatePointers::FuzzerPassMutatePointers( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassMutatePointers::~FuzzerPassMutatePointers() = default; - void FuzzerPassMutatePointers::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.h index f77523efbe..5ef6a2ab4a 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_mutate_pointers.h @@ -28,8 +28,6 @@ class FuzzerPassMutatePointers : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassMutatePointers() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.cpp index d87662eee2..32318e8965 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.cpp @@ -34,8 +34,6 @@ FuzzerPassObfuscateConstants::FuzzerPassObfuscateConstants( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassObfuscateConstants::~FuzzerPassObfuscateConstants() = default; - void FuzzerPassObfuscateConstants::ObfuscateBoolConstantViaConstantPair( uint32_t depth, const protobufs::IdUseDescriptor& bool_constant_use, const std::vector& greater_than_opcodes, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.h index d48b37f6e0..82b1092c70 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_obfuscate_constants.h @@ -32,8 +32,6 @@ class FuzzerPassObfuscateConstants : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassObfuscateConstants() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.cpp index 4210125650..bfde61f7c3 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.cpp @@ -31,8 +31,6 @@ FuzzerPassOutlineFunctions::FuzzerPassOutlineFunctions( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassOutlineFunctions::~FuzzerPassOutlineFunctions() = default; - void FuzzerPassOutlineFunctions::Apply() { std::vector original_functions; for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.h index 02022aa7ce..45e52ff44e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_outline_functions.h @@ -29,8 +29,6 @@ class FuzzerPassOutlineFunctions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassOutlineFunctions(); - void Apply() override; // Returns a block suitable to be an entry block for a region that can be diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.cpp index 24c16fbbb3..769c49f069 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.cpp @@ -26,8 +26,6 @@ FuzzerPassPermuteBlocks::FuzzerPassPermuteBlocks( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPermuteBlocks::~FuzzerPassPermuteBlocks() = default; - void FuzzerPassPermuteBlocks::Apply() { // For now we do something very simple: we randomly decide whether to move a // block, and for each block that we do move, we push it down as far as we diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.h index e5a672cb3d..e40178e656 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_blocks.h @@ -29,8 +29,6 @@ class FuzzerPassPermuteBlocks : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPermuteBlocks() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.cpp index de6b03f39f..9a61bea0f9 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.cpp @@ -32,9 +32,6 @@ FuzzerPassPermuteFunctionParameters::FuzzerPassPermuteFunctionParameters( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPermuteFunctionParameters::~FuzzerPassPermuteFunctionParameters() = - default; - void FuzzerPassPermuteFunctionParameters::Apply() { for (const auto& function : *GetIRContext()->module()) { uint32_t function_id = function.result_id(); diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.h index bc1031cbba..a4bf2ca52d 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_parameters.h @@ -34,8 +34,6 @@ class FuzzerPassPermuteFunctionParameters : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPermuteFunctionParameters() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_variables.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_variables.cpp new file mode 100644 index 0000000000..a4e19e3b19 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_variables.cpp @@ -0,0 +1,73 @@ +// Copyright (c) 2021 Mostafa Ashraf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/fuzzer_pass_permute_function_variables.h" + +#include +#include +#include + +#include "source/fuzz/fuzzer_context.h" +#include "source/fuzz/fuzzer_util.h" +#include "source/fuzz/instruction_descriptor.h" +#include "source/fuzz/transformation_swap_function_variables.h" + +namespace spvtools { +namespace fuzz { + +FuzzerPassPermuteFunctionVariables::FuzzerPassPermuteFunctionVariables( + opt::IRContext* ir_context, TransformationContext* transformation_context, + FuzzerContext* fuzzer_context, + protobufs::TransformationSequence* transformations) + : FuzzerPass(ir_context, transformation_context, fuzzer_context, + transformations) {} // Here we call parent constructor. + +void FuzzerPassPermuteFunctionVariables::Apply() { + // Permuting OpVariable instructions in each function. + for (auto& function : *GetIRContext()->module()) { + if (!GetFuzzerContext()->ChoosePercentage( + GetFuzzerContext()->GetChanceOfPermutingFunctionVariables())) { + continue; + } + + auto first_block = function.entry().get(); + + std::vector variables; + for (auto& instruction : *first_block) { + if (instruction.opcode() == SpvOpVariable) { + variables.push_back(&instruction); + } + } + if (variables.size() <= 1) { + continue; + } + do { + uint32_t instruction_1_index = GetFuzzerContext()->RandomIndex(variables); + uint32_t instruction_2_index = GetFuzzerContext()->RandomIndex(variables); + + if (instruction_1_index != instruction_2_index) { + ApplyTransformation(TransformationSwapFunctionVariables( + variables[instruction_1_index]->result_id(), + variables[instruction_2_index]->result_id())); + } + + } while (GetFuzzerContext()->ChoosePercentage( + GetFuzzerContext() + ->GetChanceOfSwappingAnotherPairOfFunctionVariables()) && + variables.size() > 2); + } +} + +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_variables.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_variables.h new file mode 100644 index 0000000000..47f1de281f --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_function_variables.h @@ -0,0 +1,37 @@ +// Copyright (c) 2021 Mostafa Ashraf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_FUZZ_FUZZER_PASS_PERMUTE_FUNCTION_VARIABLES_H_ +#define SOURCE_FUZZ_FUZZER_PASS_PERMUTE_FUNCTION_VARIABLES_H_ + +#include "source/fuzz/fuzzer_pass.h" + +namespace spvtools { +namespace fuzz { + +// This fuzzer pass permutes variables in functions in the module. +class FuzzerPassPermuteFunctionVariables : public FuzzerPass { + public: + FuzzerPassPermuteFunctionVariables( + opt::IRContext* ir_context, TransformationContext* transformation_context, + FuzzerContext* fuzzer_context, + protobufs::TransformationSequence* transformations); + + void Apply() override; +}; + +} // namespace fuzz +} // namespace spvtools + +#endif // SOURCE_FUZZ_FUZZER_PASS_PERMUTE_FUNCTION_VARIABLES_H_ diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.cpp index 6867053c68..f17e018778 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.cpp @@ -29,8 +29,6 @@ FuzzerPassPermuteInstructions::FuzzerPassPermuteInstructions( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPermuteInstructions::~FuzzerPassPermuteInstructions() = default; - void FuzzerPassPermuteInstructions::Apply() { // We are iterating over all instructions in all basic blocks. for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.h index e02ddfae03..027101dd44 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_instructions.h @@ -29,8 +29,6 @@ class FuzzerPassPermuteInstructions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPermuteInstructions() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.cpp index c379c535c4..f2cc52314e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.cpp @@ -32,8 +32,6 @@ FuzzerPassPermutePhiOperands::FuzzerPassPermutePhiOperands( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPermutePhiOperands::~FuzzerPassPermutePhiOperands() = default; - void FuzzerPassPermutePhiOperands::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* /*unused*/, opt::BasicBlock* /*unused*/, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.h index 974c2c1e71..7999956288 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_permute_phi_operands.h @@ -29,8 +29,6 @@ class FuzzerPassPermutePhiOperands : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPermutePhiOperands() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.cpp index 7a115aec2d..89e14370f5 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.cpp @@ -27,15 +27,11 @@ FuzzerPassPropagateInstructionsDown::FuzzerPassPropagateInstructionsDown( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPropagateInstructionsDown::~FuzzerPassPropagateInstructionsDown() = - default; - void FuzzerPassPropagateInstructionsDown::Apply() { for (const auto& function : *GetIRContext()->module()) { std::vector reachable_blocks; for (const auto& block : function) { - if (GetIRContext()->GetDominatorAnalysis(&function)->IsReachable( - &block)) { + if (GetIRContext()->IsReachable(block)) { reachable_blocks.push_back(&block); } } diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.h index 536bf000b2..a2a0aac828 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_down.h @@ -28,8 +28,6 @@ class FuzzerPassPropagateInstructionsDown : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPropagateInstructionsDown() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.cpp index 16ec680e2f..8cd7437bdb 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.cpp @@ -29,9 +29,6 @@ FuzzerPassPropagateInstructionsUp::FuzzerPassPropagateInstructionsUp( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPropagateInstructionsUp::~FuzzerPassPropagateInstructionsUp() = - default; - void FuzzerPassPropagateInstructionsUp::Apply() { for (const auto& function : *GetIRContext()->module()) { for (const auto& block : function) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.h index d915b31eb5..b89be48dd5 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_propagate_instructions_up.h @@ -29,8 +29,6 @@ class FuzzerPassPropagateInstructionsUp : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPropagateInstructionsUp() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.cpp index 8d9acaa015..6aebac6687 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.cpp @@ -28,9 +28,6 @@ FuzzerPassPushIdsThroughVariables::FuzzerPassPushIdsThroughVariables( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassPushIdsThroughVariables::~FuzzerPassPushIdsThroughVariables() = - default; - void FuzzerPassPushIdsThroughVariables::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* function, opt::BasicBlock* block, @@ -50,7 +47,7 @@ void FuzzerPassPushIdsThroughVariables::Apply() { // The block containing the instruction we are going to insert before // must be reachable. - if (!fuzzerutil::BlockIsReachableInItsFunction(GetIRContext(), block)) { + if (!GetIRContext()->IsReachable(*block)) { return; } @@ -72,6 +69,12 @@ void FuzzerPassPushIdsThroughVariables::Apply() { auto basic_type_ids_and_pointers = GetAvailableBasicTypesAndPointers(variable_storage_class); auto& basic_types = basic_type_ids_and_pointers.first; + + // There must be at least some basic types. + if (basic_types.empty()) { + return; + } + uint32_t basic_type_id = basic_types[GetFuzzerContext()->RandomIndex(basic_types)]; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.h index 3ad5404289..53008ee223 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_push_ids_through_variables.h @@ -30,8 +30,6 @@ class FuzzerPassPushIdsThroughVariables : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassPushIdsThroughVariables() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.cpp index 139dc6e2ff..8a83d3bc51 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.cpp @@ -33,9 +33,6 @@ FuzzerPassReplaceAddsSubsMulsWithCarryingExtended:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceAddsSubsMulsWithCarryingExtended:: - ~FuzzerPassReplaceAddsSubsMulsWithCarryingExtended() = default; - void FuzzerPassReplaceAddsSubsMulsWithCarryingExtended::Apply() { std::vector instructions_for_transformation; for (auto& function : *GetIRContext()->module()) { diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.h index dd39e6b061..0e29a6c6b0 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_adds_subs_muls_with_carrying_extended.h @@ -31,8 +31,6 @@ class FuzzerPassReplaceAddsSubsMulsWithCarryingExtended : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceAddsSubsMulsWithCarryingExtended() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.cpp index e6bebead1c..a516f3d45b 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.cpp @@ -32,9 +32,6 @@ FuzzerPassReplaceBranchesFromDeadBlocksWithExits:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceBranchesFromDeadBlocksWithExits:: - ~FuzzerPassReplaceBranchesFromDeadBlocksWithExits() = default; - void FuzzerPassReplaceBranchesFromDeadBlocksWithExits::Apply() { // OpKill can only be used as a terminator in a function that is guaranteed // to be executed with the Fragment execution model. We conservatively only diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.h index 62164b320e..ab7e00e5c5 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_branches_from_dead_blocks_with_exits.h @@ -30,8 +30,6 @@ class FuzzerPassReplaceBranchesFromDeadBlocksWithExits : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceBranchesFromDeadBlocksWithExits() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.cpp index 6847146666..f17339a9c8 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.cpp @@ -30,9 +30,6 @@ FuzzerPassReplaceCopyMemoriesWithLoadsStores:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceCopyMemoriesWithLoadsStores:: - ~FuzzerPassReplaceCopyMemoriesWithLoadsStores() = default; - void FuzzerPassReplaceCopyMemoriesWithLoadsStores::Apply() { GetIRContext()->module()->ForEachInst([this](opt::Instruction* instruction) { // Randomly decide whether to replace the OpCopyMemory. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.h index 9c24ac7352..cffe1cb92c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_memories_with_loads_stores.h @@ -30,8 +30,6 @@ class FuzzerPassReplaceCopyMemoriesWithLoadsStores : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceCopyMemoriesWithLoadsStores() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.cpp index e372924594..24f2255b74 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.cpp @@ -30,9 +30,6 @@ FuzzerPassReplaceCopyObjectsWithStoresLoads:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceCopyObjectsWithStoresLoads:: - ~FuzzerPassReplaceCopyObjectsWithStoresLoads() = default; - void FuzzerPassReplaceCopyObjectsWithStoresLoads::Apply() { GetIRContext()->module()->ForEachInst([this](opt::Instruction* instruction) { // Randomly decide whether to replace OpCopyObject. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.h index ae03a4501d..e7b11ce107 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_copy_objects_with_stores_loads.h @@ -30,8 +30,6 @@ class FuzzerPassReplaceCopyObjectsWithStoresLoads : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceCopyObjectsWithStoresLoads() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.cpp index 432addbc9d..7e9d7baaa1 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.cpp @@ -31,8 +31,6 @@ FuzzerPassReplaceIrrelevantIds::FuzzerPassReplaceIrrelevantIds( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceIrrelevantIds::~FuzzerPassReplaceIrrelevantIds() = default; - void FuzzerPassReplaceIrrelevantIds::Apply() { // Keep track of the irrelevant ids. This includes all the ids that are // irrelevant according to the fact manager and that are still present in the diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.h index ab3f01d145..1dc6b5d386 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_irrelevant_ids.h @@ -30,8 +30,6 @@ class FuzzerPassReplaceIrrelevantIds : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceIrrelevantIds(); - void Apply() override; }; } // namespace fuzz diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.cpp index c3e65789ec..0890c2fe70 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.cpp @@ -30,9 +30,6 @@ FuzzerPassReplaceLinearAlgebraInstructions:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceLinearAlgebraInstructions:: - ~FuzzerPassReplaceLinearAlgebraInstructions() = default; - void FuzzerPassReplaceLinearAlgebraInstructions::Apply() { // For each instruction, checks whether it is a linear algebra instruction. In // this case, the transformation is randomly applied. diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.h index 2c6126cd16..5d2f204287 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_linear_algebra_instructions.h @@ -29,8 +29,6 @@ class FuzzerPassReplaceLinearAlgebraInstructions : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceLinearAlgebraInstructions(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.cpp index 7690ac41a1..f2cf80fae4 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.cpp @@ -31,9 +31,6 @@ FuzzerPassReplaceLoadsStoresWithCopyMemories:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceLoadsStoresWithCopyMemories:: - ~FuzzerPassReplaceLoadsStoresWithCopyMemories() = default; - void FuzzerPassReplaceLoadsStoresWithCopyMemories::Apply() { // We look for matching pairs of instructions OpLoad and // OpStore within the same block. Potential instructions OpLoad to be matched diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.h index 67871db252..f30fc2b77f 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_loads_stores_with_copy_memories.h @@ -30,8 +30,6 @@ class FuzzerPassReplaceLoadsStoresWithCopyMemories : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceLoadsStoresWithCopyMemories() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.cpp index 433cf744b9..b0a3d57c60 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.cpp @@ -28,9 +28,6 @@ FuzzerPassReplaceOpPhiIdsFromDeadPredecessors:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceOpPhiIdsFromDeadPredecessors:: - ~FuzzerPassReplaceOpPhiIdsFromDeadPredecessors() = default; - void FuzzerPassReplaceOpPhiIdsFromDeadPredecessors::Apply() { // Keep a vector of the transformations to apply. std::vector transformations; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.h index 972c5f9da5..a2bc1886a9 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opphi_ids_from_dead_predecessors.h @@ -29,8 +29,6 @@ class FuzzerPassReplaceOpPhiIdsFromDeadPredecessors : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceOpPhiIdsFromDeadPredecessors(); - void Apply() override; }; } // namespace fuzz diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.cpp index c3db0ef14a..10bb90adbd 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.cpp @@ -31,9 +31,6 @@ FuzzerPassReplaceOpSelectsWithConditionalBranches:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceOpSelectsWithConditionalBranches:: - ~FuzzerPassReplaceOpSelectsWithConditionalBranches() = default; - void FuzzerPassReplaceOpSelectsWithConditionalBranches::Apply() { // Keep track of the instructions that we want to replace. We need to collect // them in a vector, since it's not safe to modify the module while iterating diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.h index 04c6cc6d4a..ec743890eb 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_opselects_with_conditional_branches.h @@ -29,8 +29,6 @@ class FuzzerPassReplaceOpSelectsWithConditionalBranches : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceOpSelectsWithConditionalBranches() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.cpp index 6b3a63baf5..5c256bb057 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.cpp @@ -31,9 +31,6 @@ FuzzerPassReplaceParameterWithGlobal::FuzzerPassReplaceParameterWithGlobal( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceParameterWithGlobal::~FuzzerPassReplaceParameterWithGlobal() = - default; - void FuzzerPassReplaceParameterWithGlobal::Apply() { for (const auto& function : *GetIRContext()->module()) { if (fuzzerutil::FunctionIsEntryPoint(GetIRContext(), diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.h index 25011bdca0..2ae494696b 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_parameter_with_global.h @@ -29,8 +29,6 @@ class FuzzerPassReplaceParameterWithGlobal : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceParameterWithGlobal() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.cpp index 0e0610f743..c045e19f7c 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.cpp @@ -31,9 +31,6 @@ FuzzerPassReplaceParamsWithStruct::FuzzerPassReplaceParamsWithStruct( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassReplaceParamsWithStruct::~FuzzerPassReplaceParamsWithStruct() = - default; - void FuzzerPassReplaceParamsWithStruct::Apply() { for (const auto& function : *GetIRContext()->module()) { auto params = diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.h index ed1aa6b5f5..f17f520713 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_replace_params_with_struct.h @@ -29,8 +29,6 @@ class FuzzerPassReplaceParamsWithStruct : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassReplaceParamsWithStruct() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.cpp index 481cd96070..7b493559bc 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.cpp @@ -29,8 +29,6 @@ FuzzerPassSplitBlocks::FuzzerPassSplitBlocks( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassSplitBlocks::~FuzzerPassSplitBlocks() = default; - void FuzzerPassSplitBlocks::Apply() { // Gather up pointers to all the blocks in the module. We are then able to // iterate over these pointers and split the blocks to which they point; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.h index 0ece48a0d5..58f10ddbc0 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_split_blocks.h @@ -29,8 +29,6 @@ class FuzzerPassSplitBlocks : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassSplitBlocks() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.cpp index 321e8efd63..27fadd173a 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.cpp @@ -28,8 +28,6 @@ FuzzerPassSwapCommutableOperands::FuzzerPassSwapCommutableOperands( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassSwapCommutableOperands::~FuzzerPassSwapCommutableOperands() = default; - void FuzzerPassSwapCommutableOperands::Apply() { auto context = GetIRContext(); // Iterates over the module's instructions and checks whether it is diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.h index 74d937d8c6..93de1728d8 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_commutable_operands.h @@ -30,8 +30,6 @@ class FuzzerPassSwapCommutableOperands : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassSwapCommutableOperands(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.cpp index 9433a61f99..b145b3bcad 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.cpp @@ -31,9 +31,6 @@ FuzzerPassSwapBranchConditionalOperands:: : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassSwapBranchConditionalOperands:: - ~FuzzerPassSwapBranchConditionalOperands() = default; - void FuzzerPassSwapBranchConditionalOperands::Apply() { ForEachInstructionWithInstructionDescriptor( [this](opt::Function* /*unused*/, opt::BasicBlock* /*unused*/, diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.h index f84f3ba400..0137f38b97 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_conditional_branch_operands.h @@ -29,8 +29,6 @@ class FuzzerPassSwapBranchConditionalOperands : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassSwapBranchConditionalOperands() override; - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_functions.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_functions.cpp new file mode 100644 index 0000000000..171f6cb82c --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_functions.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2021 Shiyu Liu +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/fuzzer_pass_swap_functions.h" + +#include "source/fuzz/fuzzer_context.h" +#include "source/fuzz/transformation_swap_two_functions.h" + +namespace spvtools { +namespace fuzz { + +FuzzerPassSwapFunctions::FuzzerPassSwapFunctions( + opt::IRContext* ir_context, TransformationContext* transformation_context, + FuzzerContext* fuzzer_context, + protobufs::TransformationSequence* transformations) + : FuzzerPass(ir_context, transformation_context, fuzzer_context, + transformations) {} + +void FuzzerPassSwapFunctions::Apply() { + // Collect all function ids in a module. + std::vector function_ids; + for (auto& function : *GetIRContext()->module()) { + function_ids.emplace_back(function.result_id()); + } + + // Iterate through every combination of id i & j where i!=j. + for (size_t i = 0; i < function_ids.size(); ++i) { + for (size_t j = i + 1; j < function_ids.size(); ++j) { + // Perform function swap randomly. + if (!GetFuzzerContext()->ChoosePercentage( + GetFuzzerContext()->GetChanceOfSwappingFunctions())) { + continue; + } + TransformationSwapTwoFunctions transformation(function_ids[i], + function_ids[j]); + } + } +} + +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_functions.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_functions.h new file mode 100644 index 0000000000..ac551f6970 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_swap_functions.h @@ -0,0 +1,37 @@ +// Copyright (c) 2021 Shiyu Liu +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_FUZZ_FUZZER_PASS_SWAP_FUNCTIONS_H_ +#define SOURCE_FUZZ_FUZZER_PASS_SWAP_FUNCTIONS_H_ + +#include "source/fuzz/fuzzer_pass.h" + +namespace spvtools { +namespace fuzz { + +// Randomly swap functions within a module. +class FuzzerPassSwapFunctions : public FuzzerPass { + public: + FuzzerPassSwapFunctions(opt::IRContext* ir_context, + TransformationContext* transformation_context, + FuzzerContext* fuzzer_context, + protobufs::TransformationSequence* transformations); + + void Apply() override; +}; + +} // namespace fuzz +} // namespace spvtools + +#endif // SOURCE_FUZZ_FUZZER_PASS_SWAP_FUNCTIONS_H_ diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.cpp index 4f26cba362..e5afd9ee7e 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.cpp @@ -28,9 +28,6 @@ FuzzerPassToggleAccessChainInstruction::FuzzerPassToggleAccessChainInstruction( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassToggleAccessChainInstruction:: - ~FuzzerPassToggleAccessChainInstruction() = default; - void FuzzerPassToggleAccessChainInstruction::Apply() { auto context = GetIRContext(); // Iterates over the module's instructions and checks whether it is diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.h index d77c7cbe7b..ff2f5d457a 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_toggle_access_chain_instruction.h @@ -29,8 +29,6 @@ class FuzzerPassToggleAccessChainInstruction : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassToggleAccessChainInstruction(); - void Apply() override; }; diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.cpp index e6cdca41d1..66bbcd81ac 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.cpp @@ -29,9 +29,6 @@ FuzzerPassWrapRegionsInSelections::FuzzerPassWrapRegionsInSelections( : FuzzerPass(ir_context, transformation_context, fuzzer_context, transformations) {} -FuzzerPassWrapRegionsInSelections::~FuzzerPassWrapRegionsInSelections() = - default; - void FuzzerPassWrapRegionsInSelections::Apply() { for (auto& function : *GetIRContext()->module()) { if (!GetFuzzerContext()->ChoosePercentage( diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.h b/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.h index eb28d20869..822c308f43 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_pass_wrap_regions_in_selections.h @@ -29,8 +29,6 @@ class FuzzerPassWrapRegionsInSelections : public FuzzerPass { FuzzerContext* fuzzer_context, protobufs::TransformationSequence* transformations); - ~FuzzerPassWrapRegionsInSelections() override; - void Apply() override; private: diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_util.cpp b/third_party/spirv-tools/source/fuzz/fuzzer_util.cpp index 8c14db4b87..4beb67fde6 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_util.cpp +++ b/third_party/spirv-tools/source/fuzz/fuzzer_util.cpp @@ -25,6 +25,25 @@ namespace fuzz { namespace fuzzerutil { namespace { +// A utility class that uses RAII to change and restore the terminator +// instruction of the |block|. +class ChangeTerminatorRAII { + public: + explicit ChangeTerminatorRAII(opt::BasicBlock* block, + opt::Instruction new_terminator) + : block_(block), old_terminator_(std::move(*block->terminator())) { + *block_->terminator() = std::move(new_terminator); + } + + ~ChangeTerminatorRAII() { + *block_->terminator() = std::move(old_terminator_); + } + + private: + opt::BasicBlock* block_; + opt::Instruction old_terminator_; +}; + uint32_t MaybeGetOpConstant(opt::IRContext* ir_context, const TransformationContext& transformation_context, const std::vector& words, @@ -47,6 +66,34 @@ const spvtools::MessageConsumer kSilentMessageConsumer = [](spv_message_level_t, const char*, const spv_position_t&, const char*) -> void {}; +bool BuildIRContext(spv_target_env target_env, + const spvtools::MessageConsumer& message_consumer, + const std::vector& binary_in, + spv_validator_options validator_options, + std::unique_ptr* ir_context) { + SpirvTools tools(target_env); + tools.SetMessageConsumer(message_consumer); + if (!tools.IsValid()) { + message_consumer(SPV_MSG_ERROR, nullptr, {}, + "Failed to create SPIRV-Tools interface; stopping."); + return false; + } + + // Initial binary should be valid. + if (!tools.Validate(binary_in.data(), binary_in.size(), validator_options)) { + message_consumer(SPV_MSG_ERROR, nullptr, {}, + "Initial binary is invalid; stopping."); + return false; + } + + // Build the module from the input binary. + auto result = BuildModule(target_env, message_consumer, binary_in.data(), + binary_in.size()); + assert(result && "IRContext must be valid"); + *ir_context = std::move(result); + return true; +} + bool IsFreshId(opt::IRContext* context, uint32_t id) { return !context->get_def_use_mgr()->GetDef(id); } @@ -135,35 +182,46 @@ bool PhiIdsOkForNewEdge( return true; } -void AddUnreachableEdgeAndUpdateOpPhis( - opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to, - uint32_t bool_id, - const google::protobuf::RepeatedField& phi_ids) { - assert(PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids) && - "Precondition on phi_ids is not satisfied"); +opt::Instruction CreateUnreachableEdgeInstruction(opt::IRContext* ir_context, + uint32_t bb_from_id, + uint32_t bb_to_id, + uint32_t bool_id) { + const auto* bb_from = MaybeFindBlock(ir_context, bb_from_id); + assert(bb_from && "|bb_from_id| is invalid"); + assert(MaybeFindBlock(ir_context, bb_to_id) && "|bb_to_id| is invalid"); assert(bb_from->terminator()->opcode() == SpvOpBranch && "Precondition on terminator of bb_from is not satisfied"); // Get the id of the boolean constant to be used as the condition. - auto condition_inst = context->get_def_use_mgr()->GetDef(bool_id); + auto condition_inst = ir_context->get_def_use_mgr()->GetDef(bool_id); assert(condition_inst && (condition_inst->opcode() == SpvOpConstantTrue || condition_inst->opcode() == SpvOpConstantFalse) && "|bool_id| is invalid"); auto condition_value = condition_inst->opcode() == SpvOpConstantTrue; - - const bool from_to_edge_already_exists = bb_from->IsSuccessor(bb_to); - auto successor = bb_from->terminator()->GetSingleWordInOperand(0); + auto successor_id = bb_from->terminator()->GetSingleWordInOperand(0); // Add the dead branch, by turning OpBranch into OpBranchConditional, and // ordering the targets depending on whether the given boolean corresponds to // true or false. - bb_from->terminator()->SetOpcode(SpvOpBranchConditional); - bb_from->terminator()->SetInOperands( + return opt::Instruction( + ir_context, SpvOpBranchConditional, 0, 0, {{SPV_OPERAND_TYPE_ID, {bool_id}}, - {SPV_OPERAND_TYPE_ID, {condition_value ? successor : bb_to->id()}}, - {SPV_OPERAND_TYPE_ID, {condition_value ? bb_to->id() : successor}}}); + {SPV_OPERAND_TYPE_ID, {condition_value ? successor_id : bb_to_id}}, + {SPV_OPERAND_TYPE_ID, {condition_value ? bb_to_id : successor_id}}}); +} + +void AddUnreachableEdgeAndUpdateOpPhis( + opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to, + uint32_t bool_id, + const google::protobuf::RepeatedField& phi_ids) { + assert(PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids) && + "Precondition on phi_ids is not satisfied"); + + const bool from_to_edge_already_exists = bb_from->IsSuccessor(bb_to); + *bb_from->terminator() = CreateUnreachableEdgeInstruction( + context, bb_from->id(), bb_to->id(), bool_id); // Update OpPhi instructions in the target block if this branch adds a // previously non-existent edge from source to target. @@ -194,11 +252,11 @@ bool BlockIsBackEdge(opt::IRContext* context, uint32_t block_id, return false; } - // |block_id| must be reachable and be dominated by |loop_header|. + // |block| must be reachable and be dominated by |loop_header|. opt::DominatorAnalysis* dominator_analysis = context->GetDominatorAnalysis(loop_header->GetParent()); - return dominator_analysis->IsReachable(block_id) && - dominator_analysis->Dominates(loop_header_id, block_id); + return context->IsReachable(*block) && + dominator_analysis->Dominates(loop_header, block); } bool BlockIsInLoopContinueConstruct(opt::IRContext* context, uint32_t block_id, @@ -226,13 +284,6 @@ opt::BasicBlock::iterator GetIteratorForInstruction( return block->end(); } -bool BlockIsReachableInItsFunction(opt::IRContext* context, - opt::BasicBlock* bb) { - auto enclosing_function = bb->GetParent(); - return context->GetDominatorAnalysis(enclosing_function) - ->Dominates(enclosing_function->entry().get(), bb); -} - bool CanInsertOpcodeBeforeInstruction( SpvOp opcode, const opt::BasicBlock::iterator& instruction_in_block) { if (instruction_in_block->PreviousNode() && @@ -410,7 +461,7 @@ bool IsValid(const opt::IRContext* context, std::vector binary; context->module()->ToBinary(&binary, false); SpirvTools tools(context->grammar().target_env()); - tools.SetMessageConsumer(consumer); + tools.SetMessageConsumer(std::move(consumer)); return tools.Validate(binary.data(), binary.size(), validator_options); } @@ -602,13 +653,12 @@ bool IdIsAvailableAtUse(opt::IRContext* context, // It is not OK for a definition to use itself. return false; } - auto dominator_analysis = context->GetDominatorAnalysis(enclosing_function); - if (!dominator_analysis->IsReachable( - context->get_instr_block(use_instruction)) || - !dominator_analysis->IsReachable(context->get_instr_block(id))) { + if (!context->IsReachable(*context->get_instr_block(use_instruction)) || + !context->IsReachable(*context->get_instr_block(id))) { // Skip unreachable blocks. return false; } + auto dominator_analysis = context->GetDominatorAnalysis(enclosing_function); if (use_instruction->opcode() == SpvOpPhi) { // In the case where the use is an operand to OpPhi, it is actually the // *parent* block associated with the operand that must be dominated by @@ -646,8 +696,8 @@ bool IdIsAvailableBeforeInstruction(opt::IRContext* context, } const auto* dominator_analysis = context->GetDominatorAnalysis(function_enclosing_instruction); - if (dominator_analysis->IsReachable(context->get_instr_block(instruction)) && - dominator_analysis->IsReachable(context->get_instr_block(id)) && + if (context->IsReachable(*context->get_instr_block(instruction)) && + context->IsReachable(*context->get_instr_block(id)) && dominator_analysis->Dominates(id_definition, instruction)) { // The id's definition dominates the instruction, and both the definition // and the instruction are in reachable blocks, thus the id is available at @@ -657,8 +707,7 @@ bool IdIsAvailableBeforeInstruction(opt::IRContext* context, if (id_definition->opcode() == SpvOpVariable && function_enclosing_instruction == context->get_instr_block(id)->GetParent()) { - assert(!dominator_analysis->IsReachable( - context->get_instr_block(instruction)) && + assert(!context->IsReachable(*context->get_instr_block(instruction)) && "If the instruction were in a reachable block we should already " "have returned true."); // The id is a variable and it is in the same function as |instruction|. @@ -747,14 +796,15 @@ bool IsNullConstantSupported(const opt::analysis::Type& type) { bool GlobalVariablesMustBeDeclaredInEntryPointInterfaces( const opt::IRContext* ir_context) { - // TODO(afd): We capture the universal environments for which this requirement - // holds. The check should be refined on demand for other target - // environments. + // TODO(afd): We capture the environments for which this requirement holds. + // The check should be refined on demand for other target environments. switch (ir_context->grammar().target_env()) { case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_3: + case SPV_ENV_VULKAN_1_0: + case SPV_ENV_VULKAN_1_1: return false; default: return true; @@ -778,9 +828,10 @@ void AddVariableIdToEntryPointInterfaces(opt::IRContext* context, uint32_t id) { } } -void AddGlobalVariable(opt::IRContext* context, uint32_t result_id, - uint32_t type_id, SpvStorageClass storage_class, - uint32_t initializer_id) { +opt::Instruction* AddGlobalVariable(opt::IRContext* context, uint32_t result_id, + uint32_t type_id, + SpvStorageClass storage_class, + uint32_t initializer_id) { // Check various preconditions. assert(result_id != 0 && "Result id can't be 0"); @@ -815,16 +866,20 @@ void AddGlobalVariable(opt::IRContext* context, uint32_t result_id, operands.push_back({SPV_OPERAND_TYPE_ID, {initializer_id}}); } - context->module()->AddGlobalValue(MakeUnique( - context, SpvOpVariable, type_id, result_id, std::move(operands))); + auto new_instruction = MakeUnique( + context, SpvOpVariable, type_id, result_id, std::move(operands)); + auto result = new_instruction.get(); + context->module()->AddGlobalValue(std::move(new_instruction)); AddVariableIdToEntryPointInterfaces(context, result_id); UpdateModuleIdBound(context, result_id); + + return result; } -void AddLocalVariable(opt::IRContext* context, uint32_t result_id, - uint32_t type_id, uint32_t function_id, - uint32_t initializer_id) { +opt::Instruction* AddLocalVariable(opt::IRContext* context, uint32_t result_id, + uint32_t type_id, uint32_t function_id, + uint32_t initializer_id) { // Check various preconditions. assert(result_id != 0 && "Result id can't be 0"); @@ -845,13 +900,17 @@ void AddLocalVariable(opt::IRContext* context, uint32_t result_id, auto* function = FindFunction(context, function_id); assert(function && "Function id is invalid"); - function->begin()->begin()->InsertBefore(MakeUnique( + auto new_instruction = MakeUnique( context, SpvOpVariable, type_id, result_id, opt::Instruction::OperandList{ {SPV_OPERAND_TYPE_STORAGE_CLASS, {SpvStorageClassFunction}}, - {SPV_OPERAND_TYPE_ID, {initializer_id}}})); + {SPV_OPERAND_TYPE_ID, {initializer_id}}}); + auto result = new_instruction.get(); + function->begin()->begin()->InsertBefore(std::move(new_instruction)); UpdateModuleIdBound(context, result_id); + + return result; } bool HasDuplicates(const std::vector& arr) { @@ -1355,74 +1414,6 @@ uint32_t MaybeGetBoolConstant( return 0; } -void AddIntegerType(opt::IRContext* ir_context, uint32_t result_id, - uint32_t width, bool is_signed) { - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypeInt, 0, result_id, - opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_LITERAL_INTEGER, {width}}, - {SPV_OPERAND_TYPE_LITERAL_INTEGER, {is_signed ? 1u : 0u}}})); - - UpdateModuleIdBound(ir_context, result_id); -} - -void AddFloatType(opt::IRContext* ir_context, uint32_t result_id, - uint32_t width) { - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypeFloat, 0, result_id, - opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_LITERAL_INTEGER, {width}}})); - - UpdateModuleIdBound(ir_context, result_id); -} - -void AddVectorType(opt::IRContext* ir_context, uint32_t result_id, - uint32_t component_type_id, uint32_t element_count) { - const auto* component_type = - ir_context->get_type_mgr()->GetType(component_type_id); - (void)component_type; // Make compiler happy in release mode. - assert(component_type && - (component_type->AsInteger() || component_type->AsFloat() || - component_type->AsBool()) && - "|component_type_id| is invalid"); - assert(element_count >= 2 && element_count <= 4 && - "Precondition: component count must be in range [2, 4]."); - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypeVector, 0, result_id, - opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {component_type_id}}, - {SPV_OPERAND_TYPE_LITERAL_INTEGER, {element_count}}})); - - UpdateModuleIdBound(ir_context, result_id); -} - -void AddStructType(opt::IRContext* ir_context, uint32_t result_id, - const std::vector& component_type_ids) { - opt::Instruction::OperandList operands; - operands.reserve(component_type_ids.size()); - - for (auto type_id : component_type_ids) { - const auto* type = ir_context->get_type_mgr()->GetType(type_id); - (void)type; // Make compiler happy in release mode. - assert(type && !type->AsFunction() && "Component's type id is invalid"); - - if (type->AsStruct()) { - // From the spec for the BuiltIn decoration: - // - When applied to a structure-type member, that structure type cannot - // be contained as a member of another structure type. - assert(!MembersHaveBuiltInDecoration(ir_context, type_id) && - "A member struct has BuiltIn members"); - } - - operands.push_back({SPV_OPERAND_TYPE_ID, {type_id}}); - } - - ir_context->AddType(MakeUnique( - ir_context, SpvOpTypeStruct, 0, result_id, std::move(operands))); - - UpdateModuleIdBound(ir_context, result_id); -} - std::vector IntToWords(uint64_t value, uint32_t width, bool is_signed) { assert(width <= 64 && "The bit width should not be more than 64 bits"); @@ -1827,6 +1818,113 @@ std::set GetReachableReturnBlocks(opt::IRContext* ir_context, return result; } +bool NewTerminatorPreservesDominationRules(opt::IRContext* ir_context, + uint32_t block_id, + opt::Instruction new_terminator) { + auto* mutated_block = MaybeFindBlock(ir_context, block_id); + assert(mutated_block && "|block_id| is invalid"); + + ChangeTerminatorRAII change_terminator_raii(mutated_block, + std::move(new_terminator)); + opt::DominatorAnalysis dominator_analysis; + dominator_analysis.InitializeTree(*ir_context->cfg(), + mutated_block->GetParent()); + + // Check that each dominator appears before each dominated block. + std::unordered_map positions; + for (const auto& block : *mutated_block->GetParent()) { + positions[block.id()] = positions.size(); + } + + std::queue q({mutated_block->GetParent()->begin()->id()}); + std::unordered_set visited; + while (!q.empty()) { + auto block = q.front(); + q.pop(); + visited.insert(block); + + auto success = ir_context->cfg()->block(block)->WhileEachSuccessorLabel( + [&positions, &visited, &dominator_analysis, block, &q](uint32_t id) { + if (id == block) { + // Handle the case when loop header and continue target are the same + // block. + return true; + } + + if (dominator_analysis.Dominates(block, id) && + positions[block] > positions[id]) { + // |block| dominates |id| but appears after |id| - violates + // domination rules. + return false; + } + + if (!visited.count(id)) { + q.push(id); + } + + return true; + }); + + if (!success) { + return false; + } + } + + // For each instruction in the |block->GetParent()| function check whether + // all its dependencies satisfy domination rules (i.e. all id operands + // dominate that instruction). + for (const auto& block : *mutated_block->GetParent()) { + if (!ir_context->IsReachable(block)) { + // If some block is not reachable then we don't need to worry about the + // preservation of domination rules for its instructions. + continue; + } + + for (const auto& inst : block) { + for (uint32_t i = 0; i < inst.NumInOperands(); + i += inst.opcode() == SpvOpPhi ? 2 : 1) { + const auto& operand = inst.GetInOperand(i); + if (!spvIsInIdType(operand.type)) { + continue; + } + + if (MaybeFindBlock(ir_context, operand.words[0])) { + // Ignore operands that refer to OpLabel instructions. + continue; + } + + const auto* dependency_block = + ir_context->get_instr_block(operand.words[0]); + if (!dependency_block) { + // A global instruction always dominates all instructions in any + // function. + continue; + } + + auto domination_target_id = inst.opcode() == SpvOpPhi + ? inst.GetSingleWordInOperand(i + 1) + : block.id(); + + if (!dominator_analysis.Dominates(dependency_block->id(), + domination_target_id)) { + return false; + } + } + } + } + + return true; +} + +opt::Module::iterator GetFunctionIterator(opt::IRContext* ir_context, + uint32_t function_id) { + return std::find_if(ir_context->module()->begin(), + ir_context->module()->end(), + [function_id](const opt::Function& f) { + return f.result_id() == function_id; + }); +} + } // namespace fuzzerutil } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/fuzzer_util.h b/third_party/spirv-tools/source/fuzz/fuzzer_util.h index 4e6ec36ead..b956507a91 100644 --- a/third_party/spirv-tools/source/fuzz/fuzzer_util.h +++ b/third_party/spirv-tools/source/fuzz/fuzzer_util.h @@ -24,6 +24,7 @@ #include "source/opt/basic_block.h" #include "source/opt/instruction.h" #include "source/opt/ir_context.h" +#include "source/opt/module.h" #include "spirv-tools/libspirv.hpp" namespace spvtools { @@ -38,6 +39,15 @@ extern const spvtools::MessageConsumer kSilentMessageConsumer; // Function type that produces a SPIR-V module. using ModuleSupplier = std::function()>; +// Builds a new opt::IRContext object. Returns true if successful and changes +// the |ir_context| parameter. Otherwise (if any errors occur), returns false +// and |ir_context| remains unchanged. +bool BuildIRContext(spv_target_env target_env, + const spvtools::MessageConsumer& message_consumer, + const std::vector& binary_in, + spv_validator_options validator_options, + std::unique_ptr* ir_context); + // Returns true if and only if the module does not define the given id. bool IsFreshId(opt::IRContext* context, uint32_t id); @@ -59,6 +69,16 @@ bool PhiIdsOkForNewEdge( opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to, const google::protobuf::RepeatedField& phi_ids); +// Returns an OpBranchConditional instruction that will create an unreachable +// branch from |bb_from_id| to |bb_to_id|. |bool_id| must be a result id of +// either OpConstantTrue or OpConstantFalse. Based on the opcode of |bool_id|, +// operands of the returned instruction will be positioned in a way that the +// branch from |bb_from_id| to |bb_to_id| is always unreachable. +opt::Instruction CreateUnreachableEdgeInstruction(opt::IRContext* ir_context, + uint32_t bb_from_id, + uint32_t bb_to_id, + uint32_t bool_id); + // Requires that |bool_id| is a valid result id of either OpConstantTrue or // OpConstantFalse, that PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids) // holds, and that bb_from ends with "OpBranch %some_block". Turns OpBranch @@ -88,11 +108,6 @@ bool BlockIsInLoopContinueConstruct(opt::IRContext* context, uint32_t block_id, opt::BasicBlock::iterator GetIteratorForInstruction( opt::BasicBlock* block, const opt::Instruction* inst); -// Returns true if and only if there is a path to |bb| from the entry block of -// the function that contains |bb|. -bool BlockIsReachableInItsFunction(opt::IRContext* context, - opt::BasicBlock* bb); - // Determines whether it is OK to insert an instruction with opcode |opcode| // before |instruction_in_block|. bool CanInsertOpcodeBeforeInstruction( @@ -284,9 +299,12 @@ void AddVariableIdToEntryPointInterfaces(opt::IRContext* context, uint32_t id); // - |initializer_id| must be 0 if |storage_class| is Workgroup, and otherwise // may either be 0 or the id of a constant whose type is the pointee type of // |type_id|. -void AddGlobalVariable(opt::IRContext* context, uint32_t result_id, - uint32_t type_id, SpvStorageClass storage_class, - uint32_t initializer_id); +// +// Returns a pointer to the new global variable instruction. +opt::Instruction* AddGlobalVariable(opt::IRContext* context, uint32_t result_id, + uint32_t type_id, + SpvStorageClass storage_class, + uint32_t initializer_id); // Adds an instruction to the start of |function_id|, of the form: // |result_id| = OpVariable |type_id| Function |initializer_id|. @@ -296,9 +314,11 @@ void AddGlobalVariable(opt::IRContext* context, uint32_t result_id, // - |initializer_id| must be the id of a constant with the same type as the // pointer's pointee type. // - |function_id| must be the id of a function. -void AddLocalVariable(opt::IRContext* context, uint32_t result_id, - uint32_t type_id, uint32_t function_id, - uint32_t initializer_id); +// +// Returns a pointer to the new local variable instruction. +opt::Instruction* AddLocalVariable(opt::IRContext* context, uint32_t result_id, + uint32_t type_id, uint32_t function_id, + uint32_t initializer_id); // Returns true if the vector |arr| has duplicates. bool HasDuplicates(const std::vector& arr); @@ -476,30 +496,6 @@ uint32_t MaybeGetBoolConstant( const TransformationContext& transformation_context, bool value, bool is_irrelevant); -// Creates a new OpTypeInt instruction in the module. Updates module's id bound -// to accommodate for |result_id|. -void AddIntegerType(opt::IRContext* ir_context, uint32_t result_id, - uint32_t width, bool is_signed); - -// Creates a new OpTypeFloat instruction in the module. Updates module's id -// bound to accommodate for |result_id|. -void AddFloatType(opt::IRContext* ir_context, uint32_t result_id, - uint32_t width); - -// Creates a new OpTypeVector instruction in the module. |component_type_id| -// must be a valid result id of an OpTypeInt, OpTypeFloat or OpTypeBool -// instruction in the module. |element_count| must be in the range [2, 4]. -// Updates module's id bound to accommodate for |result_id|. -void AddVectorType(opt::IRContext* ir_context, uint32_t result_id, - uint32_t component_type_id, uint32_t element_count); - -// Creates a new OpTypeStruct instruction in the module. Updates module's id -// bound to accommodate for |result_id|. |component_type_ids| may not contain -// a result id of an OpTypeFunction. if |component_type_ids| contains a result -// of an OpTypeStruct instruction, that struct may not have BuiltIn members. -void AddStructType(opt::IRContext* ir_context, uint32_t result_id, - const std::vector& component_type_ids); - // Returns a vector of words representing the integer |value|, only considering // the last |width| bits. The last |width| bits are sign-extended if the value // is signed, zero-extended if it is unsigned. @@ -588,6 +584,20 @@ bool InstructionHasNoSideEffects(const opt::Instruction& instruction); std::set GetReachableReturnBlocks(opt::IRContext* ir_context, uint32_t function_id); +// Returns true if changing terminator instruction to |new_terminator| in the +// basic block with id |block_id| preserves domination rules and valid block +// order (i.e. dominator must always appear before dominated in the CFG). +// Returns false otherwise. +bool NewTerminatorPreservesDominationRules(opt::IRContext* ir_context, + uint32_t block_id, + opt::Instruction new_terminator); + +// Return the iterator that points to the function with the corresponding +// function id. If the function is not found, return the pointer pointing to +// module()->end(). +opt::Module::iterator GetFunctionIterator(opt::IRContext* ir_context, + uint32_t function_id); + } // namespace fuzzerutil } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/instruction_descriptor.cpp b/third_party/spirv-tools/source/fuzz/instruction_descriptor.cpp index c0cc5e52cd..fb1ff765a5 100644 --- a/third_party/spirv-tools/source/fuzz/instruction_descriptor.cpp +++ b/third_party/spirv-tools/source/fuzz/instruction_descriptor.cpp @@ -20,37 +20,32 @@ namespace fuzz { opt::Instruction* FindInstruction( const protobufs::InstructionDescriptor& instruction_descriptor, spvtools::opt::IRContext* context) { - for (auto& function : *context->module()) { - for (auto& block : function) { - bool found_base = - block.id() == instruction_descriptor.base_instruction_result_id(); - uint32_t num_ignored = 0; - for (auto& instruction : block) { - if (instruction.HasResultId() && - instruction.result_id() == - instruction_descriptor.base_instruction_result_id()) { - assert(!found_base && - "It should not be possible to find the base instruction " - "multiple times."); - found_base = true; - assert(num_ignored == 0 && - "The skipped instruction count should only be incremented " - "after the instruction base has been found."); - } - if (found_base && - instruction.opcode() == - instruction_descriptor.target_instruction_opcode()) { - if (num_ignored == instruction_descriptor.num_opcodes_to_ignore()) { - return &instruction; - } - num_ignored++; - } - } - if (found_base) { - // We found the base instruction, but did not find the target - // instruction in the same block. - return nullptr; + auto block = context->get_instr_block( + instruction_descriptor.base_instruction_result_id()); + if (block == nullptr) { + return nullptr; + } + bool found_base = + block->id() == instruction_descriptor.base_instruction_result_id(); + uint32_t num_ignored = 0; + for (auto& instruction : *block) { + if (instruction.HasResultId() && + instruction.result_id() == + instruction_descriptor.base_instruction_result_id()) { + assert(!found_base && + "It should not be possible to find the base instruction " + "multiple times."); + found_base = true; + assert(num_ignored == 0 && + "The skipped instruction count should only be incremented " + "after the instruction base has been found."); + } + if (found_base && instruction.opcode() == + instruction_descriptor.target_instruction_opcode()) { + if (num_ignored == instruction_descriptor.num_opcodes_to_ignore()) { + return &instruction; } + num_ignored++; } } return nullptr; diff --git a/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.cpp b/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.cpp index 032f264567..ec443733a7 100644 --- a/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.cpp +++ b/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.cpp @@ -14,6 +14,10 @@ #include "source/fuzz/pass_management/repeated_pass_manager.h" +#include "source/fuzz/pass_management/repeated_pass_manager_looped_with_recommendations.h" +#include "source/fuzz/pass_management/repeated_pass_manager_random_with_recommendations.h" +#include "source/fuzz/pass_management/repeated_pass_manager_simple.h" + namespace spvtools { namespace fuzz { @@ -23,5 +27,25 @@ RepeatedPassManager::RepeatedPassManager(FuzzerContext* fuzzer_context, RepeatedPassManager::~RepeatedPassManager() = default; +std::unique_ptr RepeatedPassManager::Create( + RepeatedPassStrategy strategy, FuzzerContext* fuzzer_context, + RepeatedPassInstances* pass_instances, + RepeatedPassRecommender* pass_recommender) { + switch (strategy) { + case RepeatedPassStrategy::kSimple: + return MakeUnique(fuzzer_context, + pass_instances); + case RepeatedPassStrategy::kLoopedWithRecommendations: + return MakeUnique( + fuzzer_context, pass_instances, pass_recommender); + case RepeatedPassStrategy::kRandomWithRecommendations: + return MakeUnique( + fuzzer_context, pass_instances, pass_recommender); + } + + assert(false && "Unreachable"); + return nullptr; +} + } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.h b/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.h index 1c231792d8..1e6ae3e48f 100644 --- a/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.h +++ b/third_party/spirv-tools/source/fuzz/pass_management/repeated_pass_manager.h @@ -18,11 +18,21 @@ #include "source/fuzz/fuzzer_context.h" #include "source/fuzz/fuzzer_pass.h" #include "source/fuzz/pass_management/repeated_pass_instances.h" +#include "source/fuzz/pass_management/repeated_pass_recommender.h" #include "source/fuzz/protobufs/spirvfuzz_protobufs.h" namespace spvtools { namespace fuzz { +// Each field of this enum corresponds to an available repeated pass +// strategy, and is used to decide which kind of RepeatedPassManager object +// to create. +enum class RepeatedPassStrategy { + kSimple, + kRandomWithRecommendations, + kLoopedWithRecommendations +}; + // An interface to encapsulate the manner in which the sequence of repeated // passes that are applied during fuzzing is chosen. An implementation of this // interface could, for example, keep track of the history of passes that have @@ -40,6 +50,12 @@ class RepeatedPassManager { virtual FuzzerPass* ChoosePass( const protobufs::TransformationSequence& applied_transformations) = 0; + // Creates a corresponding RepeatedPassManager based on the |strategy|. + static std::unique_ptr Create( + RepeatedPassStrategy strategy, FuzzerContext* fuzzer_context, + RepeatedPassInstances* pass_instances, + RepeatedPassRecommender* pass_recommender); + protected: FuzzerContext* GetFuzzerContext() { return fuzzer_context_; } diff --git a/third_party/spirv-tools/source/fuzz/protobufs/spvtoolsfuzz.proto b/third_party/spirv-tools/source/fuzz/protobufs/spvtoolsfuzz.proto index 770a2dd31c..657e807616 100644 --- a/third_party/spirv-tools/source/fuzz/protobufs/spvtoolsfuzz.proto +++ b/third_party/spirv-tools/source/fuzz/protobufs/spvtoolsfuzz.proto @@ -557,6 +557,8 @@ message Transformation { TransformationWrapEarlyTerminatorInFunction wrap_early_terminator_in_function = 83; TransformationMergeFunctionReturns merge_function_returns = 84; TransformationExpandVectorReduction expand_vector_reduction = 85; + TransformationSwapFunctionVariables swap_function_variables = 86; + TransformationSwapTwoFunctions swap_two_functions = 87; // Add additional option using the next available number. } } @@ -1134,6 +1136,14 @@ message TransformationAddSynonym { // New synonym is derived by applying OpLogicalAnd to |result_id| with the second // operand being 'true'. LOGICAL_AND = 5; + + // New synonym is derived by applying OpBitwiseOr to |result_id| with the second + // operand being 0 taken with the same bit length as |result_id| + BITWISE_OR = 6; + + // New synonym is derived by applying OpBitwiseXor to |result_id| with the second + // operand being 0 taken with the same bit length as |result_id| + BITWISE_XOR = 7; } // Type of the synonym to create. See SynonymType for more details. @@ -1632,6 +1642,9 @@ message TransformationMergeFunctionReturns { // A fresh id for the header of the new outer loop. uint32 outer_header_id = 2; + // A fresh id for an unreachable continue construct for the new outer loop. + uint32 unreachable_continue_id = 7; + // A fresh id for the new return block of the function, // i.e. the merge block of the new outer loop. uint32 outer_return_id = 3; @@ -2260,6 +2273,24 @@ message TransformationSwapConditionalBranchOperands { } +message TransformationSwapFunctionVariables { + // A transformation that swaps function variables + + // Result id of the first variable. + uint32 result_id1 = 1; + // Result id of the second variable. + uint32 result_id2 = 2; + +} + +message TransformationSwapTwoFunctions { + // A transformation that swaps the position of two functions within the same module. + + // the IDs for the two functions that are swapped. + uint32 function_id1 = 1; + uint32 function_id2 = 2; +} + message TransformationToggleAccessChainInstruction { // A transformation that toggles an access chain instruction. diff --git a/third_party/spirv-tools/source/fuzz/transformation.cpp b/third_party/spirv-tools/source/fuzz/transformation.cpp index ebbc393748..4ea0c773c6 100644 --- a/third_party/spirv-tools/source/fuzz/transformation.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation.cpp @@ -98,6 +98,8 @@ #include "source/fuzz/transformation_store.h" #include "source/fuzz/transformation_swap_commutable_operands.h" #include "source/fuzz/transformation_swap_conditional_branch_operands.h" +#include "source/fuzz/transformation_swap_function_variables.h" +#include "source/fuzz/transformation_swap_two_functions.h" #include "source/fuzz/transformation_toggle_access_chain_instruction.h" #include "source/fuzz/transformation_vector_shuffle.h" #include "source/fuzz/transformation_wrap_early_terminator_in_function.h" @@ -361,6 +363,12 @@ std::unique_ptr Transformation::FromMessage( kSwapConditionalBranchOperands: return MakeUnique( message.swap_conditional_branch_operands()); + case protobufs::Transformation::TransformationCase::kSwapFunctionVariables: + return MakeUnique( + message.swap_function_variables()); + case protobufs::Transformation::TransformationCase::kSwapTwoFunctions: + return MakeUnique( + message.swap_two_functions()); case protobufs::Transformation::TransformationCase:: kToggleAccessChainInstruction: return MakeUnique( diff --git a/third_party/spirv-tools/source/fuzz/transformation_access_chain.cpp b/third_party/spirv-tools/source/fuzz/transformation_access_chain.cpp index daf73d6347..3fe9e656b5 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_access_chain.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_access_chain.cpp @@ -23,8 +23,8 @@ namespace spvtools { namespace fuzz { TransformationAccessChain::TransformationAccessChain( - const spvtools::fuzz::protobufs::TransformationAccessChain& message) - : message_(message) {} + protobufs::TransformationAccessChain message) + : message_(std::move(message)) {} TransformationAccessChain::TransformationAccessChain( uint32_t fresh_id, uint32_t pointer_id, @@ -122,7 +122,7 @@ bool TransformationAccessChain::IsApplicable( bool successful; std::tie(successful, index_value) = - GetIndexValue(ir_context, index_id, subobject_type_id); + GetStructIndexValue(ir_context, index_id, subobject_type_id); if (!successful) { return false; @@ -228,6 +228,11 @@ void TransformationAccessChain::Apply( uint32_t id_pairs_used = 0; + opt::Instruction* instruction_to_insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + opt::BasicBlock* enclosing_block = + ir_context->get_instr_block(instruction_to_insert_before); + // Go through the index ids in turn. for (auto index_id : message_.index_id()) { uint32_t index_value; @@ -242,7 +247,7 @@ void TransformationAccessChain::Apply( // It is a struct: we need to retrieve the integer value. index_value = - GetIndexValue(ir_context, index_id, subobject_type_id).second; + GetStructIndexValue(ir_context, index_id, subobject_type_id).second; new_index_id = index_id; @@ -280,29 +285,37 @@ void TransformationAccessChain::Apply( // Clamp the integer and add the corresponding instructions in the module // if |add_clamping_instructions| is set. - auto instruction_to_insert_before = - FindInstruction(message_.instruction_to_insert_before(), ir_context); // Compare the index with the bound via an instruction of the form: // %fresh_ids.first = OpULessThanEqual %bool %int_id %bound_minus_one. fuzzerutil::UpdateModuleIdBound(ir_context, fresh_ids.first()); - instruction_to_insert_before->InsertBefore(MakeUnique( + auto comparison_instruction = MakeUnique( ir_context, SpvOpULessThanEqual, bool_type_id, fresh_ids.first(), opt::Instruction::OperandList( {{SPV_OPERAND_TYPE_ID, {index_instruction->result_id()}}, - {SPV_OPERAND_TYPE_ID, {bound_minus_one_id}}}))); + {SPV_OPERAND_TYPE_ID, {bound_minus_one_id}}})); + auto comparison_instruction_ptr = comparison_instruction.get(); + instruction_to_insert_before->InsertBefore( + std::move(comparison_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse( + comparison_instruction_ptr); + ir_context->set_instr_block(comparison_instruction_ptr, enclosing_block); // Select the index if in-bounds, otherwise one less than the bound: // %fresh_ids.second = OpSelect %int_type %fresh_ids.first %int_id // %bound_minus_one fuzzerutil::UpdateModuleIdBound(ir_context, fresh_ids.second()); - instruction_to_insert_before->InsertBefore(MakeUnique( + auto select_instruction = MakeUnique( ir_context, SpvOpSelect, int_type_inst->result_id(), fresh_ids.second(), opt::Instruction::OperandList( {{SPV_OPERAND_TYPE_ID, {fresh_ids.first()}}, {SPV_OPERAND_TYPE_ID, {index_instruction->result_id()}}, - {SPV_OPERAND_TYPE_ID, {bound_minus_one_id}}}))); + {SPV_OPERAND_TYPE_ID, {bound_minus_one_id}}})); + auto select_instruction_ptr = select_instruction.get(); + instruction_to_insert_before->InsertBefore(std::move(select_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(select_instruction_ptr); + ir_context->set_instr_block(select_instruction_ptr, enclosing_block); new_index_id = fresh_ids.second(); @@ -326,13 +339,14 @@ void TransformationAccessChain::Apply( // Add the access chain instruction to the module, and update the module's // id bound. fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( - ir_context, SpvOpAccessChain, result_type, message_.fresh_id(), - operands)); - - // Conservatively invalidate all analyses. - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + auto access_chain_instruction = MakeUnique( + ir_context, SpvOpAccessChain, result_type, message_.fresh_id(), operands); + auto access_chain_instruction_ptr = access_chain_instruction.get(); + instruction_to_insert_before->InsertBefore( + std::move(access_chain_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse( + access_chain_instruction_ptr); + ir_context->set_instr_block(access_chain_instruction_ptr, enclosing_block); // If the base pointer's pointee value was irrelevant, the same is true of // the pointee value of the result of this access chain. @@ -349,9 +363,12 @@ protobufs::Transformation TransformationAccessChain::ToMessage() const { return result; } -std::pair TransformationAccessChain::GetIndexValue( +std::pair TransformationAccessChain::GetStructIndexValue( opt::IRContext* ir_context, uint32_t index_id, uint32_t object_type_id) const { + assert(ir_context->get_def_use_mgr()->GetDef(object_type_id)->opcode() == + SpvOpTypeStruct && + "Precondition: the type must be a struct type."); if (!ValidIndexToComposite(ir_context, index_id, object_type_id)) { return {false, 0}; } @@ -360,10 +377,9 @@ std::pair TransformationAccessChain::GetIndexValue( uint32_t bound = fuzzerutil::GetBoundForCompositeIndex( *ir_context->get_def_use_mgr()->GetDef(object_type_id), ir_context); - // The index must be a constant - if (!spvOpcodeIsConstant(index_instruction->opcode())) { - return {false, 0}; - } + // Ensure that the index given must represent a constant. + assert(spvOpcodeIsConstant(index_instruction->opcode()) && + "A non-constant index should already have been rejected."); // The index must be in bounds. uint32_t value = index_instruction->GetSingleWordInOperand(0); diff --git a/third_party/spirv-tools/source/fuzz/transformation_access_chain.h b/third_party/spirv-tools/source/fuzz/transformation_access_chain.h index 02cdc32901..4e4fd2b624 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_access_chain.h +++ b/third_party/spirv-tools/source/fuzz/transformation_access_chain.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAccessChain : public Transformation { public: explicit TransformationAccessChain( - const protobufs::TransformationAccessChain& message); + protobufs::TransformationAccessChain message); TransformationAccessChain( uint32_t fresh_id, uint32_t pointer_id, @@ -83,13 +83,13 @@ class TransformationAccessChain : public Transformation { private: // Returns {false, 0} in each of the following cases: // - |index_id| does not correspond to a 32-bit integer constant - // - the object being indexed is not a composite type + // - |object_type_id| must be a struct type // - the constant at |index_id| is out of bounds. // Otherwise, returns {true, value}, where value is the value of the constant // at |index_id|. - std::pair GetIndexValue(opt::IRContext* ir_context, - uint32_t index_id, - uint32_t object_type_id) const; + std::pair GetStructIndexValue(opt::IRContext* ir_context, + uint32_t index_id, + uint32_t object_type_id) const; // Returns true if |index_id| corresponds, in the given context, to a 32-bit // integer which can be used to index an object of the type specified by diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.cpp index 6cdfdfb64c..636c0a3855 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.cpp @@ -21,9 +21,8 @@ namespace spvtools { namespace fuzz { TransformationAddBitInstructionSynonym::TransformationAddBitInstructionSynonym( - const spvtools::fuzz::protobufs::TransformationAddBitInstructionSynonym& - message) - : message_(message) {} + protobufs::TransformationAddBitInstructionSynonym message) + : message_(std::move(message)) {} TransformationAddBitInstructionSynonym::TransformationAddBitInstructionSynonym( const uint32_t instruction_result_id, @@ -40,20 +39,9 @@ bool TransformationAddBitInstructionSynonym::IsApplicable( auto instruction = ir_context->get_def_use_mgr()->GetDef(message_.instruction_result_id()); - // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3557): - // Right now we only support certain operations. When this issue is addressed - // the following conditional can use the function |spvOpcodeIsBit|. - // |instruction| must be defined and must be a supported bit instruction. - if (!instruction || (instruction->opcode() != SpvOpBitwiseOr && - instruction->opcode() != SpvOpBitwiseXor && - instruction->opcode() != SpvOpBitwiseAnd && - instruction->opcode() != SpvOpNot)) { - return false; - } - - // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3792): - // Right now, only integer operands are supported. - if (ir_context->get_type_mgr()->GetType(instruction->type_id())->AsVector()) { + // Checks on: only integer operands are supported, instructions are bitwise + // operations only. Signedness of the operands must be the same. + if (!IsInstructionSupported(ir_context, instruction)) { return false; } @@ -112,6 +100,65 @@ void TransformationAddBitInstructionSynonym::Apply( } } +bool TransformationAddBitInstructionSynonym::IsInstructionSupported( + opt::IRContext* ir_context, opt::Instruction* instruction) { + // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3557): + // Right now we only support certain operations. When this issue is addressed + // the following conditional can use the function |spvOpcodeIsBit|. + // |instruction| must be defined and must be a supported bit instruction. + if (!instruction || (instruction->opcode() != SpvOpBitwiseOr && + instruction->opcode() != SpvOpBitwiseXor && + instruction->opcode() != SpvOpBitwiseAnd && + instruction->opcode() != SpvOpNot)) { + return false; + } + + // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3792): + // Right now, only integer operands are supported. + if (ir_context->get_type_mgr()->GetType(instruction->type_id())->AsVector()) { + return false; + } + + if (instruction->opcode() == SpvOpNot) { + auto operand = instruction->GetInOperand(0).words[0]; + auto operand_inst = ir_context->get_def_use_mgr()->GetDef(operand); + auto operand_type = + ir_context->get_type_mgr()->GetType(operand_inst->type_id()); + auto operand_sign = operand_type->AsInteger()->IsSigned(); + + auto type_id_sign = ir_context->get_type_mgr() + ->GetType(instruction->type_id()) + ->AsInteger() + ->IsSigned(); + + return operand_sign == type_id_sign; + + } else { + // Other BitWise operations that takes two operands. + auto first_operand = instruction->GetInOperand(0).words[0]; + auto first_operand_inst = + ir_context->get_def_use_mgr()->GetDef(first_operand); + auto first_operand_type = + ir_context->get_type_mgr()->GetType(first_operand_inst->type_id()); + auto first_operand_sign = first_operand_type->AsInteger()->IsSigned(); + + auto second_operand = instruction->GetInOperand(1).words[0]; + auto second_operand_inst = + ir_context->get_def_use_mgr()->GetDef(second_operand); + auto second_operand_type = + ir_context->get_type_mgr()->GetType(second_operand_inst->type_id()); + auto second_operand_sign = second_operand_type->AsInteger()->IsSigned(); + + auto type_id_sign = ir_context->get_type_mgr() + ->GetType(instruction->type_id()) + ->AsInteger() + ->IsSigned(); + + return first_operand_sign == second_operand_sign && + first_operand_sign == type_id_sign; + } +} + protobufs::Transformation TransformationAddBitInstructionSynonym::ToMessage() const { protobufs::Transformation result; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.h b/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.h index ed1a0af50b..40b947a215 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_bit_instruction_synonym.h @@ -103,7 +103,7 @@ namespace fuzz { class TransformationAddBitInstructionSynonym : public Transformation { public: explicit TransformationAddBitInstructionSynonym( - const protobufs::TransformationAddBitInstructionSynonym& message); + protobufs::TransformationAddBitInstructionSynonym message); TransformationAddBitInstructionSynonym( const uint32_t instruction_result_id, @@ -128,6 +128,14 @@ class TransformationAddBitInstructionSynonym : public Transformation { static uint32_t GetRequiredFreshIdCount(opt::IRContext* ir_context, opt::Instruction* bit_instruction); + // Returns true if: + // - A |bit_instruction| is one of OpBitwiseOr, OpBitwiseAnd, OpBitwiseXor or + // OpNot. + // - |bit_instruction|'s operands are scalars. + // - The operands have the same signedness. + static bool IsInstructionSupported(opt::IRContext* ir_context, + opt::Instruction* instruction); + private: protobufs::TransformationAddBitInstructionSynonym message_; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.cpp index 937fdbcc37..3935432577 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationAddConstantBoolean::TransformationAddConstantBoolean( - const protobufs::TransformationAddConstantBoolean& message) - : message_(message) {} + protobufs::TransformationAddConstantBoolean message) + : message_(std::move(message)) {} TransformationAddConstantBoolean::TransformationAddConstantBoolean( uint32_t fresh_id, bool is_true, bool is_irrelevant) { @@ -42,14 +42,18 @@ void TransformationAddConstantBoolean::Apply( TransformationContext* transformation_context) const { // Add the boolean constant to the module, ensuring the module's id bound is // high enough. + auto new_instruction = MakeUnique( + ir_context, message_.is_true() ? SpvOpConstantTrue : SpvOpConstantFalse, + fuzzerutil::MaybeGetBoolType(ir_context), message_.fresh_id(), + opt::Instruction::OperandList()); + auto new_instruction_ptr = new_instruction.get(); + ir_context->module()->AddGlobalValue(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - ir_context->module()->AddGlobalValue( - message_.is_true() ? SpvOpConstantTrue : SpvOpConstantFalse, - message_.fresh_id(), fuzzerutil::MaybeGetBoolType(ir_context)); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + + // Inform the def-use manager about the new instruction. Invalidate the + // constant manager as we have added a new constant. + ir_context->get_def_use_mgr()->AnalyzeInstDef(new_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisConstants); if (message_.is_irrelevant()) { transformation_context->GetFactManager()->AddFactIdIsIrrelevant( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.h b/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.h index d1d04efdc1..7f31471c79 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_boolean.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddConstantBoolean : public Transformation { public: explicit TransformationAddConstantBoolean( - const protobufs::TransformationAddConstantBoolean& message); + protobufs::TransformationAddConstantBoolean message); TransformationAddConstantBoolean(uint32_t fresh_id, bool is_true, bool is_irrelevant); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.cpp index 0260321007..e6cd5a96e3 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.cpp @@ -22,9 +22,8 @@ namespace spvtools { namespace fuzz { TransformationAddConstantComposite::TransformationAddConstantComposite( - const spvtools::fuzz::protobufs::TransformationAddConstantComposite& - message) - : message_(message) {} + spvtools::fuzz::protobufs::TransformationAddConstantComposite message) + : message_(std::move(message)) {} TransformationAddConstantComposite::TransformationAddConstantComposite( uint32_t fresh_id, uint32_t type_id, @@ -120,14 +119,17 @@ void TransformationAddConstantComposite::Apply( for (auto constituent_id : message_.constituent_id()) { in_operands.push_back({SPV_OPERAND_TYPE_ID, {constituent_id}}); } - ir_context->module()->AddGlobalValue(MakeUnique( + auto new_instruction = MakeUnique( ir_context, SpvOpConstantComposite, message_.type_id(), - message_.fresh_id(), in_operands)); + message_.fresh_id(), in_operands); + auto new_instruction_ptr = new_instruction.get(); + ir_context->module()->AddGlobalValue(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + + // Inform the def-use manager of the new instruction. Invalidate the constant + // manager as we have added a new constant. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisConstants); if (message_.is_irrelevant()) { transformation_context->GetFactManager()->AddFactIdIsIrrelevant( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.h b/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.h index 9e9222dcf0..94e7a92702 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_composite.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAddConstantComposite : public Transformation { public: explicit TransformationAddConstantComposite( - const protobufs::TransformationAddConstantComposite& message); + protobufs::TransformationAddConstantComposite message); TransformationAddConstantComposite( uint32_t fresh_id, uint32_t type_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.cpp index 3c66ab10f0..32544e6deb 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddConstantNull::TransformationAddConstantNull( - const spvtools::fuzz::protobufs::TransformationAddConstantNull& message) - : message_(message) {} + spvtools::fuzz::protobufs::TransformationAddConstantNull message) + : message_(std::move(message)) {} TransformationAddConstantNull::TransformationAddConstantNull(uint32_t fresh_id, uint32_t type_id) { @@ -46,14 +46,18 @@ bool TransformationAddConstantNull::IsApplicable( } void TransformationAddConstantNull::Apply( - opt::IRContext* context, TransformationContext* /*unused*/) const { - context->module()->AddGlobalValue(MakeUnique( - context, SpvOpConstantNull, message_.type_id(), message_.fresh_id(), - opt::Instruction::OperandList())); - fuzzerutil::UpdateModuleIdBound(context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - context->InvalidateAnalysesExceptFor(opt::IRContext::Analysis::kAnalysisNone); + opt::IRContext* ir_context, TransformationContext* /*unused*/) const { + auto new_instruction = MakeUnique( + ir_context, SpvOpConstantNull, message_.type_id(), message_.fresh_id(), + opt::Instruction::OperandList()); + auto new_instruction_ptr = new_instruction.get(); + ir_context->module()->AddGlobalValue(std::move(new_instruction)); + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); + + // Inform the def-use manager about the new instruction. Invalidate the + // constant manager as we have added a new constant. + ir_context->get_def_use_mgr()->AnalyzeInstDef(new_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisConstants); } protobufs::Transformation TransformationAddConstantNull::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.h b/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.h index bd08b1da3b..bb1d1b7c6f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_null.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddConstantNull : public Transformation { public: explicit TransformationAddConstantNull( - const protobufs::TransformationAddConstantNull& message); + protobufs::TransformationAddConstantNull message); TransformationAddConstantNull(uint32_t fresh_id, uint32_t type_id); @@ -34,12 +34,12 @@ class TransformationAddConstantNull : public Transformation { // - |message_.type_id| must be the id of a type for which it is acceptable // to create a null constant bool IsApplicable( - opt::IRContext* context, + opt::IRContext* ir_context, const TransformationContext& transformation_context) const override; // Adds an OpConstantNull instruction to the module, with |message_.type_id| // as its type. The instruction has result id |message_.fresh_id|. - void Apply(opt::IRContext* context, + void Apply(opt::IRContext* ir_context, TransformationContext* transformation_context) const override; std::unordered_set GetFreshIds() const override; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.cpp index 9a6642a974..a2d95fb617 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddConstantScalar::TransformationAddConstantScalar( - const spvtools::fuzz::protobufs::TransformationAddConstantScalar& message) - : message_(message) {} + spvtools::fuzz::protobufs::TransformationAddConstantScalar message) + : message_(std::move(message)) {} TransformationAddConstantScalar::TransformationAddConstantScalar( uint32_t fresh_id, uint32_t type_id, const std::vector& words, @@ -64,19 +64,21 @@ bool TransformationAddConstantScalar::IsApplicable( void TransformationAddConstantScalar::Apply( opt::IRContext* ir_context, TransformationContext* transformation_context) const { - ir_context->module()->AddGlobalValue(MakeUnique( + auto new_instruction = MakeUnique( ir_context, SpvOpConstant, message_.type_id(), message_.fresh_id(), opt::Instruction::OperandList( {{SPV_OPERAND_TYPE_LITERAL_INTEGER, std::vector(message_.word().begin(), - message_.word().end())}}))); + message_.word().end())}})); + auto new_instruction_ptr = new_instruction.get(); + ir_context->module()->AddGlobalValue(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // Inform the def-use manager about the new instruction. Invalidate the + // constant manager as we have added a new constant. + ir_context->get_def_use_mgr()->AnalyzeInstDef(new_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisConstants); if (message_.is_irrelevant()) { transformation_context->GetFactManager()->AddFactIdIsIrrelevant( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.h b/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.h index 3f23907c13..adb07355fe 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_constant_scalar.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAddConstantScalar : public Transformation { public: explicit TransformationAddConstantScalar( - const protobufs::TransformationAddConstantScalar& message); + protobufs::TransformationAddConstantScalar message); TransformationAddConstantScalar(uint32_t fresh_id, uint32_t type_id, const std::vector& words, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.cpp index 44bb9c57d8..5eb4bdc014 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.cpp @@ -22,8 +22,8 @@ namespace spvtools { namespace fuzz { TransformationAddCopyMemory::TransformationAddCopyMemory( - const protobufs::TransformationAddCopyMemory& message) - : message_(message) {} + protobufs::TransformationAddCopyMemory message) + : message_(std::move(message)) {} TransformationAddCopyMemory::TransformationAddCopyMemory( const protobufs::InstructionDescriptor& instruction_descriptor, @@ -99,15 +99,8 @@ void TransformationAddCopyMemory::Apply( auto* insert_before_inst = FindInstruction(message_.instruction_descriptor(), ir_context); assert(insert_before_inst); - - auto insert_before_iter = fuzzerutil::GetIteratorForInstruction( - ir_context->get_instr_block(insert_before_inst), insert_before_inst); - - insert_before_iter.InsertBefore(MakeUnique( - ir_context, SpvOpCopyMemory, 0, 0, - opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {message_.fresh_id()}}, - {SPV_OPERAND_TYPE_ID, {message_.source_id()}}})); + opt::BasicBlock* enclosing_block = + ir_context->get_instr_block(insert_before_inst); // Add global or local variable to copy memory into. auto storage_class = static_cast(message_.storage_class()); @@ -118,23 +111,35 @@ void TransformationAddCopyMemory::Apply( storage_class); if (storage_class == SpvStorageClassPrivate) { - fuzzerutil::AddGlobalVariable(ir_context, message_.fresh_id(), type_id, - storage_class, message_.initializer_id()); + opt::Instruction* new_global = + fuzzerutil::AddGlobalVariable(ir_context, message_.fresh_id(), type_id, + storage_class, message_.initializer_id()); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_global); } else { assert(storage_class == SpvStorageClassFunction && "Storage class can be either Private or Function"); - fuzzerutil::AddLocalVariable(ir_context, message_.fresh_id(), type_id, - ir_context->get_instr_block(insert_before_inst) - ->GetParent() - ->result_id(), - message_.initializer_id()); + opt::Function* enclosing_function = enclosing_block->GetParent(); + opt::Instruction* new_local = fuzzerutil::AddLocalVariable( + ir_context, message_.fresh_id(), type_id, + enclosing_function->result_id(), message_.initializer_id()); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_local); + ir_context->set_instr_block(new_local, &*enclosing_function->entry()); } - fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); + auto insert_before_iter = fuzzerutil::GetIteratorForInstruction( + enclosing_block, insert_before_inst); - // Make sure our changes are analyzed - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + auto new_instruction = MakeUnique( + ir_context, SpvOpCopyMemory, 0, 0, + opt::Instruction::OperandList{ + {SPV_OPERAND_TYPE_ID, {message_.fresh_id()}}, + {SPV_OPERAND_TYPE_ID, {message_.source_id()}}}); + auto new_instruction_ptr = new_instruction.get(); + insert_before_iter.InsertBefore(std::move(new_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, enclosing_block); + + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); // Even though the copy memory instruction will - at least temporarily - lead // to the destination and source pointers referring to identical values, this diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.h b/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.h index cc42f1e289..b25652fdd1 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_copy_memory.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddCopyMemory : public Transformation { public: explicit TransformationAddCopyMemory( - const protobufs::TransformationAddCopyMemory& message); + protobufs::TransformationAddCopyMemory message); TransformationAddCopyMemory( const protobufs::InstructionDescriptor& instruction_descriptor, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.cpp index 3d77a8087c..df700ce587 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddDeadBlock::TransformationAddDeadBlock( - const spvtools::fuzz::protobufs::TransformationAddDeadBlock& message) - : message_(message) {} + protobufs::TransformationAddDeadBlock message) + : message_(std::move(message)) {} TransformationAddDeadBlock::TransformationAddDeadBlock(uint32_t fresh_id, uint32_t existing_block, @@ -79,9 +79,7 @@ bool TransformationAddDeadBlock::IsApplicable( } // |existing_block| must be reachable. - opt::DominatorAnalysis* dominator_analysis = - ir_context->GetDominatorAnalysis(existing_block->GetParent()); - if (!dominator_analysis->IsReachable(existing_block->id())) { + if (!ir_context->IsReachable(*existing_block)) { return false; } @@ -94,6 +92,8 @@ bool TransformationAddDeadBlock::IsApplicable( // the selection construct, its header |existing_block| will not dominate the // merge block |successor_block_id|, which is invalid. Thus, |existing_block| // must dominate |successor_block_id|. + opt::DominatorAnalysis* dominator_analysis = + ir_context->GetDominatorAnalysis(existing_block->GetParent()); if (!dominator_analysis->Dominates(existing_block->id(), successor_block_id)) { return false; @@ -153,7 +153,6 @@ void TransformationAddDeadBlock::Apply( : successor_block_id}}}); // Add the new block to the enclosing function. - new_block->SetParent(enclosing_function); enclosing_function->InsertBasicBlockAfter(std::move(new_block), existing_block); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.h b/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.h index 50af6b0ba4..d8b3c2aed2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_dead_block.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddDeadBlock : public Transformation { public: explicit TransformationAddDeadBlock( - const protobufs::TransformationAddDeadBlock& message); + protobufs::TransformationAddDeadBlock message); TransformationAddDeadBlock(uint32_t fresh_id, uint32_t existing_block, bool condition_value); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.cpp index bc938d407b..32080ca4c1 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.cpp @@ -24,8 +24,8 @@ namespace spvtools { namespace fuzz { TransformationAddDeadBreak::TransformationAddDeadBreak( - const spvtools::fuzz::protobufs::TransformationAddDeadBreak& message) - : message_(message) {} + protobufs::TransformationAddDeadBreak message) + : message_(std::move(message)) {} TransformationAddDeadBreak::TransformationAddDeadBreak( uint32_t from_block, uint32_t to_block, bool break_condition_value, @@ -112,9 +112,10 @@ bool TransformationAddDeadBreak::IsApplicable( const TransformationContext& transformation_context) const { // First, we check that a constant with the same value as // |message_.break_condition_value| is present. - if (!fuzzerutil::MaybeGetBoolConstant(ir_context, transformation_context, - message_.break_condition_value(), - false)) { + const auto bool_id = + fuzzerutil::MaybeGetBoolConstant(ir_context, transformation_context, + message_.break_condition_value(), false); + if (!bool_id) { // The required constant is not present, so the transformation cannot be // applied. return false; @@ -133,7 +134,7 @@ bool TransformationAddDeadBreak::IsApplicable( return false; } - if (!fuzzerutil::BlockIsReachableInItsFunction(ir_context, bb_to)) { + if (!ir_context->IsReachable(*bb_to)) { // If the target of the break is unreachable, we conservatively do not // allow adding a dead break, to avoid the compilations that arise due to // the lack of sensible dominance information for unreachable blocks. @@ -171,25 +172,23 @@ bool TransformationAddDeadBreak::IsApplicable( } // Adding the dead break is only valid if SPIR-V rules related to dominance - // hold. Rather than checking these rules explicitly, we defer to the - // validator. We make a clone of the module, apply the transformation to the - // clone, and check whether the transformed clone is valid. - // - // In principle some of the above checks could be removed, with more reliance - // being places on the validator. This should be revisited if we are sure - // the validator is complete with respect to checking structured control flow - // rules. - auto cloned_context = fuzzerutil::CloneIRContext(ir_context); - ApplyImpl(cloned_context.get(), transformation_context); - return fuzzerutil::IsValid(cloned_context.get(), - transformation_context.GetValidatorOptions(), - fuzzerutil::kSilentMessageConsumer); + // hold. + return fuzzerutil::NewTerminatorPreservesDominationRules( + ir_context, message_.from_block(), + fuzzerutil::CreateUnreachableEdgeInstruction( + ir_context, message_.from_block(), message_.to_block(), bool_id)); } void TransformationAddDeadBreak::Apply( opt::IRContext* ir_context, TransformationContext* transformation_context) const { - ApplyImpl(ir_context, *transformation_context); + fuzzerutil::AddUnreachableEdgeAndUpdateOpPhis( + ir_context, ir_context->cfg()->block(message_.from_block()), + ir_context->cfg()->block(message_.to_block()), + fuzzerutil::MaybeGetBoolConstant(ir_context, *transformation_context, + message_.break_condition_value(), false), + message_.phi_id()); + // Invalidate all analyses ir_context->InvalidateAnalysesExceptFor( opt::IRContext::Analysis::kAnalysisNone); @@ -201,17 +200,6 @@ protobufs::Transformation TransformationAddDeadBreak::ToMessage() const { return result; } -void TransformationAddDeadBreak::ApplyImpl( - spvtools::opt::IRContext* ir_context, - const TransformationContext& transformation_context) const { - fuzzerutil::AddUnreachableEdgeAndUpdateOpPhis( - ir_context, ir_context->cfg()->block(message_.from_block()), - ir_context->cfg()->block(message_.to_block()), - fuzzerutil::MaybeGetBoolConstant(ir_context, transformation_context, - message_.break_condition_value(), false), - message_.phi_id()); -} - std::unordered_set TransformationAddDeadBreak::GetFreshIds() const { return std::unordered_set(); } diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.h b/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.h index afb8dc7b7d..8c1ab4a4cb 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_dead_break.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAddDeadBreak : public Transformation { public: explicit TransformationAddDeadBreak( - const protobufs::TransformationAddDeadBreak& message); + protobufs::TransformationAddDeadBreak message); TransformationAddDeadBreak(uint32_t from_block, uint32_t to_block, bool break_condition_value, @@ -71,15 +71,6 @@ class TransformationAddDeadBreak : public Transformation { bool AddingBreakRespectsStructuredControlFlow(opt::IRContext* ir_context, opt::BasicBlock* bb_from) const; - // Used by 'Apply' to actually apply the transformation to the module of - // interest, and by 'IsApplicable' to do a dry-run of the transformation on a - // cloned module, in order to check that the transformation leads to a valid - // module. This is only invoked by 'IsApplicable' after certain basic - // applicability checks have been made, ensuring that the invocation of this - // method is legal. - void ApplyImpl(opt::IRContext* ir_context, - const TransformationContext& transformation_context) const; - protobufs::TransformationAddDeadBreak message_; }; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.cpp index 18b3c39f64..f2b9ab3fdd 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddDeadContinue::TransformationAddDeadContinue( - const spvtools::fuzz::protobufs::TransformationAddDeadContinue& message) - : message_(message) {} + protobufs::TransformationAddDeadContinue message) + : message_(std::move(message)) {} TransformationAddDeadContinue::TransformationAddDeadContinue( uint32_t from_block, bool continue_condition_value, @@ -38,9 +38,10 @@ bool TransformationAddDeadContinue::IsApplicable( const TransformationContext& transformation_context) const { // First, we check that a constant with the same value as // |message_.continue_condition_value| is present. - if (!fuzzerutil::MaybeGetBoolConstant(ir_context, transformation_context, - message_.continue_condition_value(), - false)) { + const auto bool_id = fuzzerutil::MaybeGetBoolConstant( + ir_context, transformation_context, message_.continue_condition_value(), + false); + if (!bool_id) { // The required constant is not present, so the transformation cannot be // applied. return false; @@ -82,8 +83,7 @@ bool TransformationAddDeadContinue::IsApplicable( auto continue_block = ir_context->cfg()->block(loop_header)->ContinueBlockId(); - if (!fuzzerutil::BlockIsReachableInItsFunction( - ir_context, ir_context->cfg()->block(continue_block))) { + if (!ir_context->IsReachable(*ir_context->cfg()->block(continue_block))) { // If the loop's continue block is unreachable, we conservatively do not // allow adding a dead continue, to avoid the compilations that arise due to // the lack of sensible dominance information for unreachable blocks. @@ -111,25 +111,30 @@ bool TransformationAddDeadContinue::IsApplicable( } // Adding the dead break is only valid if SPIR-V rules related to dominance - // hold. Rather than checking these rules explicitly, we defer to the - // validator. We make a clone of the module, apply the transformation to the - // clone, and check whether the transformed clone is valid. - // - // In principle some of the above checks could be removed, with more reliance - // being placed on the validator. This should be revisited if we are sure - // the validator is complete with respect to checking structured control flow - // rules. - auto cloned_context = fuzzerutil::CloneIRContext(ir_context); - ApplyImpl(cloned_context.get(), transformation_context); - return fuzzerutil::IsValid(cloned_context.get(), - transformation_context.GetValidatorOptions(), - fuzzerutil::kSilentMessageConsumer); + // hold. + return fuzzerutil::NewTerminatorPreservesDominationRules( + ir_context, message_.from_block(), + fuzzerutil::CreateUnreachableEdgeInstruction( + ir_context, message_.from_block(), continue_block, bool_id)); } void TransformationAddDeadContinue::Apply( opt::IRContext* ir_context, TransformationContext* transformation_context) const { - ApplyImpl(ir_context, *transformation_context); + auto bb_from = ir_context->cfg()->block(message_.from_block()); + auto continue_block = + bb_from->IsLoopHeader() + ? bb_from->ContinueBlockId() + : ir_context->GetStructuredCFGAnalysis()->LoopContinueBlock( + message_.from_block()); + assert(continue_block && "message_.from_block must be in a loop."); + fuzzerutil::AddUnreachableEdgeAndUpdateOpPhis( + ir_context, bb_from, ir_context->cfg()->block(continue_block), + fuzzerutil::MaybeGetBoolConstant(ir_context, *transformation_context, + message_.continue_condition_value(), + false), + message_.phi_id()); + // Invalidate all analyses ir_context->InvalidateAnalysesExceptFor( opt::IRContext::Analysis::kAnalysisNone); @@ -141,24 +146,6 @@ protobufs::Transformation TransformationAddDeadContinue::ToMessage() const { return result; } -void TransformationAddDeadContinue::ApplyImpl( - spvtools::opt::IRContext* ir_context, - const TransformationContext& transformation_context) const { - auto bb_from = ir_context->cfg()->block(message_.from_block()); - auto continue_block = - bb_from->IsLoopHeader() - ? bb_from->ContinueBlockId() - : ir_context->GetStructuredCFGAnalysis()->LoopContinueBlock( - message_.from_block()); - assert(continue_block && "message_.from_block must be in a loop."); - fuzzerutil::AddUnreachableEdgeAndUpdateOpPhis( - ir_context, bb_from, ir_context->cfg()->block(continue_block), - fuzzerutil::MaybeGetBoolConstant(ir_context, transformation_context, - message_.continue_condition_value(), - false), - message_.phi_id()); -} - std::unordered_set TransformationAddDeadContinue::GetFreshIds() const { return std::unordered_set(); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.h b/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.h index 27527e785e..9463aebc42 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_dead_continue.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAddDeadContinue : public Transformation { public: explicit TransformationAddDeadContinue( - const protobufs::TransformationAddDeadContinue& message); + protobufs::TransformationAddDeadContinue message); TransformationAddDeadContinue(uint32_t from_block, bool continue_condition_value, @@ -68,15 +68,6 @@ class TransformationAddDeadContinue : public Transformation { protobufs::Transformation ToMessage() const override; private: - // Used by 'Apply' to actually apply the transformation to the module of - // interest, and by 'IsApplicable' to do a dry-run of the transformation on a - // cloned module, in order to check that the transformation leads to a valid - // module. This is only invoked by 'IsApplicable' after certain basic - // applicability checks have been made, ensuring that the invocation of this - // method is legal. - void ApplyImpl(opt::IRContext* ir_context, - const TransformationContext& transformation_context) const; - protobufs::TransformationAddDeadContinue message_; }; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.cpp index 0aa1214b70..547398aa38 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationAddEarlyTerminatorWrapper:: TransformationAddEarlyTerminatorWrapper( - const spvtools::fuzz::protobufs:: - TransformationAddEarlyTerminatorWrapper& message) - : message_(message) {} + protobufs::TransformationAddEarlyTerminatorWrapper message) + : message_(std::move(message)) {} TransformationAddEarlyTerminatorWrapper:: TransformationAddEarlyTerminatorWrapper(uint32_t function_fresh_id, @@ -84,7 +83,6 @@ void TransformationAddEarlyTerminatorWrapper::Apply( // Add the basic block to the function as the sole block, and add the function // to the module. - basic_block->SetParent(function.get()); function->AddBasicBlock(std::move(basic_block)); function->SetFunctionEnd(MakeUnique( ir_context, SpvOpFunctionEnd, 0, 0, opt::Instruction::OperandList())); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.h b/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.h index 273037e509..97cc527cf6 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_early_terminator_wrapper.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddEarlyTerminatorWrapper : public Transformation { public: explicit TransformationAddEarlyTerminatorWrapper( - const protobufs::TransformationAddEarlyTerminatorWrapper& message); + protobufs::TransformationAddEarlyTerminatorWrapper message); TransformationAddEarlyTerminatorWrapper(uint32_t function_fresh_id, uint32_t label_fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_function.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_function.cpp index 214f741af2..06cd657241 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_function.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_function.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationAddFunction::TransformationAddFunction( - const spvtools::fuzz::protobufs::TransformationAddFunction& message) - : message_(message) {} + protobufs::TransformationAddFunction message) + : message_(std::move(message)) {} TransformationAddFunction::TransformationAddFunction( const std::vector& instructions) { @@ -276,12 +276,10 @@ bool TransformationAddFunction::TryToAddFunction( // Invariant: we should always be at a label instruction at this point. assert(message_.instruction(instruction_index).opcode() == SpvOpLabel); - // Make a basic block using the label instruction, with the new function - // as its parent. + // Make a basic block using the label instruction. std::unique_ptr block = MakeUnique(InstructionFromMessage( ir_context, message_.instruction(instruction_index))); - block->SetParent(new_function.get()); // Consider successive instructions until we hit another label or the end // of the function, adding each such instruction to the block. diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_function.h b/third_party/spirv-tools/source/fuzz/transformation_add_function.h index e5381d14c8..c41eee3302 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_function.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_function.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddFunction : public Transformation { public: explicit TransformationAddFunction( - const protobufs::TransformationAddFunction& message); + protobufs::TransformationAddFunction message); // Creates a transformation to add a non live-safe function. explicit TransformationAddFunction( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.cpp index 7a90b821f3..eb390ea0df 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddGlobalUndef::TransformationAddGlobalUndef( - const spvtools::fuzz::protobufs::TransformationAddGlobalUndef& message) - : message_(message) {} + spvtools::fuzz::protobufs::TransformationAddGlobalUndef message) + : message_(std::move(message)) {} TransformationAddGlobalUndef::TransformationAddGlobalUndef(uint32_t fresh_id, uint32_t type_id) { @@ -42,14 +42,14 @@ bool TransformationAddGlobalUndef::IsApplicable( void TransformationAddGlobalUndef::Apply( opt::IRContext* ir_context, TransformationContext* /*unused*/) const { - ir_context->module()->AddGlobalValue(MakeUnique( + auto new_instruction = MakeUnique( ir_context, SpvOpUndef, message_.type_id(), message_.fresh_id(), - opt::Instruction::OperandList())); + opt::Instruction::OperandList()); + auto new_instruction_ptr = new_instruction.get(); + ir_context->module()->AddGlobalValue(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // Inform the def-use manager about the new instruction. + ir_context->get_def_use_mgr()->AnalyzeInstDef(new_instruction_ptr); } protobufs::Transformation TransformationAddGlobalUndef::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.h b/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.h index 717dc9ad19..37542c3fda 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_global_undef.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddGlobalUndef : public Transformation { public: explicit TransformationAddGlobalUndef( - const protobufs::TransformationAddGlobalUndef& message); + protobufs::TransformationAddGlobalUndef message); TransformationAddGlobalUndef(uint32_t fresh_id, uint32_t type_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.cpp index dd04e48a8a..814d01b344 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddGlobalVariable::TransformationAddGlobalVariable( - const spvtools::fuzz::protobufs::TransformationAddGlobalVariable& message) - : message_(message) {} + spvtools::fuzz::protobufs::TransformationAddGlobalVariable message) + : message_(std::move(message)) {} TransformationAddGlobalVariable::TransformationAddGlobalVariable( uint32_t fresh_id, uint32_t type_id, SpvStorageClass storage_class, @@ -93,15 +93,13 @@ bool TransformationAddGlobalVariable::IsApplicable( void TransformationAddGlobalVariable::Apply( opt::IRContext* ir_context, TransformationContext* transformation_context) const { - fuzzerutil::AddGlobalVariable( + opt::Instruction* new_instruction = fuzzerutil::AddGlobalVariable( ir_context, message_.fresh_id(), message_.type_id(), static_cast(message_.storage_class()), message_.initializer_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // Inform the def-use manager about the new instruction. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction); if (message_.value_is_irrelevant()) { transformation_context->GetFactManager()->AddFactValueOfPointeeIsIrrelevant( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.h b/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.h index 8d46edb788..d74d48a2db 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_global_variable.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddGlobalVariable : public Transformation { public: explicit TransformationAddGlobalVariable( - const protobufs::TransformationAddGlobalVariable& message); + protobufs::TransformationAddGlobalVariable message); TransformationAddGlobalVariable(uint32_t fresh_id, uint32_t type_id, SpvStorageClass storage_class, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.cpp index ab48f0b646..1ead82bc95 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationAddImageSampleUnusedComponents:: TransformationAddImageSampleUnusedComponents( - const spvtools::fuzz::protobufs:: - TransformationAddImageSampleUnusedComponents& message) - : message_(message) {} + protobufs::TransformationAddImageSampleUnusedComponents message) + : message_(std::move(message)) {} TransformationAddImageSampleUnusedComponents:: TransformationAddImageSampleUnusedComponents( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.h b/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.h index 7486c76059..7b13f9f6d5 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_image_sample_unused_components.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddImageSampleUnusedComponents : public Transformation { public: explicit TransformationAddImageSampleUnusedComponents( - const protobufs::TransformationAddImageSampleUnusedComponents& message); + protobufs::TransformationAddImageSampleUnusedComponents message); TransformationAddImageSampleUnusedComponents( uint32_t coordinate_with_unused_components_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.cpp index 0a7a3dac7d..21768d2239 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddLocalVariable::TransformationAddLocalVariable( - const spvtools::fuzz::protobufs::TransformationAddLocalVariable& message) - : message_(message) {} + spvtools::fuzz::protobufs::TransformationAddLocalVariable message) + : message_(std::move(message)) {} TransformationAddLocalVariable::TransformationAddLocalVariable( uint32_t fresh_id, uint32_t type_id, uint32_t function_id, @@ -70,11 +70,17 @@ bool TransformationAddLocalVariable::IsApplicable( void TransformationAddLocalVariable::Apply( opt::IRContext* ir_context, TransformationContext* transformation_context) const { - fuzzerutil::AddLocalVariable(ir_context, message_.fresh_id(), - message_.type_id(), message_.function_id(), - message_.initializer_id()); + opt::Instruction* new_instruction = fuzzerutil::AddLocalVariable( + ir_context, message_.fresh_id(), message_.type_id(), + message_.function_id(), message_.initializer_id()); - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + // Inform the def-use manager about the new instruction. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction); + ir_context->set_instr_block( + new_instruction, + fuzzerutil::FindFunction(ir_context, message_.function_id()) + ->entry() + .get()); if (message_.value_is_irrelevant()) { transformation_context->GetFactManager()->AddFactValueOfPointeeIsIrrelevant( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.h b/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.h index 963079f536..b008a1c0fa 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_local_variable.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddLocalVariable : public Transformation { public: explicit TransformationAddLocalVariable( - const protobufs::TransformationAddLocalVariable& message); + protobufs::TransformationAddLocalVariable message); TransformationAddLocalVariable(uint32_t fresh_id, uint32_t type_id, uint32_t function_id, uint32_t initializer_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.cpp index 3d50fa924d..71ab18da7c 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddLoopPreheader::TransformationAddLoopPreheader( - const protobufs::TransformationAddLoopPreheader& message) - : message_(message) {} + protobufs::TransformationAddLoopPreheader message) + : message_(std::move(message)) {} TransformationAddLoopPreheader::TransformationAddLoopPreheader( uint32_t loop_header_block, uint32_t fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.h b/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.h index 05448f3fa0..9d2c565fea 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_loop_preheader.h @@ -23,7 +23,7 @@ namespace fuzz { class TransformationAddLoopPreheader : public Transformation { public: explicit TransformationAddLoopPreheader( - const protobufs::TransformationAddLoopPreheader& message); + protobufs::TransformationAddLoopPreheader message); TransformationAddLoopPreheader(uint32_t loop_header_block, uint32_t fresh_id, std::vector phi_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.cpp index 45d3fc8571..657fafa4d4 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.cpp @@ -23,9 +23,8 @@ uint32_t kMaxNumOfIterations = 32; TransformationAddLoopToCreateIntConstantSynonym:: TransformationAddLoopToCreateIntConstantSynonym( - const protobufs::TransformationAddLoopToCreateIntConstantSynonym& - message) - : message_(message) {} + protobufs::TransformationAddLoopToCreateIntConstantSynonym message) + : message_(std::move(message)) {} TransformationAddLoopToCreateIntConstantSynonym:: TransformationAddLoopToCreateIntConstantSynonym( diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.h b/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.h index 67c3bcd289..a6dfe63a50 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_loop_to_create_int_constant_synonym.h @@ -22,8 +22,7 @@ namespace fuzz { class TransformationAddLoopToCreateIntConstantSynonym : public Transformation { public: explicit TransformationAddLoopToCreateIntConstantSynonym( - const protobufs::TransformationAddLoopToCreateIntConstantSynonym& - message); + protobufs::TransformationAddLoopToCreateIntConstantSynonym message); TransformationAddLoopToCreateIntConstantSynonym( uint32_t constant_id, uint32_t initial_val_id, uint32_t step_val_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.cpp index 29a871df94..992a216bc1 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.cpp @@ -21,9 +21,8 @@ namespace fuzz { TransformationAddNoContractionDecoration:: TransformationAddNoContractionDecoration( - const spvtools::fuzz::protobufs:: - TransformationAddNoContractionDecoration& message) - : message_(message) {} + protobufs::TransformationAddNoContractionDecoration message) + : message_(std::move(message)) {} TransformationAddNoContractionDecoration:: TransformationAddNoContractionDecoration(uint32_t result_id) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.h b/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.h index f5a34e819e..2f78d4298d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_no_contraction_decoration.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddNoContractionDecoration : public Transformation { public: explicit TransformationAddNoContractionDecoration( - const protobufs::TransformationAddNoContractionDecoration& message); + protobufs::TransformationAddNoContractionDecoration message); explicit TransformationAddNoContractionDecoration(uint32_t fresh_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.cpp index 227c4338df..3c4698a793 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.cpp @@ -19,8 +19,8 @@ namespace spvtools { namespace fuzz { TransformationAddOpPhiSynonym::TransformationAddOpPhiSynonym( - const protobufs::TransformationAddOpPhiSynonym& message) - : message_(message) {} + protobufs::TransformationAddOpPhiSynonym message) + : message_(std::move(message)) {} TransformationAddOpPhiSynonym::TransformationAddOpPhiSynonym( uint32_t block_id, const std::map& preds_to_ids, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.h b/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.h index 3b68abeee7..39ebea8985 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_opphi_synonym.h @@ -22,7 +22,7 @@ namespace fuzz { class TransformationAddOpPhiSynonym : public Transformation { public: explicit TransformationAddOpPhiSynonym( - const protobufs::TransformationAddOpPhiSynonym& message); + protobufs::TransformationAddOpPhiSynonym message); TransformationAddOpPhiSynonym( uint32_t block_id, const std::map& preds_to_ids, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_parameter.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_parameter.cpp index 9ed0bfb46e..48de3e839b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_parameter.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_parameter.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddParameter::TransformationAddParameter( - const protobufs::TransformationAddParameter& message) - : message_(message) {} + protobufs::TransformationAddParameter message) + : message_(std::move(message)) {} TransformationAddParameter::TransformationAddParameter( uint32_t function_id, uint32_t parameter_fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_parameter.h b/third_party/spirv-tools/source/fuzz/transformation_add_parameter.h index a33521da17..0bc096e7d2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_parameter.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_parameter.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddParameter : public Transformation { public: explicit TransformationAddParameter( - const protobufs::TransformationAddParameter& message); + protobufs::TransformationAddParameter message); TransformationAddParameter(uint32_t function_id, uint32_t parameter_fresh_id, uint32_t parameter_type_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.cpp index 7b51305391..b66a1a833d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.cpp @@ -20,9 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddRelaxedDecoration::TransformationAddRelaxedDecoration( - const spvtools::fuzz::protobufs::TransformationAddRelaxedDecoration& - message) - : message_(message) {} + protobufs::TransformationAddRelaxedDecoration message) + : message_(std::move(message)) {} TransformationAddRelaxedDecoration::TransformationAddRelaxedDecoration( uint32_t result_id) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.h b/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.h index 3f8bf3edb1..c01634979b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_relaxed_decoration.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddRelaxedDecoration : public Transformation { public: explicit TransformationAddRelaxedDecoration( - const protobufs::TransformationAddRelaxedDecoration& message); + protobufs::TransformationAddRelaxedDecoration message); explicit TransformationAddRelaxedDecoration(uint32_t fresh_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_synonym.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_synonym.cpp index a516916bd9..a1949fbcea 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_synonym.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_synonym.cpp @@ -102,14 +102,19 @@ void TransformationAddSynonym::Apply( opt::IRContext* ir_context, TransformationContext* transformation_context) const { // Add a synonymous instruction. - FindInstruction(message_.insert_before(), ir_context) - ->InsertBefore( - MakeSynonymousInstruction(ir_context, *transformation_context)); + auto new_instruction = + MakeSynonymousInstruction(ir_context, *transformation_context); + auto new_instruction_ptr = new_instruction.get(); + auto insert_before = FindInstruction(message_.insert_before(), ir_context); + insert_before->InsertBefore(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.synonym_fresh_id()); - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // Inform the def-use manager about the new instruction and record its basic + // block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, + ir_context->get_instr_block(insert_before)); // Propagate PointeeValueIsIrrelevant fact. const auto* new_synonym_type = ir_context->get_type_mgr()->GetType( @@ -165,6 +170,18 @@ bool TransformationAddSynonym::IsInstructionValid( return type->AsInteger() || type->AsFloat(); } + case protobufs::TransformationAddSynonym::BITWISE_OR: + case protobufs::TransformationAddSynonym::BITWISE_XOR: { + // The instruction must be either an integer or a vector of integers. + const auto* type = ir_context->get_type_mgr()->GetType(inst->type_id()); + assert(type && "Instruction's result id is invalid"); + + if (const auto* vector = type->AsVector()) { + return vector->element_type()->AsInteger(); + } + + return type->AsInteger(); + } case protobufs::TransformationAddSynonym::COPY_OBJECT: // All checks for OpCopyObject are handled by // fuzzerutil::CanMakeSynonymOf. @@ -190,68 +207,56 @@ TransformationAddSynonym::MakeSynonymousInstruction( auto synonym_type_id = fuzzerutil::GetTypeId(ir_context, message_.result_id()); assert(synonym_type_id && "Synonym has invalid type id"); + auto opcode = SpvOpNop; + const auto* synonym_type = + ir_context->get_type_mgr()->GetType(synonym_type_id); + assert(synonym_type && "Synonym has invalid type"); + + auto is_integral = (synonym_type->AsVector() && + synonym_type->AsVector()->element_type()->AsInteger()) || + synonym_type->AsInteger(); switch (message_.synonym_type()) { case protobufs::TransformationAddSynonym::SUB_ZERO: + opcode = is_integral ? SpvOpISub : SpvOpFSub; + break; case protobufs::TransformationAddSynonym::MUL_ONE: - case protobufs::TransformationAddSynonym::ADD_ZERO: { - const auto* synonym_type = - ir_context->get_type_mgr()->GetType(synonym_type_id); - assert(synonym_type && "Synonym has invalid type"); + opcode = is_integral ? SpvOpIMul : SpvOpFMul; + break; + case protobufs::TransformationAddSynonym::ADD_ZERO: + opcode = is_integral ? SpvOpIAdd : SpvOpFAdd; + break; + case protobufs::TransformationAddSynonym::LOGICAL_OR: + opcode = SpvOpLogicalOr; + break; + case protobufs::TransformationAddSynonym::LOGICAL_AND: + opcode = SpvOpLogicalAnd; + break; + case protobufs::TransformationAddSynonym::BITWISE_OR: + opcode = SpvOpBitwiseOr; + break; + case protobufs::TransformationAddSynonym::BITWISE_XOR: + opcode = SpvOpBitwiseXor; + break; - // Compute instruction's opcode based on the type of the operand. - // We have already checked that the operand is either a scalar or a vector - // of either integers or floats. - auto is_integral = - (synonym_type->AsVector() && - synonym_type->AsVector()->element_type()->AsInteger()) || - synonym_type->AsInteger(); - auto opcode = SpvOpNop; - switch (message_.synonym_type()) { - case protobufs::TransformationAddSynonym::SUB_ZERO: - opcode = is_integral ? SpvOpISub : SpvOpFSub; - break; - case protobufs::TransformationAddSynonym::MUL_ONE: - opcode = is_integral ? SpvOpIMul : SpvOpFMul; - break; - case protobufs::TransformationAddSynonym::ADD_ZERO: - opcode = is_integral ? SpvOpIAdd : SpvOpFAdd; - break; - default: - assert(false && "Unreachable"); - break; - } - - return MakeUnique( - ir_context, opcode, synonym_type_id, message_.synonym_fresh_id(), - opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {message_.result_id()}}, - {SPV_OPERAND_TYPE_ID, - {MaybeGetConstantId(ir_context, transformation_context)}}}); - } case protobufs::TransformationAddSynonym::COPY_OBJECT: return MakeUnique( ir_context, SpvOpCopyObject, synonym_type_id, message_.synonym_fresh_id(), opt::Instruction::OperandList{ {SPV_OPERAND_TYPE_ID, {message_.result_id()}}}); - case protobufs::TransformationAddSynonym::LOGICAL_OR: - case protobufs::TransformationAddSynonym::LOGICAL_AND: { - auto opcode = message_.synonym_type() == - protobufs::TransformationAddSynonym::LOGICAL_OR - ? SpvOpLogicalOr - : SpvOpLogicalAnd; - return MakeUnique( - ir_context, opcode, synonym_type_id, message_.synonym_fresh_id(), - opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {message_.result_id()}}, - {SPV_OPERAND_TYPE_ID, - {MaybeGetConstantId(ir_context, transformation_context)}}}); - } + default: assert(false && "Unhandled synonym type"); return nullptr; } + + return MakeUnique( + ir_context, opcode, synonym_type_id, message_.synonym_fresh_id(), + opt::Instruction::OperandList{ + {SPV_OPERAND_TYPE_ID, {message_.result_id()}}, + {SPV_OPERAND_TYPE_ID, + {MaybeGetConstantId(ir_context, transformation_context)}}}); } uint32_t TransformationAddSynonym::MaybeGetConstantId( @@ -268,6 +273,8 @@ uint32_t TransformationAddSynonym::MaybeGetConstantId( case protobufs::TransformationAddSynonym::ADD_ZERO: case protobufs::TransformationAddSynonym::SUB_ZERO: case protobufs::TransformationAddSynonym::LOGICAL_OR: + case protobufs::TransformationAddSynonym::BITWISE_OR: + case protobufs::TransformationAddSynonym::BITWISE_XOR: return fuzzerutil::MaybeGetZeroConstant( ir_context, transformation_context, synonym_type_id, false); case protobufs::TransformationAddSynonym::MUL_ONE: @@ -314,6 +321,8 @@ bool TransformationAddSynonym::IsAdditionalConstantRequired( case protobufs::TransformationAddSynonym::LOGICAL_OR: case protobufs::TransformationAddSynonym::MUL_ONE: case protobufs::TransformationAddSynonym::LOGICAL_AND: + case protobufs::TransformationAddSynonym::BITWISE_OR: + case protobufs::TransformationAddSynonym::BITWISE_XOR: return true; default: return false; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_array.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_array.cpp index c9f6a87a39..45bc8dfe9a 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_array.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_array.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeArray::TransformationAddTypeArray( - const spvtools::fuzz::protobufs::TransformationAddTypeArray& message) - : message_(message) {} + protobufs::TransformationAddTypeArray message) + : message_(std::move(message)) {} TransformationAddTypeArray::TransformationAddTypeArray(uint32_t fresh_id, uint32_t element_type_id, @@ -39,9 +39,11 @@ bool TransformationAddTypeArray::IsApplicable( } auto element_type = ir_context->get_type_mgr()->GetType(message_.element_type_id()); - if (!element_type || element_type->AsFunction()) { - // The element type id either does not refer to a type, or refers to a - // function type; both are illegal. + if (!element_type || element_type->AsFunction() || + fuzzerutil::HasBlockOrBufferBlockDecoration(ir_context, + message_.element_type_id())) { + // The element type id either does not refer to a type, refers to a function + // type, or refers to a block-decorated struct. These cases are all illegal. return false; } auto constant = @@ -69,13 +71,17 @@ void TransformationAddTypeArray::Apply( opt::Instruction::OperandList in_operands; in_operands.push_back({SPV_OPERAND_TYPE_ID, {message_.element_type_id()}}); in_operands.push_back({SPV_OPERAND_TYPE_ID, {message_.size_id()}}); - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypeArray, 0, message_.fresh_id(), in_operands)); + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeArray, 0, message_.fresh_id(), in_operands); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeArray::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_array.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_array.h index ebefc2379c..3162497a69 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_array.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_array.h @@ -26,15 +26,17 @@ namespace fuzz { class TransformationAddTypeArray : public Transformation { public: explicit TransformationAddTypeArray( - const protobufs::TransformationAddTypeArray& message); + protobufs::TransformationAddTypeArray message); TransformationAddTypeArray(uint32_t fresh_id, uint32_t element_type_id, uint32_t size_id); // - |message_.fresh_id| must be fresh // - |message_.element_type_id| must be the id of a non-function type + // - |message_.member_type_id| must not be the result id of an OpTypeStruct + // instruction that has the Block or BufferBlock decoration // - |message_.size_id| must be the id of a 32-bit integer constant that is - // positive when interpreted as signed. + // positive when interpreted as signed bool IsApplicable( opt::IRContext* ir_context, const TransformationContext& transformation_context) const override; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.cpp index ebbfabc815..30ff43e249 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeBoolean::TransformationAddTypeBoolean( - const spvtools::fuzz::protobufs::TransformationAddTypeBoolean& message) - : message_(message) {} + protobufs::TransformationAddTypeBoolean message) + : message_(std::move(message)) {} TransformationAddTypeBoolean::TransformationAddTypeBoolean(uint32_t fresh_id) { message_.set_fresh_id(fresh_id); @@ -42,13 +42,17 @@ bool TransformationAddTypeBoolean::IsApplicable( void TransformationAddTypeBoolean::Apply( opt::IRContext* ir_context, TransformationContext* /*unused*/) const { opt::Instruction::OperandList empty_operands; - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypeBool, 0, message_.fresh_id(), empty_operands)); + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeBool, 0, message_.fresh_id(), empty_operands); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeBoolean::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.h index 25c92727a5..ee6401536c 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_boolean.h @@ -25,7 +25,7 @@ namespace fuzz { class TransformationAddTypeBoolean : public Transformation { public: explicit TransformationAddTypeBoolean( - const protobufs::TransformationAddTypeBoolean& message); + protobufs::TransformationAddTypeBoolean message); explicit TransformationAddTypeBoolean(uint32_t fresh_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_float.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_float.cpp index da3f3e4e26..1b88b25cec 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_float.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_float.cpp @@ -26,8 +26,8 @@ TransformationAddTypeFloat::TransformationAddTypeFloat(uint32_t fresh_id, } TransformationAddTypeFloat::TransformationAddTypeFloat( - const spvtools::fuzz::protobufs::TransformationAddTypeFloat& message) - : message_(message) {} + protobufs::TransformationAddTypeFloat message) + : message_(std::move(message)) {} bool TransformationAddTypeFloat::IsApplicable( opt::IRContext* ir_context, const TransformationContext& /*unused*/) const { @@ -65,11 +65,18 @@ bool TransformationAddTypeFloat::IsApplicable( void TransformationAddTypeFloat::Apply( opt::IRContext* ir_context, TransformationContext* /*unused*/) const { - fuzzerutil::AddFloatType(ir_context, message_.fresh_id(), message_.width()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeFloat, 0, message_.fresh_id(), + opt::Instruction::OperandList{ + {SPV_OPERAND_TYPE_LITERAL_INTEGER, {message_.width()}}}); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); + + // Inform the def use manager that there is a new definition, and invalidate + // the type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeFloat::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_float.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_float.h index 30cd0fc6db..e049d9a0ea 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_float.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_float.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddTypeFloat : public Transformation { public: explicit TransformationAddTypeFloat( - const protobufs::TransformationAddTypeFloat& message); + protobufs::TransformationAddTypeFloat message); TransformationAddTypeFloat(uint32_t fresh_id, uint32_t width); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_function.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_function.cpp index b6cddfc02f..e96067f20d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_function.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_function.cpp @@ -22,8 +22,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeFunction::TransformationAddTypeFunction( - const spvtools::fuzz::protobufs::TransformationAddTypeFunction& message) - : message_(message) {} + protobufs::TransformationAddTypeFunction message) + : message_(std::move(message)) {} TransformationAddTypeFunction::TransformationAddTypeFunction( uint32_t fresh_id, uint32_t return_type_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_function.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_function.h index 59ded2b338..7104457953 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_function.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_function.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAddTypeFunction : public Transformation { public: explicit TransformationAddTypeFunction( - const protobufs::TransformationAddTypeFunction& message); + protobufs::TransformationAddTypeFunction message); TransformationAddTypeFunction(uint32_t fresh_id, uint32_t return_type_id, const std::vector& argument_type_ids); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_int.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_int.cpp index 253ea15b4b..d4ef981912 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_int.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_int.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeInt::TransformationAddTypeInt( - const spvtools::fuzz::protobufs::TransformationAddTypeInt& message) - : message_(message) {} + protobufs::TransformationAddTypeInt message) + : message_(std::move(message)) {} TransformationAddTypeInt::TransformationAddTypeInt(uint32_t fresh_id, uint32_t width, @@ -74,12 +74,21 @@ bool TransformationAddTypeInt::IsApplicable( void TransformationAddTypeInt::Apply(opt::IRContext* ir_context, TransformationContext* /*unused*/) const { - fuzzerutil::AddIntegerType(ir_context, message_.fresh_id(), message_.width(), - message_.is_signed()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeInt, 0, message_.fresh_id(), + opt::Instruction::OperandList{ + {SPV_OPERAND_TYPE_LITERAL_INTEGER, {message_.width()}}, + {SPV_OPERAND_TYPE_LITERAL_INTEGER, + {message_.is_signed() ? 1u : 0u}}}); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeInt::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_int.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_int.h index 20c90ca455..dc67b7dc84 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_int.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_int.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddTypeInt : public Transformation { public: explicit TransformationAddTypeInt( - const protobufs::TransformationAddTypeInt& message); + protobufs::TransformationAddTypeInt message); TransformationAddTypeInt(uint32_t fresh_id, uint32_t width, bool is_signed); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.cpp index cecebb41e0..b574b01b41 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeMatrix::TransformationAddTypeMatrix( - const spvtools::fuzz::protobufs::TransformationAddTypeMatrix& message) - : message_(message) {} + protobufs::TransformationAddTypeMatrix message) + : message_(std::move(message)) {} TransformationAddTypeMatrix::TransformationAddTypeMatrix( uint32_t fresh_id, uint32_t column_type_id, uint32_t column_count) { @@ -52,13 +52,17 @@ void TransformationAddTypeMatrix::Apply( in_operands.push_back({SPV_OPERAND_TYPE_ID, {message_.column_type_id()}}); in_operands.push_back( {SPV_OPERAND_TYPE_LITERAL_INTEGER, {message_.column_count()}}); - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypeMatrix, 0, message_.fresh_id(), in_operands)); + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeMatrix, 0, message_.fresh_id(), in_operands); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeMatrix::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.h index f1d416565c..b4788b1b66 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_matrix.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddTypeMatrix : public Transformation { public: explicit TransformationAddTypeMatrix( - const protobufs::TransformationAddTypeMatrix& message); + protobufs::TransformationAddTypeMatrix message); TransformationAddTypeMatrix(uint32_t fresh_id, uint32_t column_type_id, uint32_t column_count); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.cpp index f74768d68a..c6c3945b3f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypePointer::TransformationAddTypePointer( - const spvtools::fuzz::protobufs::TransformationAddTypePointer& message) - : message_(message) {} + protobufs::TransformationAddTypePointer message) + : message_(std::move(message)) {} TransformationAddTypePointer::TransformationAddTypePointer( uint32_t fresh_id, SpvStorageClass storage_class, uint32_t base_type_id) { @@ -47,13 +47,17 @@ void TransformationAddTypePointer::Apply( opt::Instruction::OperandList in_operands = { {SPV_OPERAND_TYPE_STORAGE_CLASS, {message_.storage_class()}}, {SPV_OPERAND_TYPE_ID, {message_.base_type_id()}}}; - ir_context->module()->AddType(MakeUnique( - ir_context, SpvOpTypePointer, 0, message_.fresh_id(), in_operands)); + auto type_instruction = MakeUnique( + ir_context, SpvOpTypePointer, 0, message_.fresh_id(), in_operands); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypePointer::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.h index 3f686e977e..8468c14d8e 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_pointer.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddTypePointer : public Transformation { public: explicit TransformationAddTypePointer( - const protobufs::TransformationAddTypePointer& message); + protobufs::TransformationAddTypePointer message); TransformationAddTypePointer(uint32_t fresh_id, SpvStorageClass storage_class, uint32_t base_type_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.cpp index b20ffb0032..d7f0711eb0 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeStruct::TransformationAddTypeStruct( - const spvtools::fuzz::protobufs::TransformationAddTypeStruct& message) - : message_(message) {} + protobufs::TransformationAddTypeStruct message) + : message_(std::move(message)) {} TransformationAddTypeStruct::TransformationAddTypeStruct( uint32_t fresh_id, const std::vector& member_type_ids) { @@ -39,9 +39,11 @@ bool TransformationAddTypeStruct::IsApplicable( } for (auto member_type : message_.member_type_id()) { auto type = ir_context->get_type_mgr()->GetType(member_type); - if (!type || type->AsFunction()) { - // The member type id either does not refer to a type, or refers to a - // function type; both are illegal. + if (!type || type->AsFunction() || + fuzzerutil::HasBlockOrBufferBlockDecoration(ir_context, member_type)) { + // The member type id either does not refer to a type, refers to a + // function type, or refers to a block-decorated struct. These cases are + // all illegal. return false; } @@ -58,14 +60,36 @@ bool TransformationAddTypeStruct::IsApplicable( void TransformationAddTypeStruct::Apply( opt::IRContext* ir_context, TransformationContext* /*unused*/) const { - fuzzerutil::AddStructType( - ir_context, message_.fresh_id(), - std::vector(message_.member_type_id().begin(), - message_.member_type_id().end())); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + opt::Instruction::OperandList operands; + operands.reserve(message_.member_type_id().size()); + + for (auto type_id : message_.member_type_id()) { + const auto* type = ir_context->get_type_mgr()->GetType(type_id); + (void)type; // Make compiler happy in release mode. + assert(type && !type->AsFunction() && "Component's type id is invalid"); + + if (type->AsStruct()) { + // From the spec for the BuiltIn decoration: + // - When applied to a structure-type member, that structure type cannot + // be contained as a member of another structure type. + assert(!fuzzerutil::MembersHaveBuiltInDecoration(ir_context, type_id) && + "A member struct has BuiltIn members"); + } + + operands.push_back({SPV_OPERAND_TYPE_ID, {type_id}}); + } + + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeStruct, 0, message_.fresh_id(), std::move(operands)); + auto type_instruction_ptr = type_instruction.get(); + ir_context->AddType(std::move(type_instruction)); + + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeStruct::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.h index 94be42ad7a..6a8dce7c53 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_struct.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationAddTypeStruct : public Transformation { public: explicit TransformationAddTypeStruct( - const protobufs::TransformationAddTypeStruct& message); + protobufs::TransformationAddTypeStruct message); TransformationAddTypeStruct(uint32_t fresh_id, const std::vector& component_type_ids); @@ -37,7 +37,9 @@ class TransformationAddTypeStruct : public Transformation { // - |message_.member_type_id| must be a sequence of non-function type ids // - |message_.member_type_id| may not contain a result id of an OpTypeStruct // instruction with BuiltIn members (i.e. members of the struct are - // decorated via OpMemberDecorate with BuiltIn decoration). + // decorated via OpMemberDecorate with BuiltIn decoration) + // - |message_.member_type_id| may not contain a result id of an OpTypeStruct + // instruction that has the Block or BufferBlock decoration bool IsApplicable( opt::IRContext* ir_context, const TransformationContext& transformation_context) const override; diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.cpp b/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.cpp index a3b0010ef1..4da0ff0192 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationAddTypeVector::TransformationAddTypeVector( - const spvtools::fuzz::protobufs::TransformationAddTypeVector& message) - : message_(message) {} + protobufs::TransformationAddTypeVector message) + : message_(std::move(message)) {} TransformationAddTypeVector::TransformationAddTypeVector( uint32_t fresh_id, uint32_t component_type_id, uint32_t component_count) { @@ -46,13 +46,30 @@ bool TransformationAddTypeVector::IsApplicable( void TransformationAddTypeVector::Apply( opt::IRContext* ir_context, TransformationContext* /*unused*/) const { - fuzzerutil::AddVectorType(ir_context, message_.fresh_id(), - message_.component_type_id(), - message_.component_count()); - // We have added an instruction to the module, so need to be careful about the - // validity of existing analyses. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + const auto* component_type = + ir_context->get_type_mgr()->GetType(message_.component_type_id()); + (void)component_type; // Make compiler happy in release mode. + assert(component_type && + (component_type->AsInteger() || component_type->AsFloat() || + component_type->AsBool()) && + "|component_type_id| is invalid"); + assert(message_.component_count() >= 2 && message_.component_count() <= 4 && + "Precondition: component count must be in range [2, 4]."); + + auto type_instruction = MakeUnique( + ir_context, SpvOpTypeVector, 0, message_.fresh_id(), + opt::Instruction::OperandList{ + {SPV_OPERAND_TYPE_ID, {message_.component_type_id()}}, + {SPV_OPERAND_TYPE_LITERAL_INTEGER, {message_.component_count()}}}); + auto type_instruction_ptr = type_instruction.get(); + ir_context->module()->AddType(std::move(type_instruction)); + + fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); + + // Inform the def use manager that there is a new definition. Invalidate the + // type manager since we have added a new type. + ir_context->get_def_use_mgr()->AnalyzeInstDef(type_instruction_ptr); + ir_context->InvalidateAnalyses(opt::IRContext::kAnalysisTypes); } protobufs::Transformation TransformationAddTypeVector::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.h b/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.h index c25d565d0c..43460ce46b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.h +++ b/third_party/spirv-tools/source/fuzz/transformation_add_type_vector.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAddTypeVector : public Transformation { public: explicit TransformationAddTypeVector( - const protobufs::TransformationAddTypeVector& message); + protobufs::TransformationAddTypeVector message); TransformationAddTypeVector(uint32_t fresh_id, uint32_t component_type_id, uint32_t component_count); diff --git a/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.cpp b/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.cpp index 8b74ed3782..21fef258e4 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.cpp @@ -28,8 +28,8 @@ const uint32_t kBranchWeightForFalseLabelIndex = 4; } // namespace TransformationAdjustBranchWeights::TransformationAdjustBranchWeights( - const spvtools::fuzz::protobufs::TransformationAdjustBranchWeights& message) - : message_(message) {} + protobufs::TransformationAdjustBranchWeights message) + : message_(std::move(message)) {} TransformationAdjustBranchWeights::TransformationAdjustBranchWeights( const protobufs::InstructionDescriptor& instruction_descriptor, diff --git a/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.h b/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.h index 4d451a5aba..41eceeb5a8 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.h +++ b/third_party/spirv-tools/source/fuzz/transformation_adjust_branch_weights.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationAdjustBranchWeights : public Transformation { public: explicit TransformationAdjustBranchWeights( - const protobufs::TransformationAdjustBranchWeights& message); + protobufs::TransformationAdjustBranchWeights message); TransformationAdjustBranchWeights( const protobufs::InstructionDescriptor& instruction_descriptor, diff --git a/third_party/spirv-tools/source/fuzz/transformation_composite_construct.cpp b/third_party/spirv-tools/source/fuzz/transformation_composite_construct.cpp index f6711f5a99..0cd2308bc8 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_composite_construct.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_composite_construct.cpp @@ -23,8 +23,8 @@ namespace spvtools { namespace fuzz { TransformationCompositeConstruct::TransformationCompositeConstruct( - const protobufs::TransformationCompositeConstruct& message) - : message_(message) {} + protobufs::TransformationCompositeConstruct message) + : message_(std::move(message)) {} TransformationCompositeConstruct::TransformationCompositeConstruct( uint32_t composite_type_id, std::vector component, @@ -120,12 +120,18 @@ void TransformationCompositeConstruct::Apply( } // Insert an OpCompositeConstruct instruction. - insert_before.InsertBefore(MakeUnique( + auto new_instruction = MakeUnique( ir_context, SpvOpCompositeConstruct, message_.composite_type_id(), - message_.fresh_id(), in_operands)); + message_.fresh_id(), in_operands); + auto new_instruction_ptr = new_instruction.get(); + insert_before.InsertBefore(std::move(new_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, destination_block); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + + // No analyses need to be invalidated since the transformation is local to a + // block and the def-use and instruction-to-block mappings have been updated. AddDataSynonymFacts(ir_context, transformation_context); } @@ -283,15 +289,25 @@ void TransformationCompositeConstruct::AddDataSynonymFacts( ir_context->get_type_mgr()->GetType(message_.composite_type_id()); uint32_t index = 0; for (auto component : message_.component()) { + auto component_type = ir_context->get_type_mgr()->GetType( + ir_context->get_def_use_mgr()->GetDef(component)->type_id()); + // Whether the component is a vector being packed into a vector determines + // how we should keep track of the indices associated with components. + const bool packing_vector_into_vector = + composite_type->AsVector() && component_type->AsVector(); if (!fuzzerutil::CanMakeSynonymOf( ir_context, *transformation_context, ir_context->get_def_use_mgr()->GetDef(component))) { - index++; + // We can't make a synonym of this component, so we skip on to the next + // component. In the case where we're packing a vector into a vector we + // have to skip as many components of the resulting vectors as there are + // elements of the component vector. + index += packing_vector_into_vector + ? component_type->AsVector()->element_count() + : 1; continue; } - auto component_type = ir_context->get_type_mgr()->GetType( - ir_context->get_def_use_mgr()->GetDef(component)->type_id()); - if (composite_type->AsVector() && component_type->AsVector()) { + if (packing_vector_into_vector) { // The case where the composite being constructed is a vector and the // component provided for construction is also a vector is special. It // requires adding a synonym fact relating each element of the sub-vector diff --git a/third_party/spirv-tools/source/fuzz/transformation_composite_construct.h b/third_party/spirv-tools/source/fuzz/transformation_composite_construct.h index 3a3e43c4ac..cc44a612a1 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_composite_construct.h +++ b/third_party/spirv-tools/source/fuzz/transformation_composite_construct.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationCompositeConstruct : public Transformation { public: explicit TransformationCompositeConstruct( - const protobufs::TransformationCompositeConstruct& message); + protobufs::TransformationCompositeConstruct message); TransformationCompositeConstruct( uint32_t composite_type_id, std::vector component, diff --git a/third_party/spirv-tools/source/fuzz/transformation_composite_extract.cpp b/third_party/spirv-tools/source/fuzz/transformation_composite_extract.cpp index 2aff02fb3e..647cd74e6d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_composite_extract.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_composite_extract.cpp @@ -24,8 +24,8 @@ namespace spvtools { namespace fuzz { TransformationCompositeExtract::TransformationCompositeExtract( - const spvtools::fuzz::protobufs::TransformationCompositeExtract& message) - : message_(message) {} + protobufs::TransformationCompositeExtract message) + : message_(std::move(message)) {} TransformationCompositeExtract::TransformationCompositeExtract( const protobufs::InstructionDescriptor& instruction_to_insert_before, @@ -89,15 +89,20 @@ void TransformationCompositeExtract::Apply( auto extracted_type = fuzzerutil::WalkCompositeTypeIndices( ir_context, composite_instruction->type_id(), message_.index()); - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( + auto insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + opt::Instruction* new_instruction = + insert_before->InsertBefore(MakeUnique( ir_context, SpvOpCompositeExtract, extracted_type, message_.fresh_id(), extract_operands)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction); + ir_context->set_instr_block(new_instruction, + ir_context->get_instr_block(insert_before)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // No analyses need to be invalidated since the transformation is local to a + // block and the def-use and instruction-to-block mappings have been updated. AddDataSynonymFacts(ir_context, transformation_context); } diff --git a/third_party/spirv-tools/source/fuzz/transformation_composite_extract.h b/third_party/spirv-tools/source/fuzz/transformation_composite_extract.h index 0f5348a810..0682a61c5f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_composite_extract.h +++ b/third_party/spirv-tools/source/fuzz/transformation_composite_extract.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationCompositeExtract : public Transformation { public: explicit TransformationCompositeExtract( - const protobufs::TransformationCompositeExtract& message); + protobufs::TransformationCompositeExtract message); TransformationCompositeExtract( const protobufs::InstructionDescriptor& instruction_to_insert_before, diff --git a/third_party/spirv-tools/source/fuzz/transformation_composite_insert.cpp b/third_party/spirv-tools/source/fuzz/transformation_composite_insert.cpp index cc6814152d..05162bfc9e 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_composite_insert.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_composite_insert.cpp @@ -14,7 +14,6 @@ #include "transformation_composite_insert.h" -#include "source/fuzz/fuzzer_pass_add_composite_inserts.h" #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/instruction_descriptor.h" @@ -22,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationCompositeInsert::TransformationCompositeInsert( - const spvtools::fuzz::protobufs::TransformationCompositeInsert& message) - : message_(message) {} + protobufs::TransformationCompositeInsert message) + : message_(std::move(message)) {} TransformationCompositeInsert::TransformationCompositeInsert( const protobufs::InstructionDescriptor& instruction_to_insert_before, @@ -124,15 +123,21 @@ void TransformationCompositeInsert::Apply( auto composite_type_id = fuzzerutil::GetTypeId(ir_context, message_.composite_id()); - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( - ir_context, SpvOpCompositeInsert, composite_type_id, - message_.fresh_id(), std::move(in_operands))); + auto insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + auto new_instruction = MakeUnique( + ir_context, SpvOpCompositeInsert, composite_type_id, message_.fresh_id(), + std::move(in_operands)); + auto new_instruction_ptr = new_instruction.get(); + insert_before->InsertBefore(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - // We have modified the module so most analyzes are now invalid. - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + // Inform the def-use manager about the new instruction and record its basic + // block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, + ir_context->get_instr_block(insert_before)); // Add data synonym facts that arise from the insertion. AddDataSynonymFacts(ir_context, transformation_context); diff --git a/third_party/spirv-tools/source/fuzz/transformation_composite_insert.h b/third_party/spirv-tools/source/fuzz/transformation_composite_insert.h index f229014274..413d41f131 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_composite_insert.h +++ b/third_party/spirv-tools/source/fuzz/transformation_composite_insert.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationCompositeInsert : public Transformation { public: explicit TransformationCompositeInsert( - const protobufs::TransformationCompositeInsert& message); + protobufs::TransformationCompositeInsert message); TransformationCompositeInsert( const protobufs::InstructionDescriptor& instruction_to_insert_before, diff --git a/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.cpp b/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.cpp index f727052623..7ae9df824f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.cpp @@ -19,9 +19,8 @@ namespace fuzz { TransformationComputeDataSynonymFactClosure:: TransformationComputeDataSynonymFactClosure( - const spvtools::fuzz::protobufs:: - TransformationComputeDataSynonymFactClosure& message) - : message_(message) {} + protobufs::TransformationComputeDataSynonymFactClosure message) + : message_(std::move(message)) {} TransformationComputeDataSynonymFactClosure:: TransformationComputeDataSynonymFactClosure( diff --git a/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.h b/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.h index dedabe23fb..c61b26ecbf 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.h +++ b/third_party/spirv-tools/source/fuzz/transformation_compute_data_synonym_fact_closure.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationComputeDataSynonymFactClosure : public Transformation { public: explicit TransformationComputeDataSynonymFactClosure( - const protobufs::TransformationComputeDataSynonymFactClosure& message); + protobufs::TransformationComputeDataSynonymFactClosure message); explicit TransformationComputeDataSynonymFactClosure( uint32_t maximum_equivalence_class_size); diff --git a/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.cpp b/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.cpp index 07758cd3c3..dee1207fa6 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.cpp @@ -21,9 +21,8 @@ namespace fuzz { TransformationDuplicateRegionWithSelection:: TransformationDuplicateRegionWithSelection( - const spvtools::fuzz::protobufs:: - TransformationDuplicateRegionWithSelection& message) - : message_(message) {} + protobufs::TransformationDuplicateRegionWithSelection message) + : message_(std::move(message)) {} TransformationDuplicateRegionWithSelection:: TransformationDuplicateRegionWithSelection( @@ -209,7 +208,7 @@ bool TransformationDuplicateRegionWithSelection::IsApplicable( return false; } } else { - auto duplicate_label = original_label_to_duplicate_label[block->id()]; + auto duplicate_label = original_label_to_duplicate_label.at(block->id()); // Each id assigned to labels in the region must be distinct and fresh. if (!duplicate_label || !CheckIdIsFreshAndNotUsedByThisTransformation( @@ -217,7 +216,7 @@ bool TransformationDuplicateRegionWithSelection::IsApplicable( return false; } } - for (auto instr : *block) { + for (auto& instr : *block) { if (!instr.HasResultId()) { continue; } @@ -228,7 +227,7 @@ bool TransformationDuplicateRegionWithSelection::IsApplicable( return false; } } else { - auto duplicate_id = original_id_to_duplicate_id[instr.result_id()]; + auto duplicate_id = original_id_to_duplicate_id.at(instr.result_id()); // Id assigned to this result id in the region must be distinct and // fresh. if (!duplicate_id || @@ -237,43 +236,48 @@ bool TransformationDuplicateRegionWithSelection::IsApplicable( return false; } } - if (&instr == &*exit_block->tail() || - fuzzerutil::IdIsAvailableBeforeInstruction( - ir_context, &*exit_block->tail(), instr.result_id())) { - // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3787): - // Consider not adding OpPhi instructions for the pointers and - // sampled images which are unused after the region, so that the - // transformation could be still applicable. - - // Using pointers with OpPhi requires capability VariablePointers. - if (ir_context->get_def_use_mgr()->GetDef(instr.type_id())->opcode() == - SpvOpTypePointer && - !ir_context->get_feature_mgr()->HasCapability( - SpvCapabilityVariablePointers)) { - return false; - } - - // OpTypeSampledImage cannot be the result type of an OpPhi instruction. - if (ir_context->get_def_use_mgr()->GetDef(instr.type_id())->opcode() == - SpvOpTypeSampledImage) { - return false; - } - - // Every instruction with a result id available at the end of the region - // must be present in the map |original_id_to_phi_id|, unless overflow - // ids are present. - if (original_id_to_phi_id.count(instr.result_id()) == 0) { - if (!transformation_context.GetOverflowIdSource()->HasOverflowIds()) { + // If the instruction is available at the end of the region then we would + // like to be able to add an OpPhi instruction at the merge point of the + // duplicated region to capture the values computed by both duplicates of + // the instruction, so that this is also available after the region. We + // do this not just for instructions that are already used after the + // region, but for all instructions so that the phi is available to future + // transformations. + if (AvailableAfterRegion(instr, exit_block, ir_context)) { + if (!ValidOpPhiArgument(instr, ir_context)) { + // The instruction cannot be used as an OpPhi argument. This is a + // blocker if there are uses of the instruction after the region. + // Otherwise we can simply avoid generating an OpPhi for this + // instruction and its duplicate. + if (!ir_context->get_def_use_mgr()->WhileEachUser( + &instr, + [ir_context, + ®ion_set](opt::Instruction* use_instr) -> bool { + opt::BasicBlock* use_block = + ir_context->get_instr_block(use_instr); + return use_block == nullptr || + region_set.count(use_block) > 0; + })) { return false; } } else { - auto phi_id = original_id_to_phi_id[instr.result_id()]; - // Id assigned to this result id in the region must be distinct and - // fresh. - if (!phi_id || - !CheckIdIsFreshAndNotUsedByThisTransformation( - phi_id, ir_context, &ids_used_by_this_transformation)) { - return false; + // Every instruction with a result id available at the end of the + // region must be present in the map |original_id_to_phi_id|, unless + // overflow ids are present. + if (original_id_to_phi_id.count(instr.result_id()) == 0) { + if (!transformation_context.GetOverflowIdSource() + ->HasOverflowIds()) { + return false; + } + } else { + auto phi_id = original_id_to_phi_id.at(instr.result_id()); + // Id assigned to this result id in the region must be distinct and + // fresh. + if (!phi_id || + !CheckIdIsFreshAndNotUsedByThisTransformation( + phi_id, ir_context, &ids_used_by_this_transformation)) { + return false; + } } } } @@ -329,7 +333,7 @@ void TransformationDuplicateRegionWithSelection::Apply( {block->id(), transformation_context->GetOverflowIdSource()->GetNextOverflowId()}); } - for (auto instr : *block) { + for (auto& instr : *block) { if (!instr.HasResultId()) { continue; } @@ -338,9 +342,8 @@ void TransformationDuplicateRegionWithSelection::Apply( {instr.result_id(), transformation_context->GetOverflowIdSource() ->GetNextOverflowId()}); } - if (&instr == &*exit_block->tail() || - fuzzerutil::IdIsAvailableBeforeInstruction( - ir_context, &*exit_block->tail(), instr.result_id())) { + if (AvailableAfterRegion(instr, exit_block, ir_context) && + ValidOpPhiArgument(instr, ir_context)) { if (original_id_to_phi_id.count(instr.result_id()) == 0) { original_id_to_phi_id.insert( {instr.result_id(), transformation_context->GetOverflowIdSource() @@ -414,12 +417,12 @@ void TransformationDuplicateRegionWithSelection::Apply( } fuzzerutil::UpdateModuleIdBound( - ir_context, original_label_to_duplicate_label[block->id()]); + ir_context, original_label_to_duplicate_label.at(block->id())); std::unique_ptr duplicated_block = MakeUnique(MakeUnique( ir_context, SpvOpLabel, 0, - original_label_to_duplicate_label[block->id()], + original_label_to_duplicate_label.at(block->id()), opt::Instruction::OperandList())); for (auto& instr : *block) { @@ -444,8 +447,10 @@ void TransformationDuplicateRegionWithSelection::Apply( duplicated_block->AddInstruction( std::unique_ptr(cloned_instr)); - fuzzerutil::UpdateModuleIdBound( - ir_context, original_id_to_duplicate_id[instr.result_id()]); + if (instr.HasResultId()) { + fuzzerutil::UpdateModuleIdBound( + ir_context, original_id_to_duplicate_id.at(instr.result_id())); + } // If an id from the original region was used in this instruction, // replace it with the value from |original_id_to_duplicate_id|. @@ -456,8 +461,7 @@ void TransformationDuplicateRegionWithSelection::Apply( original_label_to_duplicate_label](uint32_t* op) { if (original_id_to_duplicate_id.count(*op) != 0) { *op = original_id_to_duplicate_id.at(*op); - } - if (original_label_to_duplicate_label.count(*op) != 0) { + } else if (original_label_to_duplicate_label.count(*op) != 0) { *op = original_label_to_duplicate_label.at(*op); } }); @@ -484,26 +488,27 @@ void TransformationDuplicateRegionWithSelection::Apply( for (auto& block : region_blocks) { for (auto& instr : *block) { - if (instr.result_id() != 0 && - (&instr == &*exit_block->tail() || - fuzzerutil::IdIsAvailableBeforeInstruction( - ir_context, &*exit_block->tail(), instr.result_id()))) { - // Add the OpPhi instruction for every result id that is - // available at the end of the region (the last instruction - // of the |exit_block|) + if (instr.result_id() == 0) { + continue; + } + if (AvailableAfterRegion(instr, exit_block, ir_context) && + ValidOpPhiArgument(instr, ir_context)) { + // Add an OpPhi instruction for every result id that is available at + // the end of the region, as long as the result id is valid for use + // with OpPhi. merge_block->AddInstruction(MakeUnique( ir_context, SpvOpPhi, instr.type_id(), - original_id_to_phi_id[instr.result_id()], + original_id_to_phi_id.at(instr.result_id()), opt::Instruction::OperandList({ {SPV_OPERAND_TYPE_ID, {instr.result_id()}}, {SPV_OPERAND_TYPE_ID, {exit_block->id()}}, {SPV_OPERAND_TYPE_ID, - {original_id_to_duplicate_id[instr.result_id()]}}, + {original_id_to_duplicate_id.at(instr.result_id())}}, {SPV_OPERAND_TYPE_ID, {duplicated_exit_block->id()}}, }))); fuzzerutil::UpdateModuleIdBound( - ir_context, original_id_to_phi_id[instr.result_id()]); + ir_context, original_id_to_phi_id.at(instr.result_id())); // If the instruction has been remapped by an OpPhi, look // for all its uses outside of the region and outside of the @@ -544,7 +549,8 @@ void TransformationDuplicateRegionWithSelection::Apply( {{SPV_OPERAND_TYPE_ID, {message_.condition_id()}}, {SPV_OPERAND_TYPE_ID, {message_.entry_block_id()}}, {SPV_OPERAND_TYPE_ID, - {original_label_to_duplicate_label[message_.entry_block_id()]}}}))); + {original_label_to_duplicate_label.at( + message_.entry_block_id())}}}))); // Move the terminator of |exit_block| to the end of // |merge_block|. @@ -678,5 +684,38 @@ TransformationDuplicateRegionWithSelection::GetFreshIds() const { return result; } +bool TransformationDuplicateRegionWithSelection::AvailableAfterRegion( + const opt::Instruction& instr, opt::BasicBlock* exit_block, + opt::IRContext* ir_context) { + opt::Instruction* final_instruction_in_region = &*exit_block->tail(); + return &instr == final_instruction_in_region || + fuzzerutil::IdIsAvailableBeforeInstruction( + ir_context, final_instruction_in_region, instr.result_id()); +} + +bool TransformationDuplicateRegionWithSelection::ValidOpPhiArgument( + const opt::Instruction& instr, opt::IRContext* ir_context) { + opt::Instruction* instr_type = + ir_context->get_def_use_mgr()->GetDef(instr.type_id()); + + // It is invalid to apply OpPhi to void-typed values. + if (instr_type->opcode() == SpvOpTypeVoid) { + return false; + } + + // Using pointers with OpPhi requires capability VariablePointers. + if (instr_type->opcode() == SpvOpTypePointer && + !ir_context->get_feature_mgr()->HasCapability( + SpvCapabilityVariablePointers)) { + return false; + } + + // OpTypeSampledImage cannot be the result type of an OpPhi instruction. + if (instr_type->opcode() == SpvOpTypeSampledImage) { + return false; + } + return true; +} + } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.h b/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.h index d6f0ad9a8a..30e3c3736d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.h +++ b/third_party/spirv-tools/source/fuzz/transformation_duplicate_region_with_selection.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationDuplicateRegionWithSelection : public Transformation { public: explicit TransformationDuplicateRegionWithSelection( - const protobufs::TransformationDuplicateRegionWithSelection& message); + protobufs::TransformationDuplicateRegionWithSelection message); explicit TransformationDuplicateRegionWithSelection( uint32_t new_entry_fresh_id, uint32_t condition_id, @@ -66,6 +66,17 @@ class TransformationDuplicateRegionWithSelection : public Transformation { opt::IRContext* ir_context, opt::BasicBlock* entry_block, opt::BasicBlock* exit_block); + // Returns true if and only if |instr| is available at the end of the region + // for which |exit_block| is the final block. + static bool AvailableAfterRegion(const opt::Instruction& instr, + opt::BasicBlock* exit_block, + opt::IRContext* ir_context); + + // Returns true if and only if |instr| is valid as an argument to an OpPhi + // instruction. + static bool ValidOpPhiArgument(const opt::Instruction& instr, + opt::IRContext* ir_context); + std::unordered_set GetFreshIds() const override; protobufs::Transformation ToMessage() const override; diff --git a/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.cpp b/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.cpp index 32e8351855..1e5dae9730 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationEquationInstruction::TransformationEquationInstruction( - const spvtools::fuzz::protobufs::TransformationEquationInstruction& message) - : message_(message) {} + protobufs::TransformationEquationInstruction message) + : message_(std::move(message)) {} TransformationEquationInstruction::TransformationEquationInstruction( uint32_t fresh_id, SpvOp opcode, const std::vector& in_operand_id, @@ -84,13 +84,17 @@ void TransformationEquationInstruction::Apply( rhs_id.push_back(id); } - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( + auto insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + opt::Instruction* new_instruction = + insert_before->InsertBefore(MakeUnique( ir_context, static_cast(message_.opcode()), MaybeGetResultTypeId(ir_context), message_.fresh_id(), std::move(in_operands))); - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction); + ir_context->set_instr_block(new_instruction, + ir_context->get_instr_block(insert_before)); // Add an equation fact as long as the result id is not irrelevant (it could // be if we are inserting into a dead block). diff --git a/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.h b/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.h index 4afc85fb0a..ae32a1a2c2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.h +++ b/third_party/spirv-tools/source/fuzz/transformation_equation_instruction.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationEquationInstruction : public Transformation { public: explicit TransformationEquationInstruction( - const protobufs::TransformationEquationInstruction& message); + protobufs::TransformationEquationInstruction message); TransformationEquationInstruction( uint32_t fresh_id, SpvOp opcode, diff --git a/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.cpp b/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.cpp index 640aea2528..9938706698 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.cpp @@ -21,9 +21,8 @@ namespace spvtools { namespace fuzz { TransformationExpandVectorReduction::TransformationExpandVectorReduction( - const spvtools::fuzz::protobufs::TransformationExpandVectorReduction& - message) - : message_(message) {} + protobufs::TransformationExpandVectorReduction message) + : message_(std::move(message)) {} TransformationExpandVectorReduction::TransformationExpandVectorReduction( const uint32_t instruction_result_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.h b/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.h index e4cc953998..6ee2cefaa6 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.h +++ b/third_party/spirv-tools/source/fuzz/transformation_expand_vector_reduction.h @@ -70,7 +70,7 @@ namespace fuzz { class TransformationExpandVectorReduction : public Transformation { public: explicit TransformationExpandVectorReduction( - const protobufs::TransformationExpandVectorReduction& message); + protobufs::TransformationExpandVectorReduction message); TransformationExpandVectorReduction(const uint32_t instruction_result_id, const std::vector& fresh_ids); diff --git a/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.cpp b/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.cpp index dec933c79b..127e762811 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationFlattenConditionalBranch::TransformationFlattenConditionalBranch( - const protobufs::TransformationFlattenConditionalBranch& message) - : message_(message) {} + protobufs::TransformationFlattenConditionalBranch message) + : message_(std::move(message)) {} TransformationFlattenConditionalBranch::TransformationFlattenConditionalBranch( uint32_t header_block_id, bool true_branch_first, @@ -441,17 +441,17 @@ bool TransformationFlattenConditionalBranch:: header->terminator()->opcode() == SpvOpBranchConditional && "|header| must be the header of a conditional."); + // |header| must be reachable. + if (!ir_context->IsReachable(*header)) { + return false; + } + auto enclosing_function = header->GetParent(); auto dominator_analysis = ir_context->GetDominatorAnalysis(enclosing_function); auto postdominator_analysis = ir_context->GetPostDominatorAnalysis(enclosing_function); - // |header| must be reachable. - if (!dominator_analysis->IsReachable(header)) { - return false; - } - // Check that the header and the merge block describe a single-entry, // single-exit region. if (!dominator_analysis->Dominates(header->id(), merge_block_id) || @@ -512,15 +512,31 @@ bool TransformationFlattenConditionalBranch:: return false; } + // The base objects for all data descriptors involved in synonym facts. + std::unordered_set synonym_base_objects; + for (auto* synonym : + transformation_context.GetFactManager()->GetAllSynonyms()) { + synonym_base_objects.insert(synonym->object()); + } + // Check all of the instructions in the block. - bool all_instructions_compatible = - block->WhileEachInst([ir_context, instructions_that_need_ids]( - opt::Instruction* instruction) { + bool all_instructions_compatible = block->WhileEachInst( + [ir_context, instructions_that_need_ids, + &synonym_base_objects](opt::Instruction* instruction) { // We can ignore OpLabel instructions. if (instruction->opcode() == SpvOpLabel) { return true; } + // If the instruction is the base object of some synonym then we + // conservatively bail out: if a synonym ends up depending on an + // instruction that needs to be enclosed in a side-effect wrapper then + // it might no longer hold after we flatten the conditional. + if (instruction->result_id() && + synonym_base_objects.count(instruction->result_id())) { + return false; + } + // If the instruction is a branch, it must be an unconditional branch. if (instruction->IsBranch()) { return instruction->opcode() == SpvOpBranch; @@ -828,7 +844,9 @@ bool TransformationFlattenConditionalBranch::OpSelectArgumentsAreRestricted( case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: - case SPV_ENV_UNIVERSAL_1_3: { + case SPV_ENV_UNIVERSAL_1_3: + case SPV_ENV_VULKAN_1_0: + case SPV_ENV_VULKAN_1_1: { return true; } default: diff --git a/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.h b/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.h index e8cb41453b..4efff67062 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.h +++ b/third_party/spirv-tools/source/fuzz/transformation_flatten_conditional_branch.h @@ -23,7 +23,7 @@ namespace fuzz { class TransformationFlattenConditionalBranch : public Transformation { public: explicit TransformationFlattenConditionalBranch( - const protobufs::TransformationFlattenConditionalBranch& message); + protobufs::TransformationFlattenConditionalBranch message); TransformationFlattenConditionalBranch( uint32_t header_block_id, bool true_branch_first, @@ -41,6 +41,8 @@ class TransformationFlattenConditionalBranch : public Transformation { // single-exit region. // - The region must not contain barrier or OpSampledImage instructions. // - The region must not contain selection or loop constructs. + // - The region must not define ids that are the base objects for existing + // synonym facts. // - For each instruction that requires additional fresh ids, then: // - if the instruction is mapped to the required ids for enclosing it by // |message_.side_effect_wrapper_info|, these must be valid (the diff --git a/third_party/spirv-tools/source/fuzz/transformation_function_call.cpp b/third_party/spirv-tools/source/fuzz/transformation_function_call.cpp index ec95c32058..0f88ce51ad 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_function_call.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_function_call.cpp @@ -22,8 +22,8 @@ namespace spvtools { namespace fuzz { TransformationFunctionCall::TransformationFunctionCall( - const spvtools::fuzz::protobufs::TransformationFunctionCall& message) - : message_(message) {} + protobufs::TransformationFunctionCall message) + : message_(std::move(message)) {} TransformationFunctionCall::TransformationFunctionCall( uint32_t fresh_id, uint32_t callee_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_function_call.h b/third_party/spirv-tools/source/fuzz/transformation_function_call.h index e220d83d80..a2aaf3654c 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_function_call.h +++ b/third_party/spirv-tools/source/fuzz/transformation_function_call.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationFunctionCall : public Transformation { public: explicit TransformationFunctionCall( - const protobufs::TransformationFunctionCall& message); + protobufs::TransformationFunctionCall message); TransformationFunctionCall( uint32_t fresh_id, uint32_t callee_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_inline_function.cpp b/third_party/spirv-tools/source/fuzz/transformation_inline_function.cpp index f58b123271..a48b81796c 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_inline_function.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_inline_function.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationInlineFunction::TransformationInlineFunction( - const spvtools::fuzz::protobufs::TransformationInlineFunction& message) - : message_(message) {} + protobufs::TransformationInlineFunction message) + : message_(std::move(message)) {} TransformationInlineFunction::TransformationInlineFunction( uint32_t function_call_id, @@ -183,7 +183,6 @@ void TransformationInlineFunction::Apply( auto* cloned_block = block.Clone(ir_context); cloned_block = caller_function->InsertBasicBlockBefore( std::unique_ptr(cloned_block), successor_block); - cloned_block->SetParent(caller_function); cloned_block->GetLabel()->SetResultId(result_id_map.at(cloned_block->id())); fuzzerutil::UpdateModuleIdBound(ir_context, cloned_block->id()); diff --git a/third_party/spirv-tools/source/fuzz/transformation_inline_function.h b/third_party/spirv-tools/source/fuzz/transformation_inline_function.h index 8105d92b67..f4dc410af2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_inline_function.h +++ b/third_party/spirv-tools/source/fuzz/transformation_inline_function.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationInlineFunction : public Transformation { public: explicit TransformationInlineFunction( - const protobufs::TransformationInlineFunction& message); + protobufs::TransformationInlineFunction message); TransformationInlineFunction( uint32_t function_call_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_load.cpp b/third_party/spirv-tools/source/fuzz/transformation_load.cpp index f8b351342e..e22f8dd292 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_load.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_load.cpp @@ -20,9 +20,8 @@ namespace spvtools { namespace fuzz { -TransformationLoad::TransformationLoad( - const spvtools::fuzz::protobufs::TransformationLoad& message) - : message_(message) {} +TransformationLoad::TransformationLoad(protobufs::TransformationLoad message) + : message_(std::move(message)) {} TransformationLoad::TransformationLoad( uint32_t fresh_id, uint32_t pointer_id, @@ -84,12 +83,19 @@ void TransformationLoad::Apply(opt::IRContext* ir_context, uint32_t result_type = fuzzerutil::GetPointeeTypeIdFromPointerType( ir_context, fuzzerutil::GetTypeId(ir_context, message_.pointer_id())); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( - ir_context, SpvOpLoad, result_type, message_.fresh_id(), - opt::Instruction::OperandList( - {{SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}}))); - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + auto insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + auto new_instruction = MakeUnique( + ir_context, SpvOpLoad, result_type, message_.fresh_id(), + opt::Instruction::OperandList( + {{SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}})); + auto new_instruction_ptr = new_instruction.get(); + insert_before->InsertBefore(std::move(new_instruction)); + // Inform the def-use manager about the new instruction and record its basic + // block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, + ir_context->get_instr_block(insert_before)); } protobufs::Transformation TransformationLoad::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_load.h b/third_party/spirv-tools/source/fuzz/transformation_load.h index 683bba527a..d10b0073d8 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_load.h +++ b/third_party/spirv-tools/source/fuzz/transformation_load.h @@ -25,7 +25,7 @@ namespace fuzz { class TransformationLoad : public Transformation { public: - explicit TransformationLoad(const protobufs::TransformationLoad& message); + explicit TransformationLoad(protobufs::TransformationLoad message); TransformationLoad( uint32_t fresh_id, uint32_t pointer_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.cpp b/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.cpp index d6d51404c7..bd0664c0ea 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationMakeVectorOperationDynamic:: TransformationMakeVectorOperationDynamic( - const spvtools::fuzz::protobufs:: - TransformationMakeVectorOperationDynamic& message) - : message_(message) {} + protobufs::TransformationMakeVectorOperationDynamic message) + : message_(std::move(message)) {} TransformationMakeVectorOperationDynamic:: TransformationMakeVectorOperationDynamic(uint32_t instruction_result_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.h b/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.h index d1765c5239..e444f40c17 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.h +++ b/third_party/spirv-tools/source/fuzz/transformation_make_vector_operation_dynamic.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationMakeVectorOperationDynamic : public Transformation { public: explicit TransformationMakeVectorOperationDynamic( - const protobufs::TransformationMakeVectorOperationDynamic& message); + protobufs::TransformationMakeVectorOperationDynamic message); TransformationMakeVectorOperationDynamic(uint32_t instruction_result_id, uint32_t constant_index_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.cpp b/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.cpp index 2a9e90ccbf..dbf782e22a 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationMergeBlocks::TransformationMergeBlocks( - const spvtools::fuzz::protobufs::TransformationMergeBlocks& message) - : message_(message) {} + protobufs::TransformationMergeBlocks message) + : message_(std::move(message)) {} TransformationMergeBlocks::TransformationMergeBlocks(uint32_t block_id) { message_.set_block_id(block_id); @@ -43,6 +43,9 @@ bool TransformationMergeBlocks::IsApplicable( } auto first_block = ir_context->cfg()->block(predecessors.at(0)); + if (!ir_context->IsReachable(*first_block)) { + return false; + } return opt::blockmergeutil::CanMergeWithSuccessor(ir_context, first_block); } diff --git a/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.h b/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.h index d9a0ca051e..f3462fae4f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.h +++ b/third_party/spirv-tools/source/fuzz/transformation_merge_blocks.h @@ -26,11 +26,12 @@ namespace fuzz { class TransformationMergeBlocks : public Transformation { public: explicit TransformationMergeBlocks( - const protobufs::TransformationMergeBlocks& message); + protobufs::TransformationMergeBlocks message); TransformationMergeBlocks(uint32_t block_id); // - |message_.block_id| must be the id of a block, b + // - b must be statically reachable in the control flow graph of its function // - b must have a single predecessor, a // - b must be the sole successor of a // - Replacing a with the merge of a and b (and removing b) must lead to a diff --git a/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.cpp b/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.cpp index 90578a2a32..022e1b6dbf 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.cpp @@ -21,15 +21,17 @@ namespace spvtools { namespace fuzz { TransformationMergeFunctionReturns::TransformationMergeFunctionReturns( - const protobufs::TransformationMergeFunctionReturns& message) - : message_(message) {} + protobufs::TransformationMergeFunctionReturns message) + : message_(std::move(message)) {} TransformationMergeFunctionReturns::TransformationMergeFunctionReturns( - uint32_t function_id, uint32_t outer_header_id, uint32_t outer_return_id, + uint32_t function_id, uint32_t outer_header_id, + uint32_t unreachable_continue_id, uint32_t outer_return_id, uint32_t return_val_id, uint32_t any_returnable_val_id, const std::vector& returns_merging_info) { message_.set_function_id(function_id); message_.set_outer_header_id(outer_header_id); + message_.set_unreachable_continue_id(unreachable_continue_id); message_.set_outer_return_id(outer_return_id); message_.set_return_val_id(return_val_id); message_.set_any_returnable_val_id(any_returnable_val_id); @@ -66,7 +68,9 @@ bool TransformationMergeFunctionReturns::IsApplicable( // Check that the fresh ids provided are fresh and distinct. std::set used_fresh_ids; - for (uint32_t id : {message_.outer_header_id(), message_.outer_return_id()}) { + for (uint32_t id : + {message_.outer_header_id(), message_.unreachable_continue_id(), + message_.outer_return_id()}) { if (!id || !CheckIdIsFreshAndNotUsedByThisTransformation(id, ir_context, &used_fresh_ids)) { return false; @@ -499,25 +503,20 @@ void TransformationMergeFunctionReturns::Apply( fuzzerutil::UpdateModuleIdBound(ir_context, message_.outer_header_id()); - // Add the instruction: OpLoopMerge %outer_return_id %outer_header_id None - // The header is the continue block of the outer loop. + // Add the instruction: + // OpLoopMerge %outer_return_id %unreachable_continue_id None outer_loop_header->AddInstruction(MakeUnique( ir_context, SpvOpLoopMerge, 0, 0, opt::Instruction::OperandList{ {SPV_OPERAND_TYPE_ID, {message_.outer_return_id()}}, - {SPV_OPERAND_TYPE_ID, {message_.outer_header_id()}}, + {SPV_OPERAND_TYPE_ID, {message_.unreachable_continue_id()}}, {SPV_OPERAND_TYPE_LOOP_CONTROL, {SpvLoopControlMaskNone}}})); - // Add conditional branch: - // OpBranchConditional %true %block_after_entry %outer_header_id - // This will always branch to %block_after_entry, but it also creates a back - // edge for the loop (which is never traversed). + // Add unconditional branch to %block_after_entry. outer_loop_header->AddInstruction(MakeUnique( - ir_context, SpvOpBranchConditional, 0, 0, + ir_context, SpvOpBranch, 0, 0, opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {constant_true}}, - {SPV_OPERAND_TYPE_ID, {block_after_entry}}, - {SPV_OPERAND_TYPE_ID, {message_.outer_header_id()}}})); + {SPV_OPERAND_TYPE_ID, {block_after_entry}}})); // Insert the header right after the entry block. function->InsertBasicBlockAfter(std::move(outer_loop_header), @@ -579,9 +578,26 @@ void TransformationMergeFunctionReturns::Apply( } // Insert the new return block at the end of the function. - outer_return_block->SetParent(function); function->AddBasicBlock(std::move(outer_return_block)); + // Create the unreachable continue block associated with the enclosing loop. + auto unreachable_continue_block = + MakeUnique(MakeUnique( + ir_context, SpvOpLabel, 0, message_.unreachable_continue_id(), + opt::Instruction::OperandList())); + + fuzzerutil::UpdateModuleIdBound(ir_context, + message_.unreachable_continue_id()); + + // Insert an branch back to the loop header, to create a back edge. + unreachable_continue_block->AddInstruction(MakeUnique( + ir_context, SpvOpBranch, 0, 0, + opt::Instruction::OperandList{ + {SPV_OPERAND_TYPE_ID, {message_.outer_header_id()}}})); + + // Insert the unreachable continue block at the end of the function. + function->AddBasicBlock(std::move(unreachable_continue_block)); + // All analyses must be invalidated because the structure of the module was // changed. ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); @@ -591,13 +607,14 @@ std::unordered_set TransformationMergeFunctionReturns::GetFreshIds() const { std::unordered_set result; result.emplace(message_.outer_header_id()); + result.emplace(message_.unreachable_continue_id()); result.emplace(message_.outer_return_id()); // |message_.return_val_info| can be 0 if the function is void. if (message_.return_val_id()) { result.emplace(message_.return_val_id()); } - for (auto merging_info : message_.return_merging_info()) { + for (const auto& merging_info : message_.return_merging_info()) { result.emplace(merging_info.is_returning_id()); // |maybe_return_val_id| can be 0 if the function is void. if (merging_info.maybe_return_val_id()) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.h b/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.h index 4b2993675e..b3208acfec 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.h +++ b/third_party/spirv-tools/source/fuzz/transformation_merge_function_returns.h @@ -22,10 +22,11 @@ namespace fuzz { class TransformationMergeFunctionReturns : public Transformation { public: explicit TransformationMergeFunctionReturns( - const protobufs::TransformationMergeFunctionReturns& message); + protobufs::TransformationMergeFunctionReturns message); TransformationMergeFunctionReturns( - uint32_t function_id, uint32_t outer_header_id, uint32_t outer_return_id, + uint32_t function_id, uint32_t outer_header_id, + uint32_t unreachable_continue_id, uint32_t outer_return_id, uint32_t return_val_id, uint32_t any_returnable_val_id, const std::vector& returns_merging_info); @@ -40,7 +41,7 @@ class TransformationMergeFunctionReturns : public Transformation { // statements, this id will be ignored. // - Merge blocks of reachable loops that contain return statements only // consist of OpLabel, OpPhi or OpBranch instructions. - // - The model contains OpConstantTrue and OpConstantFalse instructions. + // - The module contains OpConstantTrue and OpConstantFalse instructions. // - For all merge blocks of reachable loops that contain return statements, // either: // - a mapping is provided in |message_.return_merging_info|, all of the diff --git a/third_party/spirv-tools/source/fuzz/transformation_move_block_down.cpp b/third_party/spirv-tools/source/fuzz/transformation_move_block_down.cpp index c5ed4333e0..dc1b24303f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_move_block_down.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_move_block_down.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationMoveBlockDown::TransformationMoveBlockDown( - const spvtools::fuzz::protobufs::TransformationMoveBlockDown& message) - : message_(message) {} + protobufs::TransformationMoveBlockDown message) + : message_(std::move(message)) {} TransformationMoveBlockDown::TransformationMoveBlockDown(uint32_t id) { message_.set_block_id(id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_move_block_down.h b/third_party/spirv-tools/source/fuzz/transformation_move_block_down.h index 82f2599a93..cbad945116 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_move_block_down.h +++ b/third_party/spirv-tools/source/fuzz/transformation_move_block_down.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationMoveBlockDown : public Transformation { public: explicit TransformationMoveBlockDown( - const protobufs::TransformationMoveBlockDown& message); + protobufs::TransformationMoveBlockDown message); explicit TransformationMoveBlockDown(uint32_t id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.cpp b/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.cpp index dec0578903..c8139e726f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.cpp @@ -38,8 +38,8 @@ std::string GetExtensionSet(opt::IRContext* ir_context, } // namespace TransformationMoveInstructionDown::TransformationMoveInstructionDown( - const protobufs::TransformationMoveInstructionDown& message) - : message_(message) {} + protobufs::TransformationMoveInstructionDown message) + : message_(std::move(message)) {} TransformationMoveInstructionDown::TransformationMoveInstructionDown( const protobufs::InstructionDescriptor& instruction) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.h b/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.h index 85852253a9..2a5a8f1f50 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.h +++ b/third_party/spirv-tools/source/fuzz/transformation_move_instruction_down.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationMoveInstructionDown : public Transformation { public: explicit TransformationMoveInstructionDown( - const protobufs::TransformationMoveInstructionDown& message); + protobufs::TransformationMoveInstructionDown message); explicit TransformationMoveInstructionDown( const protobufs::InstructionDescriptor& instruction); diff --git a/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.cpp b/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.cpp index fefedbd154..516a0d6164 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationMutatePointer::TransformationMutatePointer( - const protobufs::TransformationMutatePointer& message) - : message_(message) {} + protobufs::TransformationMutatePointer message) + : message_(std::move(message)) {} TransformationMutatePointer::TransformationMutatePointer( uint32_t pointer_id, uint32_t fresh_id, @@ -92,36 +92,47 @@ void TransformationMutatePointer::Apply( auto* insert_before_inst = FindInstruction(message_.insert_before(), ir_context); assert(insert_before_inst && "|insert_before| descriptor is invalid"); + opt::BasicBlock* enclosing_block = + ir_context->get_instr_block(insert_before_inst); auto pointee_type_id = fuzzerutil::GetPointeeTypeIdFromPointerType( ir_context, fuzzerutil::GetTypeId(ir_context, message_.pointer_id())); // Back up the original value. - insert_before_inst->InsertBefore(MakeUnique( + auto backup_instruction = MakeUnique( ir_context, SpvOpLoad, pointee_type_id, message_.fresh_id(), opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}})); + {SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}}); + auto backup_instruction_ptr = backup_instruction.get(); + insert_before_inst->InsertBefore(std::move(backup_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(backup_instruction_ptr); + ir_context->set_instr_block(backup_instruction_ptr, enclosing_block); // Insert a new value. - insert_before_inst->InsertBefore(MakeUnique( + auto new_value_instruction = MakeUnique( ir_context, SpvOpStore, 0, 0, opt::Instruction::OperandList{ {SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}, {SPV_OPERAND_TYPE_ID, {fuzzerutil::MaybeGetZeroConstant( - ir_context, *transformation_context, pointee_type_id, true)}}})); + ir_context, *transformation_context, pointee_type_id, true)}}}); + auto new_value_instruction_ptr = new_value_instruction.get(); + insert_before_inst->InsertBefore(std::move(new_value_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_value_instruction_ptr); + ir_context->set_instr_block(new_value_instruction_ptr, enclosing_block); // Restore the original value. - insert_before_inst->InsertBefore(MakeUnique( + auto restore_instruction = MakeUnique( ir_context, SpvOpStore, 0, 0, opt::Instruction::OperandList{ {SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}, - {SPV_OPERAND_TYPE_ID, {message_.fresh_id()}}})); + {SPV_OPERAND_TYPE_ID, {message_.fresh_id()}}}); + auto restore_instruction_ptr = restore_instruction.get(); + insert_before_inst->InsertBefore(std::move(restore_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(restore_instruction_ptr); + ir_context->set_instr_block(restore_instruction_ptr, enclosing_block); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - - // Make sure analyses represent the correct state of the module. - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); } protobufs::Transformation TransformationMutatePointer::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.h b/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.h index b9f0965673..2c7129097f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.h +++ b/third_party/spirv-tools/source/fuzz/transformation_mutate_pointer.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationMutatePointer : public Transformation { public: explicit TransformationMutatePointer( - const protobufs::TransformationMutatePointer& message); + protobufs::TransformationMutatePointer message); explicit TransformationMutatePointer( uint32_t pointer_id, uint32_t fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_outline_function.cpp b/third_party/spirv-tools/source/fuzz/transformation_outline_function.cpp index 26f9e0b265..3140fa6b34 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_outline_function.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_outline_function.cpp @@ -22,8 +22,8 @@ namespace spvtools { namespace fuzz { TransformationOutlineFunction::TransformationOutlineFunction( - const spvtools::fuzz::protobufs::TransformationOutlineFunction& message) - : message_(message) {} + protobufs::TransformationOutlineFunction message) + : message_(std::move(message)) {} TransformationOutlineFunction::TransformationOutlineFunction( uint32_t entry_block, uint32_t exit_block, @@ -175,6 +175,18 @@ bool TransformationOutlineFunction::IsApplicable( // This is achieved by going through every block in the function that contains // the region. for (auto& block : *entry_block->GetParent()) { + if (region_set.count(&block) != 0) { + // The block is in the region. Check that it does not have any unreachable + // predecessors. If it does, then we do not regard the region as single- + // entry-single-exit and hence do not outline it. + for (auto pred : ir_context->cfg()->preds(block.id())) { + if (!ir_context->IsReachable(*ir_context->cfg()->block(pred))) { + // The predecessor is unreachable. + return false; + } + } + } + if (&block == exit_block) { // It is OK (and typically expected) for the exit block of the region to // have successors outside the region. @@ -778,7 +790,6 @@ void TransformationOutlineFunction::PopulateOutlinedFunction( MakeUnique(MakeUnique( ir_context, SpvOpLabel, 0, message_.new_function_region_entry_block(), opt::Instruction::OperandList())); - outlined_region_entry_block->SetParent(outlined_function); if (&original_region_entry_block == &original_region_exit_block) { outlined_region_exit_block = outlined_region_entry_block.get(); @@ -815,8 +826,6 @@ void TransformationOutlineFunction::PopulateOutlinedFunction( outlined_region_exit_block = cloned_block.get(); } - cloned_block->SetParent(outlined_function); - // Redirect any OpPhi operands whose predecessors are the original region // entry block to become the new function entry block. cloned_block->ForEachPhiInst([this](opt::Instruction* phi_inst) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_outline_function.h b/third_party/spirv-tools/source/fuzz/transformation_outline_function.h index 36c0daf579..94ce556de3 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_outline_function.h +++ b/third_party/spirv-tools/source/fuzz/transformation_outline_function.h @@ -30,7 +30,7 @@ namespace fuzz { class TransformationOutlineFunction : public Transformation { public: explicit TransformationOutlineFunction( - const protobufs::TransformationOutlineFunction& message); + protobufs::TransformationOutlineFunction message); TransformationOutlineFunction( uint32_t entry_block, uint32_t exit_block, diff --git a/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.cpp b/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.cpp index a954cc18a2..5663d72fe8 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.cpp @@ -23,9 +23,8 @@ namespace fuzz { TransformationPermuteFunctionParameters:: TransformationPermuteFunctionParameters( - const spvtools::fuzz::protobufs:: - TransformationPermuteFunctionParameters& message) - : message_(message) {} + protobufs::TransformationPermuteFunctionParameters message) + : message_(std::move(message)) {} TransformationPermuteFunctionParameters:: TransformationPermuteFunctionParameters( diff --git a/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.h b/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.h index 38de8b18c1..abb5675c23 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.h +++ b/third_party/spirv-tools/source/fuzz/transformation_permute_function_parameters.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationPermuteFunctionParameters : public Transformation { public: explicit TransformationPermuteFunctionParameters( - const protobufs::TransformationPermuteFunctionParameters& message); + protobufs::TransformationPermuteFunctionParameters message); TransformationPermuteFunctionParameters( uint32_t function_id, uint32_t function_type_fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.cpp b/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.cpp index ebd3c86264..7ee7a82fa7 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.cpp @@ -22,8 +22,8 @@ namespace spvtools { namespace fuzz { TransformationPermutePhiOperands::TransformationPermutePhiOperands( - const spvtools::fuzz::protobufs::TransformationPermutePhiOperands& message) - : message_(message) {} + protobufs::TransformationPermutePhiOperands message) + : message_(std::move(message)) {} TransformationPermutePhiOperands::TransformationPermutePhiOperands( uint32_t result_id, const std::vector& permutation) { @@ -80,9 +80,8 @@ void TransformationPermutePhiOperands::Apply( inst->SetInOperands(std::move(permuted_operands)); - // Make sure our changes are analyzed - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // Update the def-use manager. + ir_context->UpdateDefUse(inst); } protobufs::Transformation TransformationPermutePhiOperands::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.h b/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.h index 8198b70650..16427113e8 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.h +++ b/third_party/spirv-tools/source/fuzz/transformation_permute_phi_operands.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationPermutePhiOperands : public Transformation { public: explicit TransformationPermutePhiOperands( - const protobufs::TransformationPermutePhiOperands& message); + protobufs::TransformationPermutePhiOperands message); TransformationPermutePhiOperands(uint32_t result_id, const std::vector& permutation); diff --git a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.cpp b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.cpp index ba22e398d7..c3b7c4d9eb 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationPropagateInstructionDown::TransformationPropagateInstructionDown( - const protobufs::TransformationPropagateInstructionDown& message) - : message_(message) {} + protobufs::TransformationPropagateInstructionDown message) + : message_(std::move(message)) {} TransformationPropagateInstructionDown::TransformationPropagateInstructionDown( uint32_t block_id, uint32_t phi_fresh_id, @@ -386,11 +386,8 @@ bool TransformationPropagateInstructionDown::IsApplicableToBlock( return false; } - const auto* dominator_analysis = - ir_context->GetDominatorAnalysis(block->GetParent()); - // |block| must be reachable. - if (!dominator_analysis->IsReachable(block)) { + if (!ir_context->IsReachable(*block)) { return false; } @@ -430,6 +427,9 @@ bool TransformationPropagateInstructionDown::IsApplicableToBlock( auto phi_block_id = GetOpPhiBlockId(ir_context, block_id, *inst_to_propagate, successor_ids); + const auto* dominator_analysis = + ir_context->GetDominatorAnalysis(block->GetParent()); + // Make sure we can adjust all users of the propagated instruction. return ir_context->get_def_use_mgr()->WhileEachUse( inst_to_propagate, @@ -537,7 +537,7 @@ uint32_t TransformationPropagateInstructionDown::GetOpPhiBlockId( // Check that |merge_block_id| is reachable in the CFG and |block_id| // dominates |merge_block_id|. - if (!dominator_analysis->IsReachable(merge_block_id) || + if (!ir_context->IsReachable(*ir_context->cfg()->block(merge_block_id)) || !dominator_analysis->Dominates(block_id, merge_block_id)) { return 0; } diff --git a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.h b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.h index 7eca1ad1f1..560d7dc528 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.h +++ b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_down.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationPropagateInstructionDown : public Transformation { public: explicit TransformationPropagateInstructionDown( - const protobufs::TransformationPropagateInstructionDown& message); + protobufs::TransformationPropagateInstructionDown message); TransformationPropagateInstructionDown( uint32_t block_id, uint32_t phi_fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.cpp b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.cpp index a2cacf40fd..bf0e66307b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.cpp @@ -79,8 +79,8 @@ bool HasValidDependencies(opt::IRContext* ir_context, opt::Instruction* inst) { } // namespace TransformationPropagateInstructionUp::TransformationPropagateInstructionUp( - const protobufs::TransformationPropagateInstructionUp& message) - : message_(message) {} + protobufs::TransformationPropagateInstructionUp message) + : message_(std::move(message)) {} TransformationPropagateInstructionUp::TransformationPropagateInstructionUp( uint32_t block_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.h b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.h index 63540947e8..0ca051bf0d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.h +++ b/third_party/spirv-tools/source/fuzz/transformation_propagate_instruction_up.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationPropagateInstructionUp : public Transformation { public: explicit TransformationPropagateInstructionUp( - const protobufs::TransformationPropagateInstructionUp& message); + protobufs::TransformationPropagateInstructionUp message); TransformationPropagateInstructionUp( uint32_t block_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.cpp b/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.cpp index cdc40aab88..ff52516545 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.cpp @@ -21,9 +21,8 @@ namespace spvtools { namespace fuzz { TransformationPushIdThroughVariable::TransformationPushIdThroughVariable( - const spvtools::fuzz::protobufs::TransformationPushIdThroughVariable& - message) - : message_(message) {} + protobufs::TransformationPushIdThroughVariable message) + : message_(std::move(message)) {} TransformationPushIdThroughVariable::TransformationPushIdThroughVariable( uint32_t value_id, uint32_t value_synonym_id, uint32_t variable_id, @@ -62,7 +61,7 @@ bool TransformationPushIdThroughVariable::IsApplicable( // The instruction to insert before must belong to a reachable block. auto basic_block = ir_context->get_instr_block(instruction_to_insert_before); - if (!fuzzerutil::BlockIsReachableInItsFunction(ir_context, basic_block)) { + if (!ir_context->IsReachable(*basic_block)) { return false; } @@ -105,6 +104,10 @@ void TransformationPushIdThroughVariable::Apply( auto value_instruction = ir_context->get_def_use_mgr()->GetDef(message_.value_id()); + opt::Instruction* insert_before = + FindInstruction(message_.instruction_descriptor(), ir_context); + opt::BasicBlock* enclosing_block = ir_context->get_instr_block(insert_before); + // A pointer type instruction pointing to the value type must be defined. auto pointer_type_id = fuzzerutil::MaybeGetPointerType( ir_context, value_instruction->type_id(), @@ -113,36 +116,42 @@ void TransformationPushIdThroughVariable::Apply( // Adds whether a global or local variable. if (message_.variable_storage_class() == SpvStorageClassPrivate) { - fuzzerutil::AddGlobalVariable(ir_context, message_.variable_id(), - pointer_type_id, SpvStorageClassPrivate, - message_.initializer_id()); + opt::Instruction* global_variable = fuzzerutil::AddGlobalVariable( + ir_context, message_.variable_id(), pointer_type_id, + SpvStorageClassPrivate, message_.initializer_id()); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(global_variable); } else { - auto function_id = ir_context - ->get_instr_block(FindInstruction( - message_.instruction_descriptor(), ir_context)) - ->GetParent() - ->result_id(); - fuzzerutil::AddLocalVariable(ir_context, message_.variable_id(), - pointer_type_id, function_id, - message_.initializer_id()); + opt::Function* function = + ir_context + ->get_instr_block( + FindInstruction(message_.instruction_descriptor(), ir_context)) + ->GetParent(); + opt::Instruction* local_variable = fuzzerutil::AddLocalVariable( + ir_context, message_.variable_id(), pointer_type_id, + function->result_id(), message_.initializer_id()); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(local_variable); + ir_context->set_instr_block(local_variable, &*function->entry()); } // First, insert the OpLoad instruction before |instruction_descriptor| and // then insert the OpStore instruction before the OpLoad instruction. fuzzerutil::UpdateModuleIdBound(ir_context, message_.value_synonym_id()); - FindInstruction(message_.instruction_descriptor(), ir_context) - ->InsertBefore(MakeUnique( + opt::Instruction* load_instruction = + insert_before->InsertBefore(MakeUnique( ir_context, SpvOpLoad, value_instruction->type_id(), message_.value_synonym_id(), opt::Instruction::OperandList( - {{SPV_OPERAND_TYPE_ID, {message_.variable_id()}}}))) - ->InsertBefore(MakeUnique( + {{SPV_OPERAND_TYPE_ID, {message_.variable_id()}}}))); + opt::Instruction* store_instruction = + load_instruction->InsertBefore(MakeUnique( ir_context, SpvOpStore, 0, 0, opt::Instruction::OperandList( {{SPV_OPERAND_TYPE_ID, {message_.variable_id()}}, {SPV_OPERAND_TYPE_ID, {message_.value_id()}}}))); - - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(store_instruction); + ir_context->set_instr_block(store_instruction, enclosing_block); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(load_instruction); + ir_context->set_instr_block(load_instruction, enclosing_block); // We should be able to create a synonym of |value_id| if it's not irrelevant. if (fuzzerutil::CanMakeSynonymOf(ir_context, *transformation_context, diff --git a/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.h b/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.h index d055825930..ec6943ca5b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.h +++ b/third_party/spirv-tools/source/fuzz/transformation_push_id_through_variable.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationPushIdThroughVariable : public Transformation { public: explicit TransformationPushIdThroughVariable( - const protobufs::TransformationPushIdThroughVariable& message); + protobufs::TransformationPushIdThroughVariable message); TransformationPushIdThroughVariable( uint32_t value_id, uint32_t value_synonym_fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.cpp b/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.cpp index 30ea94bb09..3278d7d82d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.cpp @@ -22,8 +22,8 @@ namespace fuzz { TransformationRecordSynonymousConstants:: TransformationRecordSynonymousConstants( - const protobufs::TransformationRecordSynonymousConstants& message) - : message_(message) {} + protobufs::TransformationRecordSynonymousConstants message) + : message_(std::move(message)) {} TransformationRecordSynonymousConstants:: TransformationRecordSynonymousConstants(uint32_t constant1_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.h b/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.h index 4376c87834..d99b0e2ad3 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.h +++ b/third_party/spirv-tools/source/fuzz/transformation_record_synonymous_constants.h @@ -24,7 +24,7 @@ namespace fuzz { class TransformationRecordSynonymousConstants : public Transformation { public: explicit TransformationRecordSynonymousConstants( - const protobufs::TransformationRecordSynonymousConstants& message); + protobufs::TransformationRecordSynonymousConstants message); TransformationRecordSynonymousConstants(uint32_t constant1_id, uint32_t constant2_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.cpp index a2575153d5..e1977a64d3 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.cpp @@ -27,9 +27,8 @@ const uint32_t kArithmeticInstructionIndexRightInOperand = 1; TransformationReplaceAddSubMulWithCarryingExtended:: TransformationReplaceAddSubMulWithCarryingExtended( - const spvtools::fuzz::protobufs:: - TransformationReplaceAddSubMulWithCarryingExtended& message) - : message_(message) {} + protobufs::TransformationReplaceAddSubMulWithCarryingExtended message) + : message_(std::move(message)) {} TransformationReplaceAddSubMulWithCarryingExtended:: TransformationReplaceAddSubMulWithCarryingExtended(uint32_t struct_fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.h b/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.h index 243542c2ed..9deb2803cb 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_add_sub_mul_with_carrying_extended.h @@ -27,8 +27,7 @@ class TransformationReplaceAddSubMulWithCarryingExtended : public Transformation { public: explicit TransformationReplaceAddSubMulWithCarryingExtended( - const protobufs::TransformationReplaceAddSubMulWithCarryingExtended& - message); + protobufs::TransformationReplaceAddSubMulWithCarryingExtended message); explicit TransformationReplaceAddSubMulWithCarryingExtended( uint32_t struct_fresh_id, uint32_t result_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.cpp index b458b5692c..24293516ea 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.cpp @@ -111,9 +111,9 @@ bool unsigned_int_binop_evaluates_to(T lhs, T rhs, SpvOp binop, TransformationReplaceBooleanConstantWithConstantBinary:: TransformationReplaceBooleanConstantWithConstantBinary( - const spvtools::fuzz::protobufs:: - TransformationReplaceBooleanConstantWithConstantBinary& message) - : message_(message) {} + protobufs::TransformationReplaceBooleanConstantWithConstantBinary + message) + : message_(std::move(message)) {} TransformationReplaceBooleanConstantWithConstantBinary:: TransformationReplaceBooleanConstantWithConstantBinary( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.h b/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.h index a0ece7f32d..97c66bf98b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_boolean_constant_with_constant_binary.h @@ -27,7 +27,7 @@ class TransformationReplaceBooleanConstantWithConstantBinary : public Transformation { public: explicit TransformationReplaceBooleanConstantWithConstantBinary( - const protobufs::TransformationReplaceBooleanConstantWithConstantBinary& + protobufs::TransformationReplaceBooleanConstantWithConstantBinary message); TransformationReplaceBooleanConstantWithConstantBinary( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.cpp index e8090121cb..9ea7cb6a37 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.cpp @@ -21,9 +21,8 @@ namespace fuzz { TransformationReplaceBranchFromDeadBlockWithExit:: TransformationReplaceBranchFromDeadBlockWithExit( - const spvtools::fuzz::protobufs:: - TransformationReplaceBranchFromDeadBlockWithExit& message) - : message_(message) {} + protobufs::TransformationReplaceBranchFromDeadBlockWithExit message) + : message_(std::move(message)) {} TransformationReplaceBranchFromDeadBlockWithExit:: TransformationReplaceBranchFromDeadBlockWithExit(uint32_t block_id, @@ -162,7 +161,10 @@ bool TransformationReplaceBranchFromDeadBlockWithExit::BlockIsSuitable( if (ir_context->cfg()->preds(successor->id()).size() < 2) { return false; } - return true; + // Make sure that domination rules are satisfied when we remove the branch + // from the |block| to its |successor|. + return fuzzerutil::NewTerminatorPreservesDominationRules( + ir_context, block.id(), {ir_context, SpvOpUnreachable}); } } // namespace fuzz diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.h b/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.h index e1418c9de5..89667fcdfe 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_branch_from_dead_block_with_exit.h @@ -27,8 +27,7 @@ namespace fuzz { class TransformationReplaceBranchFromDeadBlockWithExit : public Transformation { public: explicit TransformationReplaceBranchFromDeadBlockWithExit( - const protobufs::TransformationReplaceBranchFromDeadBlockWithExit& - message); + protobufs::TransformationReplaceBranchFromDeadBlockWithExit message); TransformationReplaceBranchFromDeadBlockWithExit(uint32_t block_id, SpvOp opcode, @@ -41,13 +40,17 @@ class TransformationReplaceBranchFromDeadBlockWithExit : public Transformation { // predecessor // - |message_.opcode()| must be one of OpKill, OpReturn, OpReturnValue and // OpUnreachable - // - |message_.opcode()| can only be OpKill the module's entry points all + // - |message_.opcode()| can only be OpKill if the module's entry points all // have Fragment execution mode // - |message_.opcode()| can only be OpReturn if the return type of the // function containing the block is void // - If |message_.opcode()| is OpReturnValue then |message_.return_value_id| // must be an id that is available at the block terminator and that matches // the return type of the enclosing function + // - Domination rules should be preserved when we apply this transformation. + // In particular, if some block appears after the |block_id|'s successor in + // the CFG, then that block cannot dominate |block_id|'s successor when this + // transformation is applied. bool IsApplicable( opt::IRContext* ir_context, const TransformationContext& transformation_context) const override; diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.cpp index 95932bf68a..c6698c0397 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationReplaceConstantWithUniform:: TransformationReplaceConstantWithUniform( - const spvtools::fuzz::protobufs:: - TransformationReplaceConstantWithUniform& message) - : message_(message) {} + protobufs::TransformationReplaceConstantWithUniform message) + : message_(std::move(message)) {} TransformationReplaceConstantWithUniform:: TransformationReplaceConstantWithUniform( @@ -254,28 +253,39 @@ void TransformationReplaceConstantWithUniform::Apply( auto* insert_before_inst = GetInsertBeforeInstruction(ir_context); assert(insert_before_inst && "There must exist an insertion point for OpAccessChain and OpLoad"); + opt::BasicBlock* enclosing_block = + ir_context->get_instr_block(insert_before_inst); // Add an access chain instruction to target the uniform element. - insert_before_inst->InsertBefore( - MakeAccessChainInstruction(ir_context, constant_type_id)); + auto access_chain_instruction = + MakeAccessChainInstruction(ir_context, constant_type_id); + auto access_chain_instruction_ptr = access_chain_instruction.get(); + insert_before_inst->InsertBefore(std::move(access_chain_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse( + access_chain_instruction_ptr); + ir_context->set_instr_block(access_chain_instruction_ptr, enclosing_block); // Add a load from this access chain. - insert_before_inst->InsertBefore( - MakeLoadInstruction(ir_context, constant_type_id)); + auto load_instruction = MakeLoadInstruction(ir_context, constant_type_id); + auto load_instruction_ptr = load_instruction.get(); + insert_before_inst->InsertBefore(std::move(load_instruction)); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(load_instruction_ptr); + ir_context->set_instr_block(load_instruction_ptr, enclosing_block); // Adjust the instruction containing the usage of the constant so that this // usage refers instead to the result of the load. instruction_containing_constant_use->SetInOperand( message_.id_use_descriptor().in_operand_index(), {message_.fresh_id_for_load()}); + ir_context->get_def_use_mgr()->EraseUseRecordsOfOperandIds( + instruction_containing_constant_use); + ir_context->get_def_use_mgr()->AnalyzeInstUse( + instruction_containing_constant_use); // Update the module id bound to reflect the new instructions. fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id_for_load()); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id_for_access_chain()); - - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); } protobufs::Transformation TransformationReplaceConstantWithUniform::ToMessage() diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.h b/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.h index 9e09748435..21210927c4 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_constant_with_uniform.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationReplaceConstantWithUniform : public Transformation { public: explicit TransformationReplaceConstantWithUniform( - const protobufs::TransformationReplaceConstantWithUniform& message); + protobufs::TransformationReplaceConstantWithUniform message); TransformationReplaceConstantWithUniform( protobufs::IdUseDescriptor id_use, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.cpp index 936b05422c..de9d1fd39f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationReplaceCopyMemoryWithLoadStore:: TransformationReplaceCopyMemoryWithLoadStore( - const spvtools::fuzz::protobufs:: - TransformationReplaceCopyMemoryWithLoadStore& message) - : message_(message) {} + protobufs::TransformationReplaceCopyMemoryWithLoadStore message) + : message_(std::move(message)) {} TransformationReplaceCopyMemoryWithLoadStore:: TransformationReplaceCopyMemoryWithLoadStore( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.h b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.h index 67d349ff84..55d1e0640d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_memory_with_load_store.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationReplaceCopyMemoryWithLoadStore : public Transformation { public: explicit TransformationReplaceCopyMemoryWithLoadStore( - const protobufs::TransformationReplaceCopyMemoryWithLoadStore& message); + protobufs::TransformationReplaceCopyMemoryWithLoadStore message); TransformationReplaceCopyMemoryWithLoadStore( uint32_t fresh_id, const protobufs::InstructionDescriptor& diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.cpp index 54c99d518a..e0643bf3d1 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationReplaceCopyObjectWithStoreLoad:: TransformationReplaceCopyObjectWithStoreLoad( - const spvtools::fuzz::protobufs:: - TransformationReplaceCopyObjectWithStoreLoad& message) - : message_(message) {} + protobufs::TransformationReplaceCopyObjectWithStoreLoad message) + : message_(std::move(message)) {} TransformationReplaceCopyObjectWithStoreLoad:: TransformationReplaceCopyObjectWithStoreLoad( @@ -88,6 +87,10 @@ void TransformationReplaceCopyObjectWithStoreLoad::Apply( assert(copy_object_instruction && copy_object_instruction->opcode() == SpvOpCopyObject && "The required OpCopyObject instruction must be defined."); + + opt::BasicBlock* enclosing_block = + ir_context->get_instr_block(copy_object_instruction); + // Get id used as a source by the OpCopyObject instruction. uint32_t src_operand = copy_object_instruction->GetSingleWordInOperand(0); // A pointer type instruction pointing to the value type must be defined. @@ -98,37 +101,46 @@ void TransformationReplaceCopyObjectWithStoreLoad::Apply( // Adds a global or local variable (according to the storage class). if (message_.variable_storage_class() == SpvStorageClassPrivate) { - fuzzerutil::AddGlobalVariable(ir_context, message_.fresh_variable_id(), - pointer_type_id, SpvStorageClassPrivate, - message_.variable_initializer_id()); + opt::Instruction* new_global = fuzzerutil::AddGlobalVariable( + ir_context, message_.fresh_variable_id(), pointer_type_id, + SpvStorageClassPrivate, message_.variable_initializer_id()); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_global); } else { - auto function_id = ir_context->get_instr_block(copy_object_instruction) - ->GetParent() - ->result_id(); - fuzzerutil::AddLocalVariable(ir_context, message_.fresh_variable_id(), - pointer_type_id, function_id, - message_.variable_initializer_id()); + opt::Function* function = + ir_context->get_instr_block(copy_object_instruction)->GetParent(); + opt::Instruction* new_local = fuzzerutil::AddLocalVariable( + ir_context, message_.fresh_variable_id(), pointer_type_id, + function->result_id(), message_.variable_initializer_id()); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_local); + ir_context->set_instr_block(new_local, &*function->begin()); } // First, insert the OpLoad instruction before the OpCopyObject instruction // and then insert the OpStore instruction before the OpLoad instruction. fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_variable_id()); - copy_object_instruction - ->InsertBefore(MakeUnique( + opt::Instruction* load_instruction = + copy_object_instruction->InsertBefore(MakeUnique( ir_context, SpvOpLoad, copy_object_instruction->type_id(), message_.copy_object_result_id(), opt::Instruction::OperandList( - {{SPV_OPERAND_TYPE_ID, {message_.fresh_variable_id()}}}))) - ->InsertBefore(MakeUnique( + {{SPV_OPERAND_TYPE_ID, {message_.fresh_variable_id()}}}))); + opt::Instruction* store_instruction = + load_instruction->InsertBefore(MakeUnique( ir_context, SpvOpStore, 0, 0, opt::Instruction::OperandList( {{SPV_OPERAND_TYPE_ID, {message_.fresh_variable_id()}}, {SPV_OPERAND_TYPE_ID, {src_operand}}}))); + + // Register the new instructions with the def-use manager, and record their + // enclosing block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(store_instruction); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(load_instruction); + ir_context->set_instr_block(store_instruction, enclosing_block); + ir_context->set_instr_block(load_instruction, enclosing_block); + // Remove the CopyObject instruction. ir_context->KillInst(copy_object_instruction); - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); - if (!transformation_context->GetFactManager()->IdIsIrrelevant( message_.copy_object_result_id()) && !transformation_context->GetFactManager()->IdIsIrrelevant(src_operand)) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.h b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.h index a90905c582..8c5ce9e29a 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_copy_object_with_store_load.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationReplaceCopyObjectWithStoreLoad : public Transformation { public: explicit TransformationReplaceCopyObjectWithStoreLoad( - const protobufs::TransformationReplaceCopyObjectWithStoreLoad& message); + protobufs::TransformationReplaceCopyObjectWithStoreLoad message); TransformationReplaceCopyObjectWithStoreLoad( uint32_t copy_object_result_id, uint32_t fresh_variable_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.cpp index 24e079ff67..92ce751dd5 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.cpp @@ -26,9 +26,8 @@ namespace spvtools { namespace fuzz { TransformationReplaceIdWithSynonym::TransformationReplaceIdWithSynonym( - const spvtools::fuzz::protobufs::TransformationReplaceIdWithSynonym& - message) - : message_(message) {} + protobufs::TransformationReplaceIdWithSynonym message) + : message_(std::move(message)) {} TransformationReplaceIdWithSynonym::TransformationReplaceIdWithSynonym( protobufs::IdUseDescriptor id_use_descriptor, uint32_t synonymous_id) { @@ -95,8 +94,12 @@ void TransformationReplaceIdWithSynonym::Apply( instruction_to_change->SetInOperand( message_.id_use_descriptor().in_operand_index(), {message_.synonymous_id()}); - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + ir_context->get_def_use_mgr()->EraseUseRecordsOfOperandIds( + instruction_to_change); + ir_context->get_def_use_mgr()->AnalyzeInstUse(instruction_to_change); + + // No analyses need to be invalidated, since the transformation is local to a + // block, and the def-use analysis has been updated. } protobufs::Transformation TransformationReplaceIdWithSynonym::ToMessage() diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.h b/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.h index 3101710a8b..1ac636b4b5 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_id_with_synonym.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationReplaceIdWithSynonym : public Transformation { public: explicit TransformationReplaceIdWithSynonym( - const protobufs::TransformationReplaceIdWithSynonym& message); + protobufs::TransformationReplaceIdWithSynonym message); TransformationReplaceIdWithSynonym( protobufs::IdUseDescriptor id_use_descriptor, uint32_t synonymous_id); diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.cpp index 27f56eba7c..a71f96a89b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationReplaceIrrelevantId::TransformationReplaceIrrelevantId( - const protobufs::TransformationReplaceIrrelevantId& message) - : message_(message) {} + protobufs::TransformationReplaceIrrelevantId message) + : message_(std::move(message)) {} TransformationReplaceIrrelevantId::TransformationReplaceIrrelevantId( const protobufs::IdUseDescriptor& id_use_descriptor, @@ -107,9 +107,12 @@ void TransformationReplaceIrrelevantId::Apply( message_.id_use_descriptor().in_operand_index(), {message_.replacement_id()}); - // Invalidate the analyses, since the usage of ids has been changed. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + ir_context->get_def_use_mgr()->EraseUseRecordsOfOperandIds( + instruction_to_change); + ir_context->get_def_use_mgr()->AnalyzeInstUse(instruction_to_change); + + // No analyses need to be invalidated, since the transformation is local to a + // block, and the def-use analysis has been updated. } protobufs::Transformation TransformationReplaceIrrelevantId::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.h b/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.h index 35b1987d29..e6210b4d8e 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_irrelevant_id.h @@ -23,7 +23,7 @@ namespace fuzz { class TransformationReplaceIrrelevantId : public Transformation { public: explicit TransformationReplaceIrrelevantId( - const protobufs::TransformationReplaceIrrelevantId& message); + protobufs::TransformationReplaceIrrelevantId message); TransformationReplaceIrrelevantId( const protobufs::IdUseDescriptor& id_use_descriptor, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.cpp index fc73a262af..2430ccabeb 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationReplaceLinearAlgebraInstruction:: TransformationReplaceLinearAlgebraInstruction( - const spvtools::fuzz::protobufs:: - TransformationReplaceLinearAlgebraInstruction& message) - : message_(message) {} + protobufs::TransformationReplaceLinearAlgebraInstruction message) + : message_(std::move(message)) {} TransformationReplaceLinearAlgebraInstruction:: TransformationReplaceLinearAlgebraInstruction( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.h b/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.h index 45f4aa64d9..0f0c18bff9 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_linear_algebra_instruction.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationReplaceLinearAlgebraInstruction : public Transformation { public: explicit TransformationReplaceLinearAlgebraInstruction( - const protobufs::TransformationReplaceLinearAlgebraInstruction& message); + protobufs::TransformationReplaceLinearAlgebraInstruction message); TransformationReplaceLinearAlgebraInstruction( const std::vector& fresh_ids, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.cpp index 6067fca879..e75337f689 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.cpp @@ -29,9 +29,8 @@ const uint32_t kOpLoadOperandIndexSourceVariable = 2; TransformationReplaceLoadStoreWithCopyMemory:: TransformationReplaceLoadStoreWithCopyMemory( - const spvtools::fuzz::protobufs:: - TransformationReplaceLoadStoreWithCopyMemory& message) - : message_(message) {} + protobufs::TransformationReplaceLoadStoreWithCopyMemory message) + : message_(std::move(message)) {} TransformationReplaceLoadStoreWithCopyMemory:: TransformationReplaceLoadStoreWithCopyMemory( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.h b/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.h index 4dd728e707..bb4d27ef6b 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_load_store_with_copy_memory.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationReplaceLoadStoreWithCopyMemory : public Transformation { public: explicit TransformationReplaceLoadStoreWithCopyMemory( - const protobufs::TransformationReplaceLoadStoreWithCopyMemory& message); + protobufs::TransformationReplaceLoadStoreWithCopyMemory message); TransformationReplaceLoadStoreWithCopyMemory( const protobufs::InstructionDescriptor& load_instruction_descriptor, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.cpp index f13af7e794..84ca1aba31 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.cpp @@ -21,9 +21,8 @@ namespace fuzz { TransformationReplaceOpPhiIdFromDeadPredecessor:: TransformationReplaceOpPhiIdFromDeadPredecessor( - const protobufs::TransformationReplaceOpPhiIdFromDeadPredecessor& - message) - : message_(message) {} + protobufs::TransformationReplaceOpPhiIdFromDeadPredecessor message) + : message_(std::move(message)) {} TransformationReplaceOpPhiIdFromDeadPredecessor:: TransformationReplaceOpPhiIdFromDeadPredecessor(uint32_t opphi_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.h b/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.h index d26b6b0a98..87ce8ad1e2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_opphi_id_from_dead_predecessor.h @@ -23,8 +23,7 @@ namespace fuzz { class TransformationReplaceOpPhiIdFromDeadPredecessor : public Transformation { public: explicit TransformationReplaceOpPhiIdFromDeadPredecessor( - const protobufs::TransformationReplaceOpPhiIdFromDeadPredecessor& - message); + protobufs::TransformationReplaceOpPhiIdFromDeadPredecessor message); TransformationReplaceOpPhiIdFromDeadPredecessor(uint32_t opphi_id, uint32_t pred_label_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.cpp index 7160d4d569..c0e6e449c7 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.cpp @@ -20,9 +20,8 @@ namespace spvtools { namespace fuzz { TransformationReplaceOpSelectWithConditionalBranch:: TransformationReplaceOpSelectWithConditionalBranch( - const spvtools::fuzz::protobufs:: - TransformationReplaceOpSelectWithConditionalBranch& message) - : message_(message) {} + protobufs::TransformationReplaceOpSelectWithConditionalBranch message) + : message_(std::move(message)) {} TransformationReplaceOpSelectWithConditionalBranch:: TransformationReplaceOpSelectWithConditionalBranch( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.h b/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.h index 8ee5c7f177..ec926c65a8 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_opselect_with_conditional_branch.h @@ -24,8 +24,7 @@ class TransformationReplaceOpSelectWithConditionalBranch : public Transformation { public: explicit TransformationReplaceOpSelectWithConditionalBranch( - const protobufs::TransformationReplaceOpSelectWithConditionalBranch& - message); + protobufs::TransformationReplaceOpSelectWithConditionalBranch message); TransformationReplaceOpSelectWithConditionalBranch(uint32_t select_id, uint32_t true_block_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.cpp index cdf7645f44..caf6716850 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.cpp @@ -23,8 +23,8 @@ namespace fuzz { TransformationReplaceParameterWithGlobal:: TransformationReplaceParameterWithGlobal( - const protobufs::TransformationReplaceParameterWithGlobal& message) - : message_(message) {} + protobufs::TransformationReplaceParameterWithGlobal message) + : message_(std::move(message)) {} TransformationReplaceParameterWithGlobal:: TransformationReplaceParameterWithGlobal( diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.h b/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.h index c2d5f8ffed..38a9c17fcd 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_parameter_with_global.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationReplaceParameterWithGlobal : public Transformation { public: explicit TransformationReplaceParameterWithGlobal( - const protobufs::TransformationReplaceParameterWithGlobal& message); + protobufs::TransformationReplaceParameterWithGlobal message); TransformationReplaceParameterWithGlobal(uint32_t function_type_fresh_id, uint32_t parameter_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.cpp b/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.cpp index 0a135e5614..13eeccb4ee 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.cpp @@ -22,8 +22,8 @@ namespace spvtools { namespace fuzz { TransformationReplaceParamsWithStruct::TransformationReplaceParamsWithStruct( - const protobufs::TransformationReplaceParamsWithStruct& message) - : message_(message) {} + protobufs::TransformationReplaceParamsWithStruct message) + : message_(std::move(message)) {} TransformationReplaceParamsWithStruct::TransformationReplaceParamsWithStruct( const std::vector& parameter_id, uint32_t fresh_function_type_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.h b/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.h index afa6b14f4f..705f3405a9 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.h +++ b/third_party/spirv-tools/source/fuzz/transformation_replace_params_with_struct.h @@ -28,7 +28,7 @@ namespace fuzz { class TransformationReplaceParamsWithStruct : public Transformation { public: explicit TransformationReplaceParamsWithStruct( - const protobufs::TransformationReplaceParamsWithStruct& message); + protobufs::TransformationReplaceParamsWithStruct message); TransformationReplaceParamsWithStruct( const std::vector& parameter_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_function_control.cpp b/third_party/spirv-tools/source/fuzz/transformation_set_function_control.cpp index 8ab9b8cb9b..02a8c9fe70 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_function_control.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_set_function_control.cpp @@ -18,8 +18,8 @@ namespace spvtools { namespace fuzz { TransformationSetFunctionControl::TransformationSetFunctionControl( - const spvtools::fuzz::protobufs::TransformationSetFunctionControl& message) - : message_(message) {} + protobufs::TransformationSetFunctionControl message) + : message_(std::move(message)) {} TransformationSetFunctionControl::TransformationSetFunctionControl( uint32_t function_id, uint32_t function_control) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_function_control.h b/third_party/spirv-tools/source/fuzz/transformation_set_function_control.h index 2952cc6d28..2e16e1ca70 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_function_control.h +++ b/third_party/spirv-tools/source/fuzz/transformation_set_function_control.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationSetFunctionControl : public Transformation { public: explicit TransformationSetFunctionControl( - const protobufs::TransformationSetFunctionControl& message); + protobufs::TransformationSetFunctionControl message); TransformationSetFunctionControl(uint32_t function_id, uint32_t function_control); diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.cpp b/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.cpp index b2180d8a69..1449960655 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.cpp @@ -18,8 +18,8 @@ namespace spvtools { namespace fuzz { TransformationSetLoopControl::TransformationSetLoopControl( - const spvtools::fuzz::protobufs::TransformationSetLoopControl& message) - : message_(message) {} + protobufs::TransformationSetLoopControl message) + : message_(std::move(message)) {} TransformationSetLoopControl::TransformationSetLoopControl( uint32_t block_id, uint32_t loop_control, uint32_t peel_count, @@ -77,12 +77,14 @@ bool TransformationSetLoopControl::IsApplicable( } } - if ((message_.loop_control() & - (SpvLoopControlPeelCountMask | SpvLoopControlPartialCountMask)) && - !(PeelCountIsSupported(ir_context) && - PartialCountIsSupported(ir_context))) { - // At least one of PeelCount or PartialCount is used, but the SPIR-V version - // in question does not support these loop controls. + // Check that PeelCount and PartialCount are supported if used. + if ((message_.loop_control() & SpvLoopControlPeelCountMask) && + !PeelCountIsSupported(ir_context)) { + return false; + } + + if ((message_.loop_control() & SpvLoopControlPartialCountMask) && + !PartialCountIsSupported(ir_context)) { return false; } @@ -183,14 +185,16 @@ bool TransformationSetLoopControl::LoopControlBitIsAddedByTransformation( bool TransformationSetLoopControl::PartialCountIsSupported( opt::IRContext* ir_context) { - // TODO(afd): We capture the universal environments for which this loop - // control is definitely not supported. The check should be refined on - // demand for other target environments. + // TODO(afd): We capture the environments for which this loop control is + // definitely not supported. The check should be refined on demand for other + // target environments. switch (ir_context->grammar().target_env()) { case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_3: + case SPV_ENV_VULKAN_1_0: + case SPV_ENV_VULKAN_1_1: return false; default: return true; @@ -199,14 +203,16 @@ bool TransformationSetLoopControl::PartialCountIsSupported( bool TransformationSetLoopControl::PeelCountIsSupported( opt::IRContext* ir_context) { - // TODO(afd): We capture the universal environments for which this loop - // control is definitely not supported. The check should be refined on - // demand for other target environments. + // TODO(afd): We capture the environments for which this loop control is + // definitely not supported. The check should be refined on demand for other + // target environments. switch (ir_context->grammar().target_env()) { case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_3: + case SPV_ENV_VULKAN_1_0: + case SPV_ENV_VULKAN_1_1: return false; default: return true; diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.h b/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.h index c3480b19b8..bc17c8a438 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.h +++ b/third_party/spirv-tools/source/fuzz/transformation_set_loop_control.h @@ -29,7 +29,7 @@ class TransformationSetLoopControl : public Transformation { const static uint32_t kLoopControlFirstLiteralInOperandIndex = 3; explicit TransformationSetLoopControl( - const protobufs::TransformationSetLoopControl& message); + protobufs::TransformationSetLoopControl message); TransformationSetLoopControl(uint32_t block_id, uint32_t loop_control, uint32_t peel_count, uint32_t partial_count); diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.cpp b/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.cpp index deb207aea9..5a986ad2c9 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.cpp @@ -29,9 +29,8 @@ const uint32_t kOpCopyMemorySizedFirstMemoryOperandsMaskIndex = 3; } // namespace TransformationSetMemoryOperandsMask::TransformationSetMemoryOperandsMask( - const spvtools::fuzz::protobufs::TransformationSetMemoryOperandsMask& - message) - : message_(message) {} + protobufs::TransformationSetMemoryOperandsMask message) + : message_(std::move(message)) {} TransformationSetMemoryOperandsMask::TransformationSetMemoryOperandsMask( const protobufs::InstructionDescriptor& memory_access_instruction, @@ -53,7 +52,9 @@ bool TransformationSetMemoryOperandsMask::IsApplicable( SpvOpCopyMemory || message_.memory_access_instruction().target_instruction_opcode() == SpvOpCopyMemorySized); - assert(MultipleMemoryOperandMasksAreSupported(ir_context)); + assert(MultipleMemoryOperandMasksAreSupported(ir_context) && + "Multiple memory operand masks are not supported for this SPIR-V " + "version."); } auto instruction = @@ -205,14 +206,16 @@ uint32_t TransformationSetMemoryOperandsMask::GetInOperandIndexForMask( bool TransformationSetMemoryOperandsMask:: MultipleMemoryOperandMasksAreSupported(opt::IRContext* ir_context) { - // TODO(afd): We capture the universal environments for which this loop - // control is definitely not supported. The check should be refined on - // demand for other target environments. + // TODO(afd): We capture the environments for which this loop control is + // definitely not supported. The check should be refined on demand for other + // target environments. switch (ir_context->grammar().target_env()) { case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_3: + case SPV_ENV_VULKAN_1_0: + case SPV_ENV_VULKAN_1_1: return false; default: return true; diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.h b/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.h index 7357b1ad99..c52fbdba14 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.h +++ b/third_party/spirv-tools/source/fuzz/transformation_set_memory_operands_mask.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationSetMemoryOperandsMask : public Transformation { public: explicit TransformationSetMemoryOperandsMask( - const protobufs::TransformationSetMemoryOperandsMask& message); + protobufs::TransformationSetMemoryOperandsMask message); TransformationSetMemoryOperandsMask( const protobufs::InstructionDescriptor& memory_access_instruction, diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.cpp b/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.cpp index 625187ea5a..6dddbdf831 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.cpp @@ -18,8 +18,8 @@ namespace spvtools { namespace fuzz { TransformationSetSelectionControl::TransformationSetSelectionControl( - const spvtools::fuzz::protobufs::TransformationSetSelectionControl& message) - : message_(message) {} + protobufs::TransformationSetSelectionControl message) + : message_(std::move(message)) {} TransformationSetSelectionControl::TransformationSetSelectionControl( uint32_t block_id, uint32_t selection_control) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.h b/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.h index 56b588529c..93b190498f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.h +++ b/third_party/spirv-tools/source/fuzz/transformation_set_selection_control.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationSetSelectionControl : public Transformation { public: explicit TransformationSetSelectionControl( - const protobufs::TransformationSetSelectionControl& message); + protobufs::TransformationSetSelectionControl message); TransformationSetSelectionControl(uint32_t block_id, uint32_t selection_control); diff --git a/third_party/spirv-tools/source/fuzz/transformation_split_block.cpp b/third_party/spirv-tools/source/fuzz/transformation_split_block.cpp index b383c405f4..e15dffa360 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_split_block.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_split_block.cpp @@ -24,8 +24,8 @@ namespace spvtools { namespace fuzz { TransformationSplitBlock::TransformationSplitBlock( - const spvtools::fuzz::protobufs::TransformationSplitBlock& message) - : message_(message) {} + protobufs::TransformationSplitBlock message) + : message_(std::move(message)) {} TransformationSplitBlock::TransformationSplitBlock( const protobufs::InstructionDescriptor& instruction_to_split_before, @@ -109,24 +109,37 @@ void TransformationSplitBlock::Apply( split_before); // The split does not automatically add a branch between the two parts of // the original block, so we add one. - block_to_split->AddInstruction(MakeUnique( + auto branch_instruction = MakeUnique( ir_context, SpvOpBranch, 0, 0, std::initializer_list{opt::Operand( - spv_operand_type_t::SPV_OPERAND_TYPE_ID, {message_.fresh_id()})})); + spv_operand_type_t::SPV_OPERAND_TYPE_ID, {message_.fresh_id()})}); + auto branch_instruction_ptr = branch_instruction.get(); + block_to_split->AddInstruction(std::move(branch_instruction)); + + // Inform the def-use manager about the branch instruction, and record its + // block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(branch_instruction_ptr); + ir_context->set_instr_block(branch_instruction_ptr, block_to_split); + // If we split before OpPhi instructions, we need to update their // predecessor operand so that the block they used to be inside is now the // predecessor. - new_bb->ForEachPhiInst([block_to_split](opt::Instruction* phi_inst) { + new_bb->ForEachPhiInst([block_to_split, + ir_context](opt::Instruction* phi_inst) { assert( phi_inst->NumInOperands() == 2 && "Precondition: a block can only be split before an OpPhi if the block" "has exactly one predecessor."); phi_inst->SetInOperand(1, {block_to_split->id()}); + ir_context->UpdateDefUse(phi_inst); }); - // Invalidate all analyses + // We have updated the def-use manager and the instruction to block mapping, + // but other analyses (especially control flow-related ones) need to be + // recomputed. ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + opt::IRContext::Analysis::kAnalysisDefUse | + opt::IRContext::Analysis::kAnalysisInstrToBlockMapping); // If the block being split was dead, the new block arising from the split is // also dead. diff --git a/third_party/spirv-tools/source/fuzz/transformation_split_block.h b/third_party/spirv-tools/source/fuzz/transformation_split_block.h index 27bf6f8cec..ace77b5bec 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_split_block.h +++ b/third_party/spirv-tools/source/fuzz/transformation_split_block.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationSplitBlock : public Transformation { public: explicit TransformationSplitBlock( - const protobufs::TransformationSplitBlock& message); + protobufs::TransformationSplitBlock message); TransformationSplitBlock( const protobufs::InstructionDescriptor& instruction_to_split_before, diff --git a/third_party/spirv-tools/source/fuzz/transformation_store.cpp b/third_party/spirv-tools/source/fuzz/transformation_store.cpp index 460ca01621..f8c6d013ba 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_store.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_store.cpp @@ -20,9 +20,8 @@ namespace spvtools { namespace fuzz { -TransformationStore::TransformationStore( - const spvtools::fuzz::protobufs::TransformationStore& message) - : message_(message) {} +TransformationStore::TransformationStore(protobufs::TransformationStore message) + : message_(std::move(message)) {} TransformationStore::TransformationStore( uint32_t pointer_id, uint32_t value_id, @@ -110,13 +109,20 @@ bool TransformationStore::IsApplicable( void TransformationStore::Apply(opt::IRContext* ir_context, TransformationContext* /*unused*/) const { - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( - ir_context, SpvOpStore, 0, 0, - opt::Instruction::OperandList( - {{SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}, - {SPV_OPERAND_TYPE_ID, {message_.value_id()}}}))); - ir_context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + auto insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + auto new_instruction = MakeUnique( + ir_context, SpvOpStore, 0, 0, + opt::Instruction::OperandList( + {{SPV_OPERAND_TYPE_ID, {message_.pointer_id()}}, + {SPV_OPERAND_TYPE_ID, {message_.value_id()}}})); + auto new_instruction_ptr = new_instruction.get(); + insert_before->InsertBefore(std::move(new_instruction)); + // Inform the def-use manager about the new instruction and record its basic + // block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, + ir_context->get_instr_block(insert_before)); } protobufs::Transformation TransformationStore::ToMessage() const { diff --git a/third_party/spirv-tools/source/fuzz/transformation_store.h b/third_party/spirv-tools/source/fuzz/transformation_store.h index 705204893b..18ba1d7d22 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_store.h +++ b/third_party/spirv-tools/source/fuzz/transformation_store.h @@ -25,7 +25,7 @@ namespace fuzz { class TransformationStore : public Transformation { public: - explicit TransformationStore(const protobufs::TransformationStore& message); + explicit TransformationStore(protobufs::TransformationStore message); TransformationStore( uint32_t pointer_id, uint32_t value_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.cpp b/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.cpp index b8bdb79069..a02e95a094 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.cpp @@ -21,9 +21,8 @@ namespace spvtools { namespace fuzz { TransformationSwapCommutableOperands::TransformationSwapCommutableOperands( - const spvtools::fuzz::protobufs::TransformationSwapCommutableOperands& - message) - : message_(message) {} + protobufs::TransformationSwapCommutableOperands message) + : message_(std::move(message)) {} TransformationSwapCommutableOperands::TransformationSwapCommutableOperands( const protobufs::InstructionDescriptor& instruction_descriptor) { diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.h b/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.h index c291c3eab9..5e211f197f 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.h +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_commutable_operands.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationSwapCommutableOperands : public Transformation { public: explicit TransformationSwapCommutableOperands( - const protobufs::TransformationSwapCommutableOperands& message); + protobufs::TransformationSwapCommutableOperands message); TransformationSwapCommutableOperands( const protobufs::InstructionDescriptor& instruction_descriptor); diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.cpp b/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.cpp index 866fee6691..340836d1e7 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationSwapConditionalBranchOperands:: TransformationSwapConditionalBranchOperands( - const spvtools::fuzz::protobufs:: - TransformationSwapConditionalBranchOperands& message) - : message_(message) {} + protobufs::TransformationSwapConditionalBranchOperands message) + : message_(std::move(message)) {} TransformationSwapConditionalBranchOperands:: TransformationSwapConditionalBranchOperands( @@ -70,11 +69,13 @@ void TransformationSwapConditionalBranchOperands::Apply( // We are swapping the labels in OpBranchConditional. This means that we must // invert the guard as well. We are using OpLogicalNot for that purpose here. - iter.InsertBefore(MakeUnique( + auto new_instruction = MakeUnique( ir_context, SpvOpLogicalNot, condition_inst->type_id(), message_.fresh_id(), opt::Instruction::OperandList{ - {SPV_OPERAND_TYPE_ID, {condition_inst->result_id()}}})); + {SPV_OPERAND_TYPE_ID, {condition_inst->result_id()}}}); + auto new_instruction_ptr = new_instruction.get(); + iter.InsertBefore(std::move(new_instruction)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); @@ -89,9 +90,13 @@ void TransformationSwapConditionalBranchOperands::Apply( std::swap(branch_inst->GetInOperand(3), branch_inst->GetInOperand(4)); } - // Make sure the changes are analyzed. - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction_ptr); + ir_context->set_instr_block(new_instruction_ptr, block); + ir_context->get_def_use_mgr()->EraseUseRecordsOfOperandIds(branch_inst); + ir_context->get_def_use_mgr()->AnalyzeInstUse(branch_inst); + + // No analyses need to be invalidated since the transformation is local to a + // block and the def-use and instruction-to-block mappings have been updated. } protobufs::Transformation diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.h b/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.h index 022c54a79b..165ab806b3 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.h +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_conditional_branch_operands.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationSwapConditionalBranchOperands : public Transformation { public: explicit TransformationSwapConditionalBranchOperands( - const protobufs::TransformationSwapConditionalBranchOperands& message); + protobufs::TransformationSwapConditionalBranchOperands message); TransformationSwapConditionalBranchOperands( const protobufs::InstructionDescriptor& instruction_descriptor, diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_function_variables.cpp b/third_party/spirv-tools/source/fuzz/transformation_swap_function_variables.cpp new file mode 100644 index 0000000000..aec32fe12b --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_function_variables.cpp @@ -0,0 +1,93 @@ +// Copyright (c) 2021 Mostafa Ashraf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/transformation_swap_function_variables.h" + +#include "source/fuzz/fuzzer_util.h" + +namespace spvtools { +namespace fuzz { + +TransformationSwapFunctionVariables::TransformationSwapFunctionVariables( + protobufs::TransformationSwapFunctionVariables message) + : message_(std::move(message)) {} + +TransformationSwapFunctionVariables::TransformationSwapFunctionVariables( + uint32_t result_id1, uint32_t result_id2) { + message_.set_result_id1(result_id1); + message_.set_result_id2(result_id2); +} + +bool TransformationSwapFunctionVariables::IsApplicable( + opt::IRContext* ir_context, const TransformationContext& /*unused*/) const { + uint32_t result_id1 = message_.result_id1(); + uint32_t result_id2 = message_.result_id2(); + + assert((result_id1 != result_id2) && "Two results ids are equal"); + + // The result ids used in the message must refer to instructions. + auto instruction1 = ir_context->get_def_use_mgr()->GetDef(result_id1); + auto instruction2 = ir_context->get_def_use_mgr()->GetDef(result_id2); + if (instruction1 == nullptr || instruction2 == nullptr) { + return false; + } + // Both instructions must be variables. + if (instruction1->opcode() != SpvOpVariable || + instruction2->opcode() != SpvOpVariable) { + return false; + } + + // Both variable instructions must be in some basic block (as they are + // function-local variables), and they must be in the same block (as they need + // to be variables of the same function). + auto* block_1 = ir_context->get_instr_block(result_id1); + auto* block_2 = ir_context->get_instr_block(result_id2); + if (block_1 == nullptr || block_2 == nullptr) { + return false; + } + + return block_1 == block_2; +} + +void TransformationSwapFunctionVariables::Apply( + opt::IRContext* ir_context, TransformationContext* /*unused*/) const { + // The result ids used in the message must refer to instructions. + auto instruction1 = + ir_context->get_def_use_mgr()->GetDef(message_.result_id1()); + auto instruction2 = + ir_context->get_def_use_mgr()->GetDef(message_.result_id2()); + + std::unique_ptr temp_instruction = + MakeUnique(); + + temp_instruction->InsertBefore(instruction1); + instruction1->InsertAfter(instruction2); + instruction2->InsertAfter(temp_instruction.get()); + temp_instruction->RemoveFromList(); +} + +protobufs::Transformation TransformationSwapFunctionVariables::ToMessage() + const { + protobufs::Transformation result; + *result.mutable_swap_function_variables() = message_; + return result; +} + +std::unordered_set TransformationSwapFunctionVariables::GetFreshIds() + const { + return std::unordered_set(); +} + +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_function_variables.h b/third_party/spirv-tools/source/fuzz/transformation_swap_function_variables.h new file mode 100644 index 0000000000..eb383f4ff7 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_function_variables.h @@ -0,0 +1,57 @@ +// Copyright (c) 2021 Mostafa Ashraf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_FUZZ_TRANSFORMATION_SWAP_FUNCTION_VARIABLES_H_ +#define SOURCE_FUZZ_TRANSFORMATION_SWAP_FUNCTION_VARIABLES_H_ + +#include "source/fuzz/protobufs/spirvfuzz_protobufs.h" +#include "source/fuzz/transformation.h" +#include "source/fuzz/transformation_context.h" +#include "source/opt/ir_context.h" + +namespace spvtools { +namespace fuzz { + +// A transformation that swaps two variable declaration instructions that appear +// in the same function. +class TransformationSwapFunctionVariables : public Transformation { + public: + explicit TransformationSwapFunctionVariables( + protobufs::TransformationSwapFunctionVariables message); + + TransformationSwapFunctionVariables(uint32_t result_id1, uint32_t result_id2); + + // - |message_.result_id1| and |message_.result_id2| must be the ids of + // distinct OpVariable instructions appearing in the same function. + bool IsApplicable( + opt::IRContext* ir_context, + const TransformationContext& transformation_context) const override; + + // Swaps two OpVariable instructions with result ids |message_.result_id1| + // and |message_.result_id2|. + void Apply(opt::IRContext* ir_context, + TransformationContext* transformation_context) const override; + + protobufs::Transformation ToMessage() const override; + + std::unordered_set GetFreshIds() const override; + + private: + protobufs::TransformationSwapFunctionVariables message_; +}; + +} // namespace fuzz +} // namespace spvtools + +#endif // SOURCE_FUZZ_TRANSFORMATION_SWAP_FUNCTION_VARIABLES_H_ diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_two_functions.cpp b/third_party/spirv-tools/source/fuzz/transformation_swap_two_functions.cpp new file mode 100644 index 0000000000..85d9e79c17 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_two_functions.cpp @@ -0,0 +1,72 @@ +// Copyright (c) 2021 Shiyu Liu +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/transformation_swap_two_functions.h" + +#include "source/opt/function.h" +#include "source/opt/module.h" + +#include "source/fuzz/fuzzer_util.h" + +namespace spvtools { +namespace fuzz { + +TransformationSwapTwoFunctions::TransformationSwapTwoFunctions( + protobufs::TransformationSwapTwoFunctions message) + : message_(std::move(message)) {} + +TransformationSwapTwoFunctions::TransformationSwapTwoFunctions(uint32_t id1, + uint32_t id2) { + assert(id1 != id2 && "The two function ids cannot be the same."); + message_.set_function_id1(id1); + message_.set_function_id2(id2); +} + +bool TransformationSwapTwoFunctions::IsApplicable( + opt::IRContext* ir_context, const TransformationContext& /*unused*/) const { + auto func1_ptr = ir_context->GetFunction(message_.function_id1()); + auto func2_ptr = ir_context->GetFunction(message_.function_id2()); + return func1_ptr != nullptr && func2_ptr != nullptr; +} + +void TransformationSwapTwoFunctions::Apply( + opt::IRContext* ir_context, TransformationContext* /*unused*/) const { + opt::Module::iterator func1_it = + fuzzerutil::GetFunctionIterator(ir_context, message_.function_id1()); + opt::Module::iterator func2_it = + fuzzerutil::GetFunctionIterator(ir_context, message_.function_id2()); + + assert(func1_it != ir_context->module()->end() && + "Could not find function 1."); + assert(func2_it != ir_context->module()->end() && + "Could not find function 2."); + + // Two function pointers are all set, swap the two functions within the + // module. + std::iter_swap(func1_it.Get(), func2_it.Get()); +} + +protobufs::Transformation TransformationSwapTwoFunctions::ToMessage() const { + protobufs::Transformation result; + *result.mutable_swap_two_functions() = message_; + return result; +} + +std::unordered_set TransformationSwapTwoFunctions::GetFreshIds() + const { + return std::unordered_set(); +} + +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/source/fuzz/transformation_swap_two_functions.h b/third_party/spirv-tools/source/fuzz/transformation_swap_two_functions.h new file mode 100644 index 0000000000..1b6d6e80d4 --- /dev/null +++ b/third_party/spirv-tools/source/fuzz/transformation_swap_two_functions.h @@ -0,0 +1,56 @@ +// Copyright (c) 2021 Shiyu Liu +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_FUZZ_TRANSFORMATION_SWAP_TWO_FUNCTIONS_H_ +#define SOURCE_FUZZ_TRANSFORMATION_SWAP_TWO_FUNCTIONS_H_ + +#include "source/fuzz/protobufs/spirvfuzz_protobufs.h" +#include "source/fuzz/transformation.h" +#include "source/fuzz/transformation_context.h" +#include "source/opt/ir_context.h" + +namespace spvtools { +namespace fuzz { + +class TransformationSwapTwoFunctions : public Transformation { + public: + explicit TransformationSwapTwoFunctions( + protobufs::TransformationSwapTwoFunctions message); + + TransformationSwapTwoFunctions(uint32_t function_id1, uint32_t function_id2); + + // |function_id1| and |function_id1| should all be existing ids. + // Swap function operation is only permitted if: + // - both ids must be ids of functions. + // - both ids can be found in the module. + // - function_id1 and function_id2 are not the same. + bool IsApplicable( + opt::IRContext* ir_context, + const TransformationContext& transformation_context) const override; + + // OpFunction with |function_id1| and |function_id1| are swapped. + void Apply(opt::IRContext* ir_context, + TransformationContext* transformation_context) const override; + + std::unordered_set GetFreshIds() const override; + protobufs::Transformation ToMessage() const override; + + private: + protobufs::TransformationSwapTwoFunctions message_; +}; + +} // namespace fuzz +} // namespace spvtools + +#endif // SOURCE_FUZZ_TRANSFORMATION_SWAP_TWO_FUNCTIONS_H_ diff --git a/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.cpp b/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.cpp index 1952a3439a..34523fe8d2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.cpp @@ -22,9 +22,8 @@ namespace fuzz { TransformationToggleAccessChainInstruction:: TransformationToggleAccessChainInstruction( - const spvtools::fuzz::protobufs:: - TransformationToggleAccessChainInstruction& message) - : message_(message) {} + protobufs::TransformationToggleAccessChainInstruction message) + : message_(std::move(message)) {} TransformationToggleAccessChainInstruction:: TransformationToggleAccessChainInstruction( diff --git a/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.h b/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.h index 977b0d7ad3..be2718b069 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.h +++ b/third_party/spirv-tools/source/fuzz/transformation_toggle_access_chain_instruction.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationToggleAccessChainInstruction : public Transformation { public: explicit TransformationToggleAccessChainInstruction( - const protobufs::TransformationToggleAccessChainInstruction& message); + protobufs::TransformationToggleAccessChainInstruction message); TransformationToggleAccessChainInstruction( const protobufs::InstructionDescriptor& instruction_descriptor); diff --git a/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.cpp b/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.cpp index 05af18e69e..ac0e3ccba2 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.cpp @@ -21,8 +21,8 @@ namespace spvtools { namespace fuzz { TransformationVectorShuffle::TransformationVectorShuffle( - const spvtools::fuzz::protobufs::TransformationVectorShuffle& message) - : message_(message) {} + protobufs::TransformationVectorShuffle message) + : message_(std::move(message)) {} TransformationVectorShuffle::TransformationVectorShuffle( const protobufs::InstructionDescriptor& instruction_to_insert_before, @@ -130,13 +130,18 @@ void TransformationVectorShuffle::Apply( // Add a shuffle instruction right before the instruction identified by // |message_.instruction_to_insert_before|. - FindInstruction(message_.instruction_to_insert_before(), ir_context) - ->InsertBefore(MakeUnique( + auto insert_before = + FindInstruction(message_.instruction_to_insert_before(), ir_context); + opt::Instruction* new_instruction = + insert_before->InsertBefore(MakeUnique( ir_context, SpvOpVectorShuffle, result_type_id, message_.fresh_id(), shuffle_operands)); fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id()); - ir_context->InvalidateAnalysesExceptFor( - opt::IRContext::Analysis::kAnalysisNone); + // Inform the def-use manager about the new instruction and record its basic + // block. + ir_context->get_def_use_mgr()->AnalyzeInstDefUse(new_instruction); + ir_context->set_instr_block(new_instruction, + ir_context->get_instr_block(insert_before)); AddDataSynonymFacts(ir_context, transformation_context); } diff --git a/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.h b/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.h index cf08a62c09..7360906fb0 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.h +++ b/third_party/spirv-tools/source/fuzz/transformation_vector_shuffle.h @@ -27,7 +27,7 @@ namespace fuzz { class TransformationVectorShuffle : public Transformation { public: explicit TransformationVectorShuffle( - const protobufs::TransformationVectorShuffle& message); + protobufs::TransformationVectorShuffle message); TransformationVectorShuffle( const protobufs::InstructionDescriptor& instruction_to_insert_before, diff --git a/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.cpp b/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.cpp index 4c436f5e99..468d809ffb 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.cpp @@ -23,9 +23,8 @@ namespace fuzz { TransformationWrapEarlyTerminatorInFunction:: TransformationWrapEarlyTerminatorInFunction( - const spvtools::fuzz::protobufs:: - TransformationWrapEarlyTerminatorInFunction& message) - : message_(message) {} + protobufs::TransformationWrapEarlyTerminatorInFunction message) + : message_(std::move(message)) {} TransformationWrapEarlyTerminatorInFunction:: TransformationWrapEarlyTerminatorInFunction( diff --git a/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.h b/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.h index 00151d402d..d6e55517ce 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.h +++ b/third_party/spirv-tools/source/fuzz/transformation_wrap_early_terminator_in_function.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationWrapEarlyTerminatorInFunction : public Transformation { public: explicit TransformationWrapEarlyTerminatorInFunction( - const protobufs::TransformationWrapEarlyTerminatorInFunction& message); + protobufs::TransformationWrapEarlyTerminatorInFunction message); TransformationWrapEarlyTerminatorInFunction( uint32_t fresh_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.cpp b/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.cpp index 9924e36843..01c98cca2d 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.cpp +++ b/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.cpp @@ -20,8 +20,8 @@ namespace spvtools { namespace fuzz { TransformationWrapRegionInSelection::TransformationWrapRegionInSelection( - const protobufs::TransformationWrapRegionInSelection& message) - : message_(message) {} + protobufs::TransformationWrapRegionInSelection message) + : message_(std::move(message)) {} TransformationWrapRegionInSelection::TransformationWrapRegionInSelection( uint32_t region_entry_block_id, uint32_t region_exit_block_id, diff --git a/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.h b/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.h index 57f4f64fc3..66d16dad36 100644 --- a/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.h +++ b/third_party/spirv-tools/source/fuzz/transformation_wrap_region_in_selection.h @@ -26,7 +26,7 @@ namespace fuzz { class TransformationWrapRegionInSelection : public Transformation { public: explicit TransformationWrapRegionInSelection( - const protobufs::TransformationWrapRegionInSelection& message); + protobufs::TransformationWrapRegionInSelection message); TransformationWrapRegionInSelection(uint32_t region_entry_block_id, uint32_t region_exit_block_id, diff --git a/third_party/spirv-tools/source/libspirv.cpp b/third_party/spirv-tools/source/libspirv.cpp index a1ed11d3fb..0bc0935083 100644 --- a/third_party/spirv-tools/source/libspirv.cpp +++ b/third_party/spirv-tools/source/libspirv.cpp @@ -14,8 +14,8 @@ #include "spirv-tools/libspirv.hpp" +#include #include - #include #include #include @@ -60,7 +60,9 @@ struct SpirvTools::Impl { spv_context context; // C interface context object. }; -SpirvTools::SpirvTools(spv_target_env env) : impl_(new Impl(env)) {} +SpirvTools::SpirvTools(spv_target_env env) : impl_(new Impl(env)) { + assert(env != SPV_ENV_WEBGPU_0); +} SpirvTools::~SpirvTools() {} diff --git a/third_party/spirv-tools/source/link/linker.cpp b/third_party/spirv-tools/source/link/linker.cpp index da6f0a78c7..8da4a98d88 100644 --- a/third_party/spirv-tools/source/link/linker.cpp +++ b/third_party/spirv-tools/source/link/linker.cpp @@ -676,14 +676,15 @@ spv_result_t Link(const Context& context, const uint32_t* const* binaries, if (schema != 0u) { position.index = 4u; return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY) - << "Schema is non-zero for module " << i << "."; + << "Schema is non-zero for module " << i + 1 << "."; } std::unique_ptr ir_context = BuildModule( c_context->target_env, consumer, binaries[i], binary_sizes[i]); if (ir_context == nullptr) return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY) - << "Failed to build a module out of " << ir_contexts.size() << "."; + << "Failed to build module " << i + 1 << " out of " << num_binaries + << "."; modules.push_back(ir_context->module()); ir_contexts.push_back(std::move(ir_context)); } diff --git a/third_party/spirv-tools/source/opcode.cpp b/third_party/spirv-tools/source/opcode.cpp index 8305bcf0a9..c96cde8d69 100644 --- a/third_party/spirv-tools/source/opcode.cpp +++ b/third_party/spirv-tools/source/opcode.cpp @@ -337,7 +337,7 @@ int32_t spvOpcodeGeneratesType(SpvOp op) { case SpvOpTypeCooperativeMatrixNV: // case SpvOpTypeAccelerationStructureKHR: covered by // SpvOpTypeAccelerationStructureNV - case SpvOpTypeRayQueryProvisionalKHR: + case SpvOpTypeRayQueryKHR: return true; default: // In particular, OpTypeForwardPointer does not generate a type, @@ -417,8 +417,10 @@ bool spvOpcodeIsAtomicWithLoad(const SpvOp opcode) { case SpvOpAtomicISub: case SpvOpAtomicSMin: case SpvOpAtomicUMin: + case SpvOpAtomicFMinEXT: case SpvOpAtomicSMax: case SpvOpAtomicUMax: + case SpvOpAtomicFMaxEXT: case SpvOpAtomicAnd: case SpvOpAtomicOr: case SpvOpAtomicXor: @@ -444,15 +446,32 @@ bool spvOpcodeIsReturn(SpvOp opcode) { } } +bool spvOpcodeIsAbort(SpvOp opcode) { + switch (opcode) { + case SpvOpKill: + case SpvOpUnreachable: + case SpvOpTerminateInvocation: + case SpvOpTerminateRayKHR: + case SpvOpIgnoreIntersectionKHR: + return true; + default: + return false; + } +} + bool spvOpcodeIsReturnOrAbort(SpvOp opcode) { - return spvOpcodeIsReturn(opcode) || opcode == SpvOpKill || - opcode == SpvOpUnreachable || opcode == SpvOpTerminateInvocation; + return spvOpcodeIsReturn(opcode) || spvOpcodeIsAbort(opcode); } bool spvOpcodeIsBlockTerminator(SpvOp opcode) { return spvOpcodeIsBranch(opcode) || spvOpcodeIsReturnOrAbort(opcode); } +bool spvOpcodeTerminatesExecution(SpvOp opcode) { + return opcode == SpvOpKill || opcode == SpvOpTerminateInvocation || + opcode == SpvOpTerminateRayKHR || opcode == SpvOpIgnoreIntersectionKHR; +} + bool spvOpcodeIsBaseOpaqueType(SpvOp opcode) { switch (opcode) { case SpvOpTypeImage: diff --git a/third_party/spirv-tools/source/opcode.h b/third_party/spirv-tools/source/opcode.h index 3702cb35fb..c8525a253a 100644 --- a/third_party/spirv-tools/source/opcode.h +++ b/third_party/spirv-tools/source/opcode.h @@ -110,10 +110,18 @@ bool spvOpcodeIsBranch(SpvOp opcode); // Returns true if the given opcode is a return instruction. bool spvOpcodeIsReturn(SpvOp opcode); +// Returns true if the given opcode aborts execution. +bool spvOpcodeIsAbort(SpvOp opcode); + // Returns true if the given opcode is a return instruction or it aborts // execution. bool spvOpcodeIsReturnOrAbort(SpvOp opcode); +// Returns true if the given opcode is a kill instruction or it terminates +// execution. Note that branches, returns, and unreachables do not terminate +// execution. +bool spvOpcodeTerminatesExecution(SpvOp opcode); + // Returns true if the given opcode is a basic block terminator. bool spvOpcodeIsBlockTerminator(SpvOp opcode); diff --git a/third_party/spirv-tools/source/operand.cpp b/third_party/spirv-tools/source/operand.cpp index d4b64a8b82..c00c9b64ed 100644 --- a/third_party/spirv-tools/source/operand.cpp +++ b/third_party/spirv-tools/source/operand.cpp @@ -24,6 +24,7 @@ #include "DebugInfo.h" #include "OpenCLDebugInfo100.h" #include "source/macro.h" +#include "source/opcode.h" #include "source/spirv_constant.h" #include "source/spirv_target_env.h" @@ -228,6 +229,9 @@ const char* spvOperandTypeStr(spv_operand_type_t type) { return "ray query committed intersection type"; case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE: return "ray query candidate intersection type"; + case SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT: + case SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT: + return "packed vector format"; case SPV_OPERAND_TYPE_IMAGE: case SPV_OPERAND_TYPE_OPTIONAL_IMAGE: return "image"; @@ -264,6 +268,15 @@ const char* spvOperandTypeStr(spv_operand_type_t type) { case SPV_OPERAND_TYPE_IMAGE_CHANNEL_DATA_TYPE: return "image channel data type"; + case SPV_OPERAND_TYPE_FPDENORM_MODE: + return "FP denorm mode"; + case SPV_OPERAND_TYPE_FPOPERATION_MODE: + return "FP operation mode"; + case SPV_OPERAND_TYPE_QUANTIZATION_MODES: + return "quantization mode"; + case SPV_OPERAND_TYPE_OVERFLOW_MODES: + return "overflow mode"; + case SPV_OPERAND_TYPE_NONE: return "NONE"; default: @@ -347,6 +360,11 @@ bool spvOperandIsConcrete(spv_operand_type_t type) { case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER: case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION: case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: + case SPV_OPERAND_TYPE_FPDENORM_MODE: + case SPV_OPERAND_TYPE_FPOPERATION_MODE: + case SPV_OPERAND_TYPE_QUANTIZATION_MODES: + case SPV_OPERAND_TYPE_OVERFLOW_MODES: + case SPV_OPERAND_TYPE_PACKED_VECTOR_FORMAT: return true; default: break; @@ -382,6 +400,7 @@ bool spvOperandIsOptional(spv_operand_type_t type) { case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER: case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: case SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER: + case SPV_OPERAND_TYPE_OPTIONAL_PACKED_VECTOR_FORMAT: case SPV_OPERAND_TYPE_OPTIONAL_CIV: return true; default: @@ -491,6 +510,11 @@ bool spvIsInIdType(spv_operand_type_t type) { std::function spvOperandCanBeForwardDeclaredFunction( SpvOp opcode) { std::function out; + if (spvOpcodeGeneratesType(opcode)) { + // All types can use forward pointers. + out = [](unsigned) { return true; }; + return out; + } switch (opcode) { case SpvOpExecutionMode: case SpvOpExecutionModeId: @@ -503,7 +527,6 @@ std::function spvOperandCanBeForwardDeclaredFunction( case SpvOpDecorateId: case SpvOpDecorateStringGOOGLE: case SpvOpMemberDecorateStringGOOGLE: - case SpvOpTypeStruct: case SpvOpBranch: case SpvOpLoopMerge: out = [](unsigned) { return true; }; diff --git a/third_party/spirv-tools/source/opt/CMakeLists.txt b/third_party/spirv-tools/source/opt/CMakeLists.txt index f3ac59060c..0e41b20581 100644 --- a/third_party/spirv-tools/source/opt/CMakeLists.txt +++ b/third_party/spirv-tools/source/opt/CMakeLists.txt @@ -32,7 +32,6 @@ set(SPIRV_TOOLS_OPT_SOURCES dead_branch_elim_pass.h dead_insert_elim_pass.h dead_variable_elimination.h - decompose_initialized_variables_pass.h decoration_manager.h debug_info_manager.h def_use_manager.h @@ -52,7 +51,6 @@ set(SPIRV_TOOLS_OPT_SOURCES fold_spec_constant_op_and_composite_pass.h freeze_spec_constant_value_pass.h function.h - generate_webgpu_initializers_pass.h graphics_robust_access_pass.h if_conversion.h inline_exhaustive_pass.h @@ -64,6 +62,7 @@ set(SPIRV_TOOLS_OPT_SOURCES instruction.h instruction_list.h instrument_pass.h + interp_fixup_pass.h ir_builder.h ir_context.h ir_loader.h @@ -97,16 +96,15 @@ set(SPIRV_TOOLS_OPT_SOURCES register_pressure.h relax_float_ops_pass.h remove_duplicates_pass.h + remove_unused_interface_variables_pass.h replace_invalid_opc.h scalar_analysis.h scalar_analysis_nodes.h scalar_replacement_pass.h set_spec_constant_default_value_pass.h simplification_pass.h - split_invalid_unreachable_pass.h ssa_rewrite_pass.h strength_reduction_pass.h - strip_atomic_counter_memory_pass.h strip_debug_info_pass.h strip_reflect_info_pass.h struct_cfg_analysis.h @@ -140,7 +138,6 @@ set(SPIRV_TOOLS_OPT_SOURCES dead_branch_elim_pass.cpp dead_insert_elim_pass.cpp dead_variable_elimination.cpp - decompose_initialized_variables_pass.cpp decoration_manager.cpp debug_info_manager.cpp def_use_manager.cpp @@ -160,7 +157,6 @@ set(SPIRV_TOOLS_OPT_SOURCES freeze_spec_constant_value_pass.cpp function.cpp graphics_robust_access_pass.cpp - generate_webgpu_initializers_pass.cpp if_conversion.cpp inline_exhaustive_pass.cpp inline_opaque_pass.cpp @@ -171,9 +167,9 @@ set(SPIRV_TOOLS_OPT_SOURCES instruction.cpp instruction_list.cpp instrument_pass.cpp + interp_fixup_pass.cpp ir_context.cpp ir_loader.cpp - legalize_vector_shuffle_pass.cpp licm_pass.cpp local_access_chain_convert_pass.cpp local_redundancy_elimination.cpp @@ -202,16 +198,15 @@ set(SPIRV_TOOLS_OPT_SOURCES register_pressure.cpp relax_float_ops_pass.cpp remove_duplicates_pass.cpp + remove_unused_interface_variables_pass.cpp replace_invalid_opc.cpp scalar_analysis.cpp scalar_analysis_simplification.cpp scalar_replacement_pass.cpp set_spec_constant_default_value_pass.cpp simplification_pass.cpp - split_invalid_unreachable_pass.cpp ssa_rewrite_pass.cpp strength_reduction_pass.cpp - strip_atomic_counter_memory_pass.cpp strip_debug_info_pass.cpp strip_reflect_info_pass.cpp struct_cfg_analysis.cpp diff --git a/third_party/spirv-tools/source/opt/aggressive_dead_code_elim_pass.cpp b/third_party/spirv-tools/source/opt/aggressive_dead_code_elim_pass.cpp index 39d468f981..7cffff5700 100644 --- a/third_party/spirv-tools/source/opt/aggressive_dead_code_elim_pass.cpp +++ b/third_party/spirv-tools/source/opt/aggressive_dead_code_elim_pass.cpp @@ -991,9 +991,14 @@ void AggressiveDCEPass::InitExtensions() { "SPV_NV_mesh_shader", "SPV_NV_ray_tracing", "SPV_KHR_ray_tracing", + "SPV_KHR_ray_query", "SPV_EXT_fragment_invocation_density", "SPV_EXT_physical_storage_buffer", "SPV_KHR_terminate_invocation", + "SPV_KHR_shader_clock", + "SPV_KHR_vulkan_memory_model", + "SPV_KHR_subgroup_uniform_control_flow", + "SPV_KHR_integer_dot_product", }); } diff --git a/third_party/spirv-tools/source/opt/basic_block.cpp b/third_party/spirv-tools/source/opt/basic_block.cpp index 3608448ba8..e82a744af5 100644 --- a/third_party/spirv-tools/source/opt/basic_block.cpp +++ b/third_party/spirv-tools/source/opt/basic_block.cpp @@ -230,7 +230,7 @@ std::string BasicBlock::PrettyPrint(uint32_t options) const { std::ostringstream str; ForEachInst([&str, options](const Instruction* inst) { str << inst->PrettyPrint(options); - if (!IsTerminatorInst(inst->opcode())) { + if (!spvOpcodeIsBlockTerminator(inst->opcode())) { str << std::endl; } }); @@ -248,7 +248,8 @@ BasicBlock* BasicBlock::SplitBasicBlock(IRContext* context, uint32_t label_id, function_->InsertBasicBlockAfter(std::move(new_block_temp), this); new_block->insts_.Splice(new_block->end(), &insts_, iter, end()); - new_block->SetParent(GetParent()); + assert(new_block->GetParent() == GetParent() && + "The parent should already be set appropriately."); context->AnalyzeDefUse(new_block->GetLabelInst()); diff --git a/third_party/spirv-tools/source/opt/block_merge_pass.cpp b/third_party/spirv-tools/source/opt/block_merge_pass.cpp index c7315baf26..04e47f1c2e 100644 --- a/third_party/spirv-tools/source/opt/block_merge_pass.cpp +++ b/third_party/spirv-tools/source/opt/block_merge_pass.cpp @@ -28,7 +28,9 @@ namespace opt { bool BlockMergePass::MergeBlocks(Function* func) { bool modified = false; for (auto bi = func->begin(); bi != func->end();) { - if (blockmergeutil::CanMergeWithSuccessor(context(), &*bi)) { + // Don't bother trying to merge unreachable blocks. + if (context()->IsReachable(*bi) && + blockmergeutil::CanMergeWithSuccessor(context(), &*bi)) { blockmergeutil::MergeWithSuccessor(context(), func, bi); // Reprocess block. modified = true; diff --git a/third_party/spirv-tools/source/opt/block_merge_util.cpp b/third_party/spirv-tools/source/opt/block_merge_util.cpp index 14b5d36425..15e8c6ff9c 100644 --- a/third_party/spirv-tools/source/opt/block_merge_util.cpp +++ b/third_party/spirv-tools/source/opt/block_merge_util.cpp @@ -103,11 +103,6 @@ bool CanMergeWithSuccessor(IRContext* context, BasicBlock* block) { return false; } - // Don't bother trying to merge unreachable blocks. - if (auto dominators = context->GetDominatorAnalysis(block->GetParent())) { - if (!dominators->IsReachable(block)) return false; - } - Instruction* merge_inst = block->GetMergeInst(); const bool pred_is_header = IsHeader(block); if (pred_is_header && lab_id != merge_inst->GetSingleWordInOperand(0u)) { diff --git a/third_party/spirv-tools/source/opt/build_module.cpp b/third_party/spirv-tools/source/opt/build_module.cpp index fc76a3c29d..3b606dc2b5 100644 --- a/third_party/spirv-tools/source/opt/build_module.cpp +++ b/third_party/spirv-tools/source/opt/build_module.cpp @@ -50,11 +50,20 @@ std::unique_ptr BuildModule(spv_target_env env, MessageConsumer consumer, const uint32_t* binary, const size_t size) { + return BuildModule(env, consumer, binary, size, true); +} + +std::unique_ptr BuildModule(spv_target_env env, + MessageConsumer consumer, + const uint32_t* binary, + const size_t size, + bool extra_line_tracking) { auto context = spvContextCreate(env); SetContextMessageConsumer(context, consumer); auto irContext = MakeUnique(env, consumer); opt::IrLoader loader(consumer, irContext->module()); + loader.SetExtraLineTracking(extra_line_tracking); spv_result_t status = spvBinaryParse(context, &loader, binary, size, SetSpvHeader, SetSpvInst, nullptr); diff --git a/third_party/spirv-tools/source/opt/build_module.h b/third_party/spirv-tools/source/opt/build_module.h index c9d1cf2e45..29eaf66139 100644 --- a/third_party/spirv-tools/source/opt/build_module.h +++ b/third_party/spirv-tools/source/opt/build_module.h @@ -27,7 +27,15 @@ namespace spvtools { // Builds an Module returns the owning IRContext from the given SPIR-V // |binary|. |size| specifies number of words in |binary|. The |binary| will be // decoded according to the given target |env|. Returns nullptr if errors occur -// and sends the errors to |consumer|. +// and sends the errors to |consumer|. When |extra_line_tracking| is true, +// extra OpLine instructions are injected to better presere line numbers while +// later transforms mutate the module. +std::unique_ptr BuildModule(spv_target_env env, + MessageConsumer consumer, + const uint32_t* binary, size_t size, + bool extra_line_tracking); + +// Like above, with extra line tracking turned on. std::unique_ptr BuildModule(spv_target_env env, MessageConsumer consumer, const uint32_t* binary, diff --git a/third_party/spirv-tools/source/opt/code_sink.cpp b/third_party/spirv-tools/source/opt/code_sink.cpp index e49029fe1e..cd77797476 100644 --- a/third_party/spirv-tools/source/opt/code_sink.cpp +++ b/third_party/spirv-tools/source/opt/code_sink.cpp @@ -218,8 +218,10 @@ bool CodeSinkingPass::HasUniformMemorySync() { case SpvOpAtomicISub: case SpvOpAtomicSMin: case SpvOpAtomicUMin: + case SpvOpAtomicFMinEXT: case SpvOpAtomicSMax: case SpvOpAtomicUMax: + case SpvOpAtomicFMaxEXT: case SpvOpAtomicAnd: case SpvOpAtomicOr: case SpvOpAtomicXor: diff --git a/third_party/spirv-tools/source/opt/constants.cpp b/third_party/spirv-tools/source/opt/constants.cpp index cf24295d1a..19ca6008da 100644 --- a/third_party/spirv-tools/source/opt/constants.cpp +++ b/third_party/spirv-tools/source/opt/constants.cpp @@ -389,6 +389,36 @@ const Constant* ConstantManager::GetConstant( return cst ? RegisterConstant(std::move(cst)) : nullptr; } +const Constant* ConstantManager::GetNumericVectorConstantWithWords( + const Vector* type, const std::vector& literal_words) { + const auto* element_type = type->element_type(); + uint32_t words_per_element = 0; + if (const auto* float_type = element_type->AsFloat()) + words_per_element = float_type->width() / 32; + else if (const auto* int_type = element_type->AsInteger()) + words_per_element = int_type->width() / 32; + + if (words_per_element != 1 && words_per_element != 2) return nullptr; + + if (words_per_element * type->element_count() != + static_cast(literal_words.size())) { + return nullptr; + } + + std::vector element_ids; + for (uint32_t i = 0; i < type->element_count(); ++i) { + auto first_word = literal_words.begin() + (words_per_element * i); + std::vector const_data(first_word, + first_word + words_per_element); + const analysis::Constant* element_constant = + GetConstant(element_type, const_data); + auto element_id = GetDefiningInstruction(element_constant)->result_id(); + element_ids.push_back(element_id); + } + + return GetConstant(type, element_ids); +} + uint32_t ConstantManager::GetFloatConst(float val) { Type* float_type = context()->get_type_mgr()->GetFloatType(); utils::FloatProxy v(val); diff --git a/third_party/spirv-tools/source/opt/constants.h b/third_party/spirv-tools/source/opt/constants.h index e17ae6b64d..95d984fcd2 100644 --- a/third_party/spirv-tools/source/opt/constants.h +++ b/third_party/spirv-tools/source/opt/constants.h @@ -58,7 +58,7 @@ class ConstantManager; class Constant { public: Constant() = delete; - virtual ~Constant() {} + virtual ~Constant() = default; // Make a deep copy of this constant. virtual std::unique_ptr Copy() const = 0; @@ -506,10 +506,11 @@ class ConstantManager { IRContext* context() const { return ctx_; } // Gets or creates a unique Constant instance of type |type| and a vector of - // constant defining words |words|. If a Constant instance existed already in - // the constant pool, it returns a pointer to it. Otherwise, it creates one - // using CreateConstant. If a new Constant instance cannot be created, it - // returns nullptr. + // constant defining words or ids for elements of Vector type + // |literal_words_or_ids|. If a Constant instance existed already in the + // constant pool, it returns a pointer to it. Otherwise, it creates one using + // CreateConstant. If a new Constant instance cannot be created, it returns + // nullptr. const Constant* GetConstant( const Type* type, const std::vector& literal_words_or_ids); @@ -519,6 +520,14 @@ class ConstantManager { literal_words_or_ids.end())); } + // Gets or creates a unique Constant instance of Vector type |type| with + // numeric elements and a vector of constant defining words |literal_words|. + // If a Constant instance existed already in the constant pool, it returns a + // pointer to it. Otherwise, it creates one using CreateConstant. If a new + // Constant instance cannot be created, it returns nullptr. + const Constant* GetNumericVectorConstantWithWords( + const Vector* type, const std::vector& literal_words); + // Gets or creates a Constant instance to hold the constant value of the given // instruction. It returns a pointer to a Constant instance or nullptr if it // could not create the constant. diff --git a/third_party/spirv-tools/source/opt/convert_to_half_pass.cpp b/third_party/spirv-tools/source/opt/convert_to_half_pass.cpp index 5022e1b686..6b3b540aa4 100644 --- a/third_party/spirv-tools/source/opt/convert_to_half_pass.cpp +++ b/third_party/spirv-tools/source/opt/convert_to_half_pass.cpp @@ -147,8 +147,8 @@ bool ConvertToHalfPass::MatConvertCleanup(Instruction* inst) { return true; } -void ConvertToHalfPass::RemoveRelaxedDecoration(uint32_t id) { - context()->get_decoration_mgr()->RemoveDecorationsFrom( +bool ConvertToHalfPass::RemoveRelaxedDecoration(uint32_t id) { + return context()->get_decoration_mgr()->RemoveDecorationsFrom( id, [](const Instruction& dec) { if (dec.opcode() == SpvOpDecorate && dec.GetSingleWordInOperand(1u) == SpvDecorationRelaxedPrecision) @@ -344,10 +344,14 @@ Pass::Status ConvertToHalfPass::ProcessImpl() { // If modified, make sure module has Float16 capability if (modified) context()->AddCapability(SpvCapabilityFloat16); // Remove all RelaxedPrecision decorations from instructions and globals - for (auto c_id : relaxed_ids_set_) RemoveRelaxedDecoration(c_id); + for (auto c_id : relaxed_ids_set_) { + modified |= RemoveRelaxedDecoration(c_id); + } for (auto& val : get_module()->types_values()) { uint32_t v_id = val.result_id(); - if (v_id != 0) RemoveRelaxedDecoration(v_id); + if (v_id != 0) { + modified |= RemoveRelaxedDecoration(v_id); + } } return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange; } diff --git a/third_party/spirv-tools/source/opt/convert_to_half_pass.h b/third_party/spirv-tools/source/opt/convert_to_half_pass.h index 143aebfa28..b647dd4a31 100644 --- a/third_party/spirv-tools/source/opt/convert_to_half_pass.h +++ b/third_party/spirv-tools/source/opt/convert_to_half_pass.h @@ -74,7 +74,7 @@ class ConvertToHalfPass : public Pass { void GenConvert(uint32_t* val_idp, uint32_t width, Instruction* inst); // Remove RelaxedPrecision decoration of |id|. - void RemoveRelaxedDecoration(uint32_t id); + bool RemoveRelaxedDecoration(uint32_t id); // Add |inst| to relaxed instruction set if warranted. Specifically, if // it is float32 and either decorated relaxed or a composite or phi diff --git a/third_party/spirv-tools/source/opt/debug_info_manager.cpp b/third_party/spirv-tools/source/opt/debug_info_manager.cpp index 87ef65537d..e782641f22 100644 --- a/third_party/spirv-tools/source/opt/debug_info_manager.cpp +++ b/third_party/spirv-tools/source/opt/debug_info_manager.cpp @@ -31,9 +31,7 @@ static const uint32_t kDebugInlinedAtOperandInlinedIndex = 6; static const uint32_t kDebugExpressOperandOperationIndex = 4; static const uint32_t kDebugDeclareOperandLocalVariableIndex = 4; static const uint32_t kDebugDeclareOperandVariableIndex = 5; -static const uint32_t kDebugValueOperandLocalVariableIndex = 4; static const uint32_t kDebugValueOperandExpressionIndex = 6; -static const uint32_t kDebugValueOperandIndexesIndex = 7; static const uint32_t kDebugOperationOperandOperationIndex = 4; static const uint32_t kOpVariableOperandStorageClassIndex = 2; static const uint32_t kDebugLocalVariableOperandParentIndex = 9; @@ -479,44 +477,6 @@ bool DebugInfoManager::IsDeclareVisibleToInstr(Instruction* dbg_declare, return false; } -Instruction* DebugInfoManager::AddDebugValueWithIndex( - uint32_t dbg_local_var_id, uint32_t value_id, uint32_t expr_id, - uint32_t index_id, Instruction* insert_before) { - uint32_t result_id = context()->TakeNextId(); - if (!result_id) return nullptr; - std::unique_ptr new_dbg_value(new Instruction( - context(), SpvOpExtInst, context()->get_type_mgr()->GetVoidTypeId(), - result_id, - { - {spv_operand_type_t::SPV_OPERAND_TYPE_ID, - {context() - ->get_feature_mgr() - ->GetExtInstImportId_OpenCL100DebugInfo()}}, - {spv_operand_type_t::SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER, - {static_cast(OpenCLDebugInfo100DebugValue)}}, - {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {dbg_local_var_id}}, - {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {value_id}}, - {spv_operand_type_t::SPV_OPERAND_TYPE_ID, - {expr_id == 0 ? GetEmptyDebugExpression()->result_id() : expr_id}}, - })); - if (index_id) { - new_dbg_value->AddOperand( - {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {index_id}}); - } - - Instruction* added_dbg_value = - insert_before->InsertBefore(std::move(new_dbg_value)); - AnalyzeDebugInst(added_dbg_value); - if (context()->AreAnalysesValid(IRContext::Analysis::kAnalysisDefUse)) - context()->get_def_use_mgr()->AnalyzeInstDefUse(added_dbg_value); - if (context()->AreAnalysesValid( - IRContext::Analysis::kAnalysisInstrToBlockMapping)) { - auto insert_blk = context()->get_instr_block(insert_before); - context()->set_instr_block(added_dbg_value, insert_blk); - } - return added_dbg_value; -} - bool DebugInfoManager::AddDebugValueIfVarDeclIsVisible( Instruction* scope_and_line, uint32_t variable_id, uint32_t value_id, Instruction* insert_pos, @@ -540,28 +500,16 @@ bool DebugInfoManager::AddDebugValueIfVarDeclIsVisible( insert_before->opcode() == SpvOpVariable) { insert_before = insert_before->NextNode(); } - - uint32_t index_id = 0; - if (dbg_decl_or_val->NumOperands() > kDebugValueOperandIndexesIndex) { - index_id = - dbg_decl_or_val->GetSingleWordOperand(kDebugValueOperandIndexesIndex); - } - - Instruction* added_dbg_value = - AddDebugValueWithIndex(dbg_decl_or_val->GetSingleWordOperand( - kDebugValueOperandLocalVariableIndex), - value_id, 0, index_id, insert_before); - assert(added_dbg_value != nullptr); - added_dbg_value->UpdateDebugInfoFrom(scope_and_line); - AnalyzeDebugInst(added_dbg_value); - modified = true; + modified |= AddDebugValueForDecl(dbg_decl_or_val, value_id, insert_before, + scope_and_line) != nullptr; } return modified; } -bool DebugInfoManager::AddDebugValueForDecl(Instruction* dbg_decl, - uint32_t value_id) { - if (dbg_decl == nullptr || !IsDebugDeclare(dbg_decl)) return false; +Instruction* DebugInfoManager::AddDebugValueForDecl( + Instruction* dbg_decl, uint32_t value_id, Instruction* insert_before, + Instruction* scope_and_line) { + if (dbg_decl == nullptr || !IsDebugDeclare(dbg_decl)) return nullptr; std::unique_ptr dbg_val(dbg_decl->Clone(context())); dbg_val->SetResultId(context()->TakeNextId()); @@ -570,17 +518,18 @@ bool DebugInfoManager::AddDebugValueForDecl(Instruction* dbg_decl, dbg_val->SetOperand(kDebugDeclareOperandVariableIndex, {value_id}); dbg_val->SetOperand(kDebugValueOperandExpressionIndex, {GetEmptyDebugExpression()->result_id()}); + dbg_val->UpdateDebugInfoFrom(scope_and_line); - auto* added_dbg_val = dbg_decl->InsertBefore(std::move(dbg_val)); + auto* added_dbg_val = insert_before->InsertBefore(std::move(dbg_val)); AnalyzeDebugInst(added_dbg_val); if (context()->AreAnalysesValid(IRContext::Analysis::kAnalysisDefUse)) context()->get_def_use_mgr()->AnalyzeInstDefUse(added_dbg_val); if (context()->AreAnalysesValid( IRContext::Analysis::kAnalysisInstrToBlockMapping)) { - auto insert_blk = context()->get_instr_block(dbg_decl); + auto insert_blk = context()->get_instr_block(insert_before); context()->set_instr_block(added_dbg_val, insert_blk); } - return true; + return added_dbg_val; } uint32_t DebugInfoManager::GetVariableIdOfDebugValueUsedForDeclare( diff --git a/third_party/spirv-tools/source/opt/debug_info_manager.h b/third_party/spirv-tools/source/opt/debug_info_manager.h index 630be4f1d2..776e9baab5 100644 --- a/third_party/spirv-tools/source/opt/debug_info_manager.h +++ b/third_party/spirv-tools/source/opt/debug_info_manager.h @@ -151,17 +151,15 @@ class DebugInfoManager { Instruction* insert_pos, std::unordered_set* invisible_decls); - // Generates a DebugValue instruction with |dbg_local_var_id|, |value_id|, - // |expr_id|, |index_id| operands and inserts it before |insert_before|. - Instruction* AddDebugValueWithIndex(uint32_t dbg_local_var_id, - uint32_t value_id, uint32_t expr_id, - uint32_t index_id, - Instruction* insert_before); - - // Adds DebugValue for DebugDeclare |dbg_decl|. The new DebugValue has the - // same line, scope, and operands but it uses |value_id| for value. Returns - // weather it succeeds or not. - bool AddDebugValueForDecl(Instruction* dbg_decl, uint32_t value_id); + // Creates a DebugValue for DebugDeclare |dbg_decl| and inserts it before + // |insert_before|. The new DebugValue has the same line and scope as + // |scope_and_line|, or no scope and line information if |scope_and_line| + // is nullptr. The new DebugValue has the same operands as DebugDeclare + // but it uses |value_id| for the value. Returns the created DebugValue, + // or nullptr if fails to create one. + Instruction* AddDebugValueForDecl(Instruction* dbg_decl, uint32_t value_id, + Instruction* insert_before, + Instruction* scope_and_line); // Erases |instr| from data structures of this class. void ClearDebugInfo(Instruction* instr); diff --git a/third_party/spirv-tools/source/opt/decompose_initialized_variables_pass.cpp b/third_party/spirv-tools/source/opt/decompose_initialized_variables_pass.cpp deleted file mode 100644 index 875bf7e85c..0000000000 --- a/third_party/spirv-tools/source/opt/decompose_initialized_variables_pass.cpp +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "source/opt/decompose_initialized_variables_pass.h" - -#include "source/opt/ir_context.h" - -namespace spvtools { -namespace opt { - -using inst_iterator = InstructionList::iterator; - -namespace { - -bool HasInitializer(Instruction* inst) { - if (inst->opcode() != SpvOpVariable) return false; - if (inst->NumOperands() < 4) return false; - - return true; -} - -} // namespace - -Pass::Status DecomposeInitializedVariablesPass::Process() { - auto* module = context()->module(); - std::unordered_set changed; - - std::vector> global_stores; - for (auto iter = module->types_values_begin(); - iter != module->types_values_end(); ++iter) { - Instruction* inst = &(*iter); - if (!HasInitializer(inst)) continue; - - auto var_id = inst->result_id(); - auto val_id = inst->GetOperand(3).words[0]; - global_stores.push_back(std::make_tuple(var_id, val_id)); - iter->RemoveOperand(3); - changed.insert(&*iter); - } - - std::unordered_set entry_ids; - for (auto entry = module->entry_points().begin(); - entry != module->entry_points().end(); ++entry) { - entry_ids.insert(entry->GetSingleWordInOperand(1)); - } - - for (auto func = module->begin(); func != module->end(); ++func) { - std::vector function_stores; - auto first_block = func->entry().get(); - inst_iterator insert_point = first_block->begin(); - for (auto iter = first_block->begin(); - iter != first_block->end() && iter->opcode() == SpvOpVariable; - ++iter) { - // For valid SPIRV-V, there is guaranteed to be at least one instruction - // after the OpVariable instructions. - insert_point = (*iter).NextNode(); - Instruction* inst = &(*iter); - if (!HasInitializer(inst)) continue; - - auto var_id = inst->result_id(); - auto val_id = inst->GetOperand(3).words[0]; - Instruction* store_inst = new Instruction( - context(), SpvOpStore, 0, 0, - {{SPV_OPERAND_TYPE_ID, {var_id}}, {SPV_OPERAND_TYPE_ID, {val_id}}}); - function_stores.push_back(store_inst); - iter->RemoveOperand(3); - changed.insert(&*iter); - } - - if (entry_ids.find(func->result_id()) != entry_ids.end()) { - for (auto store_ids : global_stores) { - uint32_t var_id; - uint32_t val_id; - std::tie(var_id, val_id) = store_ids; - auto* store_inst = new Instruction( - context(), SpvOpStore, 0, 0, - {{SPV_OPERAND_TYPE_ID, {var_id}}, {SPV_OPERAND_TYPE_ID, {val_id}}}); - context()->set_instr_block(store_inst, &*first_block); - first_block->AddInstruction(std::unique_ptr(store_inst)); - store_inst->InsertBefore(&*insert_point); - changed.insert(store_inst); - } - } - - for (auto store = function_stores.begin(); store != function_stores.end(); - ++store) { - context()->set_instr_block(*store, first_block); - (*store)->InsertBefore(&*insert_point); - changed.insert(*store); - } - } - - auto* def_use_mgr = get_def_use_mgr(); - for (auto* inst : changed) def_use_mgr->UpdateDefUse(inst); - - return !changed.empty() ? Pass::Status::SuccessWithChange - : Pass::Status::SuccessWithoutChange; -} - -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/decompose_initialized_variables_pass.h b/third_party/spirv-tools/source/opt/decompose_initialized_variables_pass.h deleted file mode 100644 index c0bd35e760..0000000000 --- a/third_party/spirv-tools/source/opt/decompose_initialized_variables_pass.h +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SOURCE_OPT_DECOMPOSE_INITALIZED_VAIRABLES_PASS_H_ -#define SOURCE_OPT_DECOMPOSE_INITALIZED_VAIRABLES_PASS_H_ - -#include "source/opt/ir_context.h" -#include "source/opt/module.h" -#include "source/opt/pass.h" - -namespace spvtools { -namespace opt { - -// Converts variable declartions with initializers into seperate declaration and -// assignment statements. This is done due to known issues with some Vulkan -// implementations' handling of initialized variables. -// -// Only decomposes variables with storage classes that are valid in Vulkan -// execution environments; Output, Private, and Function. -// Currently only Function is implemented. -class DecomposeInitializedVariablesPass : public Pass { - public: - const char* name() const override { - return "decompose-initialized-variables"; - } - Status Process() override; - - IRContext::Analysis GetPreservedAnalyses() override { - return IRContext::kAnalysisInstrToBlockMapping | - IRContext::kAnalysisDecorations | IRContext::kAnalysisCombinators | - IRContext::kAnalysisCFG | IRContext::kAnalysisDominatorAnalysis | - IRContext::kAnalysisLoopAnalysis | IRContext::kAnalysisNameMap | - IRContext::kAnalysisScalarEvolution | - IRContext::kAnalysisRegisterPressure | - IRContext::kAnalysisValueNumberTable | - IRContext::kAnalysisStructuredCFG | - IRContext::kAnalysisBuiltinVarId | - IRContext::kAnalysisIdToFuncMapping | IRContext::kAnalysisTypes | - IRContext::kAnalysisDefUse | IRContext::kAnalysisConstants; - } -}; - -} // namespace opt -} // namespace spvtools - -#endif // SOURCE_OPT_DECOMPOSE_INITALIZED_VAIRABLES_PASS_H_ diff --git a/third_party/spirv-tools/source/opt/decoration_manager.cpp b/third_party/spirv-tools/source/opt/decoration_manager.cpp index a10c992e16..4bf026efd8 100644 --- a/third_party/spirv-tools/source/opt/decoration_manager.cpp +++ b/third_party/spirv-tools/source/opt/decoration_manager.cpp @@ -53,11 +53,12 @@ namespace spvtools { namespace opt { namespace analysis { -void DecorationManager::RemoveDecorationsFrom( +bool DecorationManager::RemoveDecorationsFrom( uint32_t id, std::function pred) { + bool was_modified = false; const auto ids_iter = id_to_decoration_insts_.find(id); if (ids_iter == id_to_decoration_insts_.end()) { - return; + return was_modified; } TargetData& decorations_info = ids_iter->second; @@ -99,7 +100,6 @@ void DecorationManager::RemoveDecorationsFrom( // Otherwise, remove |id| from the targets of |group_id| const uint32_t stride = inst->opcode() == SpvOpGroupDecorate ? 1u : 2u; - bool was_modified = false; for (uint32_t i = 1u; i < inst->NumInOperands();) { if (inst->GetSingleWordInOperand(i) != id) { i += stride; @@ -155,6 +155,7 @@ void DecorationManager::RemoveDecorationsFrom( }), indirect_decorations.end()); + was_modified |= !insts_to_kill.empty(); for (Instruction* inst : insts_to_kill) context->KillInst(inst); insts_to_kill.clear(); @@ -165,6 +166,7 @@ void DecorationManager::RemoveDecorationsFrom( for (Instruction* inst : decorations_info.decorate_insts) insts_to_kill.push_back(inst); } + was_modified |= !insts_to_kill.empty(); for (Instruction* inst : insts_to_kill) context->KillInst(inst); if (decorations_info.direct_decorations.empty() && @@ -172,6 +174,7 @@ void DecorationManager::RemoveDecorationsFrom( decorations_info.decorate_insts.empty()) { id_to_decoration_insts_.erase(ids_iter); } + return was_modified; } std::vector DecorationManager::GetDecorationsFor( @@ -487,6 +490,13 @@ void DecorationManager::ForEachDecoration( }); } +bool DecorationManager::FindDecoration( + uint32_t id, uint32_t decoration, + std::function f) { + return !WhileEachDecoration( + id, decoration, [&f](const Instruction& inst) { return !f(inst); }); +} + void DecorationManager::CloneDecorations(uint32_t from, uint32_t to) { const auto decoration_list = id_to_decoration_insts_.find(from); if (decoration_list == id_to_decoration_insts_.end()) return; diff --git a/third_party/spirv-tools/source/opt/decoration_manager.h b/third_party/spirv-tools/source/opt/decoration_manager.h index 01244f293d..b753e6be1d 100644 --- a/third_party/spirv-tools/source/opt/decoration_manager.h +++ b/third_party/spirv-tools/source/opt/decoration_manager.h @@ -36,8 +36,9 @@ class DecorationManager { } DecorationManager() = delete; - // Changes all of the decorations (direct and through groups) where |pred| is - // true and that apply to |id| so that they no longer apply to |id|. + // Removes all decorations (direct and through groups) where |pred| is + // true and that apply to |id| so that they no longer apply to |id|. Returns + // true if something changed. // // If |id| is part of a group, it will be removed from the group if it // does not use all of the group's decorations, or, if there are no @@ -52,9 +53,9 @@ class DecorationManager { // removed, then the |OpGroupDecorate| and // |OpGroupMemberDecorate| for the group will be killed, but not the defining // |OpDecorationGroup| instruction. - void RemoveDecorationsFrom(uint32_t id, - std::function pred = - [](const Instruction&) { return true; }); + bool RemoveDecorationsFrom( + uint32_t id, std::function pred = + [](const Instruction&) { return true; }); // Removes all decorations from the result id of |inst|. // @@ -102,6 +103,13 @@ class DecorationManager { bool WhileEachDecoration(uint32_t id, uint32_t decoration, std::function f); + // |f| is run on each decoration instruction for |id| with decoration + // |decoration|. Processes all decoration which target |id| either directly or + // indirectly through decoration groups. If |f| returns true, iteration is + // terminated and this function returns true. Otherwise returns false. + bool FindDecoration(uint32_t id, uint32_t decoration, + std::function f); + // Clone all decorations from one id |from|. // The cloned decorations are assigned to the given id |to| and are // added to the module. The purpose is to decorate cloned instructions. diff --git a/third_party/spirv-tools/source/opt/desc_sroa.cpp b/third_party/spirv-tools/source/opt/desc_sroa.cpp index b68549a0c5..5e950069da 100644 --- a/third_party/spirv-tools/source/opt/desc_sroa.cpp +++ b/third_party/spirv-tools/source/opt/desc_sroa.cpp @@ -63,16 +63,7 @@ bool DescriptorScalarReplacement::IsCandidate(Instruction* var) { // All structures with descriptor assignments must be replaced by variables, // one for each of their members - with the exceptions of buffers. - // Buffers are represented as structures, but we shouldn't replace a buffer - // with its elements. All buffers have offset decorations for members of their - // structure types. - bool has_offset_decoration = false; - context()->get_decoration_mgr()->ForEachDecoration( - var_type_inst->result_id(), SpvDecorationOffset, - [&has_offset_decoration](const Instruction&) { - has_offset_decoration = true; - }); - if (has_offset_decoration) { + if (IsTypeOfStructuredBuffer(var_type_inst)) { return false; } @@ -99,6 +90,23 @@ bool DescriptorScalarReplacement::IsCandidate(Instruction* var) { return true; } +bool DescriptorScalarReplacement::IsTypeOfStructuredBuffer( + const Instruction* type) const { + if (type->opcode() != SpvOpTypeStruct) { + return false; + } + + // All buffers have offset decorations for members of their structure types. + // This is how we distinguish it from a structure of descriptors. + bool has_offset_decoration = false; + context()->get_decoration_mgr()->ForEachDecoration( + type->result_id(), SpvDecorationOffset, + [&has_offset_decoration](const Instruction&) { + has_offset_decoration = true; + }); + return has_offset_decoration; +} + bool DescriptorScalarReplacement::ReplaceCandidate(Instruction* var) { std::vector access_chain_work_list; std::vector load_work_list; @@ -368,7 +376,8 @@ uint32_t DescriptorScalarReplacement::GetNumBindingsUsedByType( // The number of bindings consumed by a structure is the sum of the bindings // used by its members. - if (type_inst->opcode() == SpvOpTypeStruct) { + if (type_inst->opcode() == SpvOpTypeStruct && + !IsTypeOfStructuredBuffer(type_inst)) { uint32_t sum = 0; for (uint32_t i = 0; i < type_inst->NumInOperands(); i++) sum += GetNumBindingsUsedByType(type_inst->GetSingleWordInOperand(i)); diff --git a/third_party/spirv-tools/source/opt/desc_sroa.h b/third_party/spirv-tools/source/opt/desc_sroa.h index c3aa0ea2b1..cd72fd3019 100644 --- a/third_party/spirv-tools/source/opt/desc_sroa.h +++ b/third_party/spirv-tools/source/opt/desc_sroa.h @@ -93,6 +93,11 @@ class DescriptorScalarReplacement : public Pass { // bindings used by its members. uint32_t GetNumBindingsUsedByType(uint32_t type_id); + // Returns true if |type| is a type that could be used for a structured buffer + // as opposed to a type that would be used for a structure of resource + // descriptors. + bool IsTypeOfStructuredBuffer(const Instruction* type) const; + // A map from an OpVariable instruction to the set of variables that will be // used to replace it. The entry |replacement_variables_[var][i]| is the id of // a variable that will be used in the place of the the ith element of the diff --git a/third_party/spirv-tools/source/opt/eliminate_dead_functions_util.cpp b/third_party/spirv-tools/source/opt/eliminate_dead_functions_util.cpp index 6b5234bb57..1379120ffa 100644 --- a/third_party/spirv-tools/source/opt/eliminate_dead_functions_util.cpp +++ b/third_party/spirv-tools/source/opt/eliminate_dead_functions_util.cpp @@ -23,9 +23,11 @@ Module::iterator EliminateFunction(IRContext* context, Module::iterator* func_iter) { bool first_func = *func_iter == context->module()->begin(); bool seen_func_end = false; + std::unordered_set to_kill; (*func_iter) ->ForEachInst( - [context, first_func, func_iter, &seen_func_end](Instruction* inst) { + [context, first_func, func_iter, &seen_func_end, + &to_kill](Instruction* inst) { if (inst->opcode() == SpvOpFunctionEnd) { seen_func_end = true; } @@ -33,6 +35,7 @@ Module::iterator EliminateFunction(IRContext* context, // global values if this is the first function. if (seen_func_end && inst->opcode() == SpvOpExtInst) { assert(inst->IsNonSemanticInstruction()); + if (to_kill.find(inst) != to_kill.end()) return; std::unique_ptr clone(inst->Clone(context)); context->ForgetUses(inst); context->AnalyzeDefUse(clone.get()); @@ -44,12 +47,17 @@ Module::iterator EliminateFunction(IRContext* context, prev_func_iter->AddNonSemanticInstruction(std::move(clone)); } inst->ToNop(); - } else { - context->KillNonSemanticInfo(inst); + } else if (to_kill.find(inst) == to_kill.end()) { + context->CollectNonSemanticTree(inst, &to_kill); context->KillInst(inst); } }, true, true); + + for (auto* dead : to_kill) { + context->KillInst(dead); + } + return func_iter->Erase(); } diff --git a/third_party/spirv-tools/source/opt/eliminate_dead_members_pass.cpp b/third_party/spirv-tools/source/opt/eliminate_dead_members_pass.cpp index 5b8f4ec54f..173df6209a 100644 --- a/third_party/spirv-tools/source/opt/eliminate_dead_members_pass.cpp +++ b/third_party/spirv-tools/source/opt/eliminate_dead_members_pass.cpp @@ -20,7 +20,7 @@ namespace { const uint32_t kRemovedMember = 0xFFFFFFFF; const uint32_t kSpecConstOpOpcodeIdx = 0; -} +} // namespace namespace spvtools { namespace opt { @@ -228,15 +228,10 @@ void EliminateDeadMembersPass::MarkMembersAsLiveForAccessChain( const_mgr->FindDeclaredConstant(inst->GetSingleWordInOperand(i)) ->AsIntConstant(); assert(member_idx); - if (member_idx->type()->AsInteger()->width() == 32) { - used_members_[type_id].insert(member_idx->GetU32()); - type_id = type_inst->GetSingleWordInOperand(member_idx->GetU32()); - } else { - used_members_[type_id].insert( - static_cast(member_idx->GetU64())); - type_id = type_inst->GetSingleWordInOperand( - static_cast(member_idx->GetU64())); - } + uint32_t index = + static_cast(member_idx->GetZeroExtendedValue()); + used_members_[type_id].insert(index); + type_id = type_inst->GetSingleWordInOperand(index); } break; case SpvOpTypeArray: case SpvOpTypeRuntimeArray: @@ -477,12 +472,8 @@ bool EliminateDeadMembersPass::UpdateAccessChain(Instruction* inst) { const_mgr->FindDeclaredConstant(inst->GetSingleWordInOperand(i)) ->AsIntConstant(); assert(member_idx); - uint32_t orig_member_idx; - if (member_idx->type()->AsInteger()->width() == 32) { - orig_member_idx = member_idx->GetU32(); - } else { - orig_member_idx = static_cast(member_idx->GetU64()); - } + uint32_t orig_member_idx = + static_cast(member_idx->GetZeroExtendedValue()); uint32_t new_member_idx = GetNewMemberIndex(type_id, orig_member_idx); assert(new_member_idx != kRemovedMember); if (orig_member_idx != new_member_idx) { diff --git a/third_party/spirv-tools/source/opt/fix_storage_class.cpp b/third_party/spirv-tools/source/opt/fix_storage_class.cpp index 03da0d0d1b..04eb1326c3 100644 --- a/third_party/spirv-tools/source/opt/fix_storage_class.cpp +++ b/third_party/spirv-tools/source/opt/fix_storage_class.cpp @@ -222,6 +222,16 @@ bool FixStorageClass::PropagateType(Instruction* inst, uint32_t type_id, uint32_t pointee_type_id = GetPointeeTypeId(ptr_inst); if (obj_type_id != pointee_type_id) { + if (context()->get_type_mgr()->GetType(obj_type_id)->AsImage() && + context()->get_type_mgr()->GetType(pointee_type_id)->AsImage()) { + // When storing an image, allow the type mismatch + // and let the later legalization passes eliminate the OpStore. + // This is to support assigning an image to a variable, + // where the assigned image does not have a pre-defined + // image format. + return false; + } + uint32_t copy_id = GenerateCopy(obj_inst, pointee_type_id, inst); inst->SetInOperand(1, {copy_id}); context()->UpdateDefUse(inst); diff --git a/third_party/spirv-tools/source/opt/folding_rules.cpp b/third_party/spirv-tools/source/opt/folding_rules.cpp index 010eec9c1a..e3e926c3a5 100644 --- a/third_party/spirv-tools/source/opt/folding_rules.cpp +++ b/third_party/spirv-tools/source/opt/folding_rules.cpp @@ -124,6 +124,66 @@ Instruction* NonConstInput(IRContext* context, const analysis::Constant* c, inst->GetSingleWordInOperand(in_op)); } +std::vector ExtractInts(uint64_t val) { + std::vector words; + words.push_back(static_cast(val)); + words.push_back(static_cast(val >> 32)); + return words; +} + +std::vector GetWordsFromScalarIntConstant( + const analysis::IntConstant* c) { + assert(c != nullptr); + uint32_t width = c->type()->AsInteger()->width(); + assert(width == 32 || width == 64); + if (width == 64) { + uint64_t uval = static_cast(c->GetU64()); + return ExtractInts(uval); + } + return {c->GetU32()}; +} + +std::vector GetWordsFromScalarFloatConstant( + const analysis::FloatConstant* c) { + assert(c != nullptr); + uint32_t width = c->type()->AsFloat()->width(); + assert(width == 32 || width == 64); + if (width == 64) { + utils::FloatProxy result(c->GetDouble()); + return result.GetWords(); + } + utils::FloatProxy result(c->GetFloat()); + return result.GetWords(); +} + +std::vector GetWordsFromNumericScalarOrVectorConstant( + analysis::ConstantManager* const_mgr, const analysis::Constant* c) { + if (const auto* float_constant = c->AsFloatConstant()) { + return GetWordsFromScalarFloatConstant(float_constant); + } else if (const auto* int_constant = c->AsIntConstant()) { + return GetWordsFromScalarIntConstant(int_constant); + } else if (const auto* vec_constant = c->AsVectorConstant()) { + std::vector words; + for (const auto* comp : vec_constant->GetComponents()) { + auto comp_in_words = + GetWordsFromNumericScalarOrVectorConstant(const_mgr, comp); + words.insert(words.end(), comp_in_words.begin(), comp_in_words.end()); + } + return words; + } + return {}; +} + +const analysis::Constant* ConvertWordsToNumericScalarOrVectorConstant( + analysis::ConstantManager* const_mgr, const std::vector& words, + const analysis::Type* type) { + if (type->AsInteger() || type->AsFloat()) + return const_mgr->GetConstant(type, words); + if (const auto* vec_type = type->AsVector()) + return const_mgr->GetNumericVectorConstantWithWords(vec_type, words); + return nullptr; +} + // Returns the negation of |c|. |c| must be a 32 or 64 bit floating point // constant. uint32_t NegateFloatingPointConstant(analysis::ConstantManager* const_mgr, @@ -146,13 +206,6 @@ uint32_t NegateFloatingPointConstant(analysis::ConstantManager* const_mgr, return const_mgr->GetDefiningInstruction(negated_const)->result_id(); } -std::vector ExtractInts(uint64_t val) { - std::vector words; - words.push_back(static_cast(val)); - words.push_back(static_cast(val >> 32)); - return words; -} - // Negates the integer constant |c|. Returns the id of the defining instruction. uint32_t NegateIntegerConstant(analysis::ConstantManager* const_mgr, const analysis::Constant* c) { @@ -470,7 +523,7 @@ uint32_t PerformFloatingPointOperation(analysis::ConstantManager* const_mgr, float fval = val.getAsFloat(); \ if (!IsValidResult(fval)) return 0; \ words = val.GetWords(); \ - } + } static_assert(true, "require extra semicolon") switch (opcode) { case SpvOpFMul: FOLD_OP(*); @@ -522,7 +575,7 @@ uint32_t PerformIntegerOperation(analysis::ConstantManager* const_mgr, uint32_t val = input1->GetU32() op input2->GetU32(); \ words.push_back(val); \ } \ - } + } static_assert(true, "require extra semicalon") switch (opcode) { case SpvOpIMul: FOLD_OP(*); @@ -1796,6 +1849,35 @@ FoldingRule RedundantPhi() { }; } +FoldingRule BitCastScalarOrVector() { + return [](IRContext* context, Instruction* inst, + const std::vector& constants) { + assert(inst->opcode() == SpvOpBitcast && constants.size() == 1); + if (constants[0] == nullptr) return false; + + const analysis::Type* type = + context->get_type_mgr()->GetType(inst->type_id()); + if (HasFloatingPoint(type) && !inst->IsFloatingPointFoldingAllowed()) + return false; + + analysis::ConstantManager* const_mgr = context->get_constant_mgr(); + std::vector words = + GetWordsFromNumericScalarOrVectorConstant(const_mgr, constants[0]); + if (words.size() == 0) return false; + + const analysis::Constant* bitcasted_constant = + ConvertWordsToNumericScalarOrVectorConstant(const_mgr, words, type); + if (!bitcasted_constant) return false; + + auto new_feeder_id = + const_mgr->GetDefiningInstruction(bitcasted_constant, inst->type_id()) + ->result_id(); + inst->SetOpcode(SpvOpCopyObject); + inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {new_feeder_id}}}); + return true; + }; +} + FoldingRule RedundantSelect() { // An OpSelect instruction where both values are the same or the condition is // constant can be replaced by one of the values @@ -2423,6 +2505,8 @@ void FoldingRules::AddFoldingRules() { // Note that the order in which rules are added to the list matters. If a rule // applies to the instruction, the rest of the rules will not be attempted. // Take that into consideration. + rules_[SpvOpBitcast].push_back(BitCastScalarOrVector()); + rules_[SpvOpCompositeConstruct].push_back(CompositeExtractFeedingConstruct); rules_[SpvOpCompositeExtract].push_back(InsertFeedingExtract()); diff --git a/third_party/spirv-tools/source/opt/function.cpp b/third_party/spirv-tools/source/opt/function.cpp index 52054eae76..38c669510b 100644 --- a/third_party/spirv-tools/source/opt/function.cpp +++ b/third_party/spirv-tools/source/opt/function.cpp @@ -42,7 +42,6 @@ Function* Function::Clone(IRContext* ctx) const { clone->blocks_.reserve(blocks_.size()); for (const auto& b : blocks_) { std::unique_ptr bb(b->Clone(ctx)); - bb->SetParent(clone); clone->AddBasicBlock(std::move(bb)); } diff --git a/third_party/spirv-tools/source/opt/function.h b/third_party/spirv-tools/source/opt/function.h index 4b20dcb9bc..9e1c72746e 100644 --- a/third_party/spirv-tools/source/opt/function.h +++ b/third_party/spirv-tools/source/opt/function.h @@ -213,6 +213,7 @@ inline void Function::AddBasicBlock(std::unique_ptr b) { inline void Function::AddBasicBlock(std::unique_ptr b, iterator ip) { + b->SetParent(this); ip.InsertBefore(std::move(b)); } diff --git a/third_party/spirv-tools/source/opt/generate_webgpu_initializers_pass.cpp b/third_party/spirv-tools/source/opt/generate_webgpu_initializers_pass.cpp deleted file mode 100644 index eaed3c28e2..0000000000 --- a/third_party/spirv-tools/source/opt/generate_webgpu_initializers_pass.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "source/opt/generate_webgpu_initializers_pass.h" -#include "source/opt/ir_context.h" - -namespace spvtools { -namespace opt { - -using inst_iterator = InstructionList::iterator; - -namespace { - -bool NeedsWebGPUInitializer(Instruction* inst) { - if (inst->opcode() != SpvOpVariable) return false; - - auto storage_class = inst->GetSingleWordOperand(2); - if (storage_class != SpvStorageClassOutput && - storage_class != SpvStorageClassPrivate && - storage_class != SpvStorageClassFunction) { - return false; - } - - if (inst->NumOperands() > 3) return false; - - return true; -} - -} // namespace - -Pass::Status GenerateWebGPUInitializersPass::Process() { - auto* module = context()->module(); - bool changed = false; - - // Handle global/module scoped variables - for (auto iter = module->types_values_begin(); - iter != module->types_values_end(); ++iter) { - Instruction* inst = &(*iter); - - if (inst->opcode() == SpvOpConstantNull) { - null_constant_type_map_[inst->type_id()] = inst; - seen_null_constants_.insert(inst); - continue; - } - - if (!NeedsWebGPUInitializer(inst)) continue; - - changed = true; - - auto* constant_inst = GetNullConstantForVariable(inst); - if (!constant_inst) return Status::Failure; - - if (seen_null_constants_.find(constant_inst) == - seen_null_constants_.end()) { - constant_inst->InsertBefore(inst); - null_constant_type_map_[inst->type_id()] = inst; - seen_null_constants_.insert(inst); - } - AddNullInitializerToVariable(constant_inst, inst); - } - - // Handle local/function scoped variables - for (auto func = module->begin(); func != module->end(); ++func) { - auto block = func->entry().get(); - for (auto iter = block->begin(); - iter != block->end() && iter->opcode() == SpvOpVariable; ++iter) { - Instruction* inst = &(*iter); - if (!NeedsWebGPUInitializer(inst)) continue; - - changed = true; - auto* constant_inst = GetNullConstantForVariable(inst); - if (!constant_inst) return Status::Failure; - - AddNullInitializerToVariable(constant_inst, inst); - } - } - - return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange; -} - -Instruction* GenerateWebGPUInitializersPass::GetNullConstantForVariable( - Instruction* variable_inst) { - auto constant_mgr = context()->get_constant_mgr(); - auto* def_use_mgr = get_def_use_mgr(); - - auto* ptr_inst = def_use_mgr->GetDef(variable_inst->type_id()); - auto type_id = ptr_inst->GetInOperand(1).words[0]; - if (null_constant_type_map_.find(type_id) == null_constant_type_map_.end()) { - auto* constant_type = context()->get_type_mgr()->GetType(type_id); - auto* constant = constant_mgr->GetConstant(constant_type, {}); - return constant_mgr->GetDefiningInstruction(constant, type_id); - } else { - return null_constant_type_map_[type_id]; - } -} - -void GenerateWebGPUInitializersPass::AddNullInitializerToVariable( - Instruction* constant_inst, Instruction* variable_inst) { - auto constant_id = constant_inst->result_id(); - variable_inst->AddOperand(Operand(SPV_OPERAND_TYPE_ID, {constant_id})); - get_def_use_mgr()->AnalyzeInstUse(variable_inst); -} - -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/generate_webgpu_initializers_pass.h b/third_party/spirv-tools/source/opt/generate_webgpu_initializers_pass.h deleted file mode 100644 index f95e84c5b0..0000000000 --- a/third_party/spirv-tools/source/opt/generate_webgpu_initializers_pass.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SOURCE_OPT_GENERATE_WEBGPU_INITIALIZERS_PASS_H_ -#define SOURCE_OPT_GENERATE_WEBGPU_INITIALIZERS_PASS_H_ - -#include "source/opt/ir_context.h" -#include "source/opt/module.h" -#include "source/opt/pass.h" - -namespace spvtools { -namespace opt { - -// Adds initializers to variables with storage classes Output, Private, and -// Function if they are missing. In the WebGPU environment these storage classes -// require that the variables are initialized. Currently they are initialized to -// NULL, though in the future some of them may be initialized to the first value -// that is stored in them, if that was a constant. -class GenerateWebGPUInitializersPass : public Pass { - public: - const char* name() const override { return "generate-webgpu-initializers"; } - Status Process() override; - - IRContext::Analysis GetPreservedAnalyses() override { - return IRContext::kAnalysisInstrToBlockMapping | - IRContext::kAnalysisDecorations | IRContext::kAnalysisCombinators | - IRContext::kAnalysisCFG | IRContext::kAnalysisDominatorAnalysis | - IRContext::kAnalysisLoopAnalysis | IRContext::kAnalysisNameMap | - IRContext::kAnalysisScalarEvolution | - IRContext::kAnalysisRegisterPressure | - IRContext::kAnalysisValueNumberTable | - IRContext::kAnalysisStructuredCFG | - IRContext::kAnalysisBuiltinVarId | - IRContext::kAnalysisIdToFuncMapping | IRContext::kAnalysisTypes | - IRContext::kAnalysisDefUse | IRContext::kAnalysisConstants; - } - - private: - using NullConstantTypeMap = std::unordered_map; - NullConstantTypeMap null_constant_type_map_; - std::unordered_set seen_null_constants_; - - Instruction* GetNullConstantForVariable(Instruction* variable_inst); - void AddNullInitializerToVariable(Instruction* constant_inst, - Instruction* variable_inst); -}; - -} // namespace opt -} // namespace spvtools - -#endif // SOURCE_OPT_GENERATE_WEBGPU_INITIALIZERS_PASS_H_ diff --git a/third_party/spirv-tools/source/opt/graphics_robust_access_pass.cpp b/third_party/spirv-tools/source/opt/graphics_robust_access_pass.cpp index 46483e48b9..1b28f9b529 100644 --- a/third_party/spirv-tools/source/opt/graphics_robust_access_pass.cpp +++ b/third_party/spirv-tools/source/opt/graphics_robust_access_pass.cpp @@ -272,10 +272,11 @@ void GraphicsRobustAccessPass::ClampIndicesForAccessChain( // Replaces one of the OpAccessChain index operands with a new value. // Updates def-use analysis. - auto replace_index = [&inst, def_use_mgr](uint32_t operand_index, - Instruction* new_value) { + auto replace_index = [this, &inst, def_use_mgr](uint32_t operand_index, + Instruction* new_value) { inst.SetOperand(operand_index, {new_value->result_id()}); def_use_mgr->AnalyzeInstUse(&inst); + module_status_.modified = true; return SPV_SUCCESS; }; diff --git a/third_party/spirv-tools/source/opt/inline_exhaustive_pass.cpp b/third_party/spirv-tools/source/opt/inline_exhaustive_pass.cpp index 24f4e73640..f24f744d05 100644 --- a/third_party/spirv-tools/source/opt/inline_exhaustive_pass.cpp +++ b/third_party/spirv-tools/source/opt/inline_exhaustive_pass.cpp @@ -38,11 +38,6 @@ Pass::Status InlineExhaustivePass::InlineExhaustive(Function* func) { if (newBlocks.size() > 1) UpdateSucceedingPhis(newBlocks); // Replace old calling block with new block(s). - // We need to kill the name and decorations for the call, which - // will be deleted. Other instructions in the block will be moved to - // newBlocks. We don't need to do anything with those. - context()->KillNamesAndDecorates(&*ii); - bi = bi.Erase(); for (auto& bb : newBlocks) { diff --git a/third_party/spirv-tools/source/opt/inline_pass.cpp b/third_party/spirv-tools/source/opt/inline_pass.cpp index eaf29aa053..8159ebf787 100644 --- a/third_party/spirv-tools/source/opt/inline_pass.cpp +++ b/third_party/spirv-tools/source/opt/inline_pass.cpp @@ -383,9 +383,7 @@ std::unique_ptr InlinePass::InlineReturn( uint32_t returnLabelId = 0; for (auto callee_block_itr = calleeFn->begin(); callee_block_itr != calleeFn->end(); ++callee_block_itr) { - if (callee_block_itr->tail()->opcode() == SpvOpUnreachable || - callee_block_itr->tail()->opcode() == SpvOpKill || - callee_block_itr->tail()->opcode() == SpvOpTerminateInvocation) { + if (spvOpcodeIsAbort(callee_block_itr->tail()->opcode())) { returnLabelId = context()->TakeNextId(); break; } @@ -619,14 +617,6 @@ bool InlinePass::GenInlineCode( assert(resId != 0); AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr, call_inst_itr->dbg_line_inst(), call_inst_itr->GetDebugScope()); - } else { - // Even though it is very unlikely, it is possible that the result id of - // the void-function call is used, so we need to generate an instruction - // with that result id. - std::unique_ptr undef_inst( - new Instruction(context(), SpvOpUndef, call_inst_itr->type_id(), - call_inst_itr->result_id(), {})); - context()->AddGlobalValue(std::move(undef_inst)); } // Move instructions of original caller block after call instruction. @@ -645,6 +635,11 @@ bool InlinePass::GenInlineCode( for (auto& blk : *new_blocks) { id2block_[blk->id()] = &*blk; } + + // We need to kill the name and decorations for the call, which will be + // deleted. + context()->KillNamesAndDecorates(&*call_inst_itr); + return true; } @@ -762,8 +757,7 @@ bool InlinePass::IsInlinableFunction(Function* func) { bool InlinePass::ContainsKillOrTerminateInvocation(Function* func) const { return !func->WhileEachInst([](Instruction* inst) { - const auto opcode = inst->opcode(); - return (opcode != SpvOpKill) && (opcode != SpvOpTerminateInvocation); + return !spvOpcodeTerminatesExecution(inst->opcode()); }); } diff --git a/third_party/spirv-tools/source/opt/inline_pass.h b/third_party/spirv-tools/source/opt/inline_pass.h index abe773af86..9a5429bac3 100644 --- a/third_party/spirv-tools/source/opt/inline_pass.h +++ b/third_party/spirv-tools/source/opt/inline_pass.h @@ -37,7 +37,7 @@ class InlinePass : public Pass { using cbb_ptr = const BasicBlock*; public: - virtual ~InlinePass() = default; + virtual ~InlinePass() override = default; protected: InlinePass(); diff --git a/third_party/spirv-tools/source/opt/inst_bindless_check_pass.cpp b/third_party/spirv-tools/source/opt/inst_bindless_check_pass.cpp index 64d389ca4f..5607239aaf 100644 --- a/third_party/spirv-tools/source/opt/inst_bindless_check_pass.cpp +++ b/third_party/spirv-tools/source/opt/inst_bindless_check_pass.cpp @@ -23,13 +23,20 @@ static const int kSpvImageSampleImageIdInIdx = 0; static const int kSpvSampledImageImageIdInIdx = 0; static const int kSpvSampledImageSamplerIdInIdx = 1; static const int kSpvImageSampledImageIdInIdx = 0; +static const int kSpvCopyObjectOperandIdInIdx = 0; static const int kSpvLoadPtrIdInIdx = 0; static const int kSpvAccessChainBaseIdInIdx = 0; static const int kSpvAccessChainIndex0IdInIdx = 1; +static const int kSpvTypeArrayTypeIdInIdx = 0; static const int kSpvTypeArrayLengthIdInIdx = 1; static const int kSpvConstantValueInIdx = 0; static const int kSpvVariableStorageClassInIdx = 0; - +static const int kSpvTypePtrTypeIdInIdx = 1; +static const int kSpvTypeImageDim = 1; +static const int kSpvTypeImageDepth = 2; +static const int kSpvTypeImageArrayed = 3; +static const int kSpvTypeImageMS = 4; +static const int kSpvTypeImageSampled = 5; } // anonymous namespace // Avoid unused variable warning/error on Linux @@ -75,42 +82,51 @@ uint32_t InstBindlessCheckPass::GenDebugReadInit(uint32_t var_id, } } +uint32_t InstBindlessCheckPass::CloneOriginalImage( + uint32_t old_image_id, InstructionBuilder* builder) { + Instruction* new_image_inst; + Instruction* old_image_inst = get_def_use_mgr()->GetDef(old_image_id); + if (old_image_inst->opcode() == SpvOpLoad) { + new_image_inst = builder->AddLoad( + old_image_inst->type_id(), + old_image_inst->GetSingleWordInOperand(kSpvLoadPtrIdInIdx)); + } else if (old_image_inst->opcode() == SpvOp::SpvOpSampledImage) { + uint32_t clone_id = CloneOriginalImage( + old_image_inst->GetSingleWordInOperand(kSpvSampledImageImageIdInIdx), + builder); + new_image_inst = builder->AddBinaryOp( + old_image_inst->type_id(), SpvOpSampledImage, clone_id, + old_image_inst->GetSingleWordInOperand(kSpvSampledImageSamplerIdInIdx)); + } else if (old_image_inst->opcode() == SpvOp::SpvOpImage) { + uint32_t clone_id = CloneOriginalImage( + old_image_inst->GetSingleWordInOperand(kSpvImageSampledImageIdInIdx), + builder); + new_image_inst = + builder->AddUnaryOp(old_image_inst->type_id(), SpvOpImage, clone_id); + } else { + assert(old_image_inst->opcode() == SpvOp::SpvOpCopyObject && + "expecting OpCopyObject"); + uint32_t clone_id = CloneOriginalImage( + old_image_inst->GetSingleWordInOperand(kSpvCopyObjectOperandIdInIdx), + builder); + // Since we are cloning, no need to create new copy + new_image_inst = get_def_use_mgr()->GetDef(clone_id); + } + uid2offset_[new_image_inst->unique_id()] = + uid2offset_[old_image_inst->unique_id()]; + uint32_t new_image_id = new_image_inst->result_id(); + get_decoration_mgr()->CloneDecorations(old_image_id, new_image_id); + return new_image_id; +} + uint32_t InstBindlessCheckPass::CloneOriginalReference( - ref_analysis* ref, InstructionBuilder* builder) { + RefAnalysis* ref, InstructionBuilder* builder) { // If original is image based, start by cloning descriptor load uint32_t new_image_id = 0; if (ref->desc_load_id != 0) { - Instruction* desc_load_inst = get_def_use_mgr()->GetDef(ref->desc_load_id); - Instruction* new_load_inst = builder->AddLoad( - desc_load_inst->type_id(), - desc_load_inst->GetSingleWordInOperand(kSpvLoadPtrIdInIdx)); - uid2offset_[new_load_inst->unique_id()] = - uid2offset_[desc_load_inst->unique_id()]; - uint32_t new_load_id = new_load_inst->result_id(); - get_decoration_mgr()->CloneDecorations(desc_load_inst->result_id(), - new_load_id); - new_image_id = new_load_id; - // Clone Image/SampledImage with new load, if needed - if (ref->image_id != 0) { - Instruction* image_inst = get_def_use_mgr()->GetDef(ref->image_id); - if (image_inst->opcode() == SpvOp::SpvOpSampledImage) { - Instruction* new_image_inst = builder->AddBinaryOp( - image_inst->type_id(), SpvOpSampledImage, new_load_id, - image_inst->GetSingleWordInOperand(kSpvSampledImageSamplerIdInIdx)); - uid2offset_[new_image_inst->unique_id()] = - uid2offset_[image_inst->unique_id()]; - new_image_id = new_image_inst->result_id(); - } else { - assert(image_inst->opcode() == SpvOp::SpvOpImage && - "expecting OpImage"); - Instruction* new_image_inst = - builder->AddUnaryOp(image_inst->type_id(), SpvOpImage, new_load_id); - uid2offset_[new_image_inst->unique_id()] = - uid2offset_[image_inst->unique_id()]; - new_image_id = new_image_inst->result_id(); - } - get_decoration_mgr()->CloneDecorations(ref->image_id, new_image_id); - } + uint32_t old_image_id = + ref->ref_inst->GetSingleWordInOperand(kSpvImageSampleImageIdInIdx); + new_image_id = CloneOriginalImage(old_image_id, builder); } // Clone original reference std::unique_ptr new_ref_inst(ref->ref_inst->Clone(context())); @@ -179,7 +195,7 @@ Instruction* InstBindlessCheckPass::GetPointeeTypeInst(Instruction* ptr_inst) { } bool InstBindlessCheckPass::AnalyzeDescriptorReference(Instruction* ref_inst, - ref_analysis* ref) { + RefAnalysis* ref) { ref->ref_inst = ref_inst; if (ref_inst->opcode() == SpvOpLoad || ref_inst->opcode() == SpvOpStore) { ref->desc_load_id = 0; @@ -193,13 +209,40 @@ bool InstBindlessCheckPass::AnalyzeDescriptorReference(Instruction* ref_inst, var_inst->GetSingleWordInOperand(kSpvVariableStorageClassInIdx); switch (storage_class) { case SpvStorageClassUniform: - case SpvStorageClassUniformConstant: case SpvStorageClassStorageBuffer: break; default: return false; break; } + // Check for deprecated storage block form + if (storage_class == SpvStorageClassUniform) { + uint32_t var_ty_id = var_inst->type_id(); + Instruction* var_ty_inst = get_def_use_mgr()->GetDef(var_ty_id); + uint32_t ptr_ty_id = + var_ty_inst->GetSingleWordInOperand(kSpvTypePtrTypeIdInIdx); + Instruction* ptr_ty_inst = get_def_use_mgr()->GetDef(ptr_ty_id); + SpvOp ptr_ty_op = ptr_ty_inst->opcode(); + uint32_t block_ty_id = + (ptr_ty_op == SpvOpTypeArray || ptr_ty_op == SpvOpTypeRuntimeArray) + ? ptr_ty_inst->GetSingleWordInOperand(kSpvTypeArrayTypeIdInIdx) + : ptr_ty_id; + assert(get_def_use_mgr()->GetDef(block_ty_id)->opcode() == + SpvOpTypeStruct && + "unexpected block type"); + bool block_found = get_decoration_mgr()->FindDecoration( + block_ty_id, SpvDecorationBlock, + [](const Instruction&) { return true; }); + if (!block_found) { + // If block decoration not found, verify deprecated form of SSBO + bool buffer_block_found = get_decoration_mgr()->FindDecoration( + block_ty_id, SpvDecorationBufferBlock, + [](const Instruction&) { return true; }); + USE_ASSERT(buffer_block_found && "block decoration not found"); + storage_class = SpvStorageClassStorageBuffer; + } + } + ref->strg_class = storage_class; Instruction* desc_type_inst = GetPointeeTypeInst(var_inst); switch (desc_type_inst->opcode()) { case SpvOpTypeArray: @@ -220,25 +263,28 @@ bool InstBindlessCheckPass::AnalyzeDescriptorReference(Instruction* ref_inst, // Reference is not load or store. If not an image-based reference, return. ref->image_id = GetImageId(ref_inst); if (ref->image_id == 0) return false; - Instruction* image_inst = get_def_use_mgr()->GetDef(ref->image_id); - Instruction* desc_load_inst = nullptr; - if (image_inst->opcode() == SpvOp::SpvOpSampledImage) { - ref->desc_load_id = - image_inst->GetSingleWordInOperand(kSpvSampledImageImageIdInIdx); - desc_load_inst = get_def_use_mgr()->GetDef(ref->desc_load_id); - } else if (image_inst->opcode() == SpvOp::SpvOpImage) { - ref->desc_load_id = - image_inst->GetSingleWordInOperand(kSpvImageSampledImageIdInIdx); - desc_load_inst = get_def_use_mgr()->GetDef(ref->desc_load_id); - } else { - ref->desc_load_id = ref->image_id; - desc_load_inst = image_inst; - ref->image_id = 0; + // Search for descriptor load + uint32_t desc_load_id = ref->image_id; + Instruction* desc_load_inst; + for (;;) { + desc_load_inst = get_def_use_mgr()->GetDef(desc_load_id); + if (desc_load_inst->opcode() == SpvOp::SpvOpSampledImage) + desc_load_id = + desc_load_inst->GetSingleWordInOperand(kSpvSampledImageImageIdInIdx); + else if (desc_load_inst->opcode() == SpvOp::SpvOpImage) + desc_load_id = + desc_load_inst->GetSingleWordInOperand(kSpvImageSampledImageIdInIdx); + else if (desc_load_inst->opcode() == SpvOp::SpvOpCopyObject) + desc_load_id = + desc_load_inst->GetSingleWordInOperand(kSpvCopyObjectOperandIdInIdx); + else + break; } if (desc_load_inst->opcode() != SpvOp::SpvOpLoad) { // TODO(greg-lunarg): Handle additional possibilities? return false; } + ref->desc_load_id = desc_load_id; ref->ptr_id = desc_load_inst->GetSingleWordInOperand(kSpvLoadPtrIdInIdx); Instruction* ptr_inst = get_def_use_mgr()->GetDef(ref->ptr_id); if (ptr_inst->opcode() == SpvOp::SpvOpVariable) { @@ -267,34 +313,45 @@ bool InstBindlessCheckPass::AnalyzeDescriptorReference(Instruction* ref_inst, uint32_t InstBindlessCheckPass::FindStride(uint32_t ty_id, uint32_t stride_deco) { uint32_t stride = 0xdeadbeef; - bool found = !get_decoration_mgr()->WhileEachDecoration( + bool found = get_decoration_mgr()->FindDecoration( ty_id, stride_deco, [&stride](const Instruction& deco_inst) { stride = deco_inst.GetSingleWordInOperand(2u); - return false; + return true; }); USE_ASSERT(found && "stride not found"); return stride; } -uint32_t InstBindlessCheckPass::ByteSize(uint32_t ty_id) { +uint32_t InstBindlessCheckPass::ByteSize(uint32_t ty_id, uint32_t matrix_stride, + bool col_major, bool in_matrix) { analysis::TypeManager* type_mgr = context()->get_type_mgr(); const analysis::Type* sz_ty = type_mgr->GetType(ty_id); if (sz_ty->kind() == analysis::Type::kPointer) { // Assuming PhysicalStorageBuffer pointer return 8; } - uint32_t size = 1; if (sz_ty->kind() == analysis::Type::kMatrix) { + assert(matrix_stride != 0 && "missing matrix stride"); const analysis::Matrix* m_ty = sz_ty->AsMatrix(); - size = m_ty->element_count() * size; - uint32_t stride = FindStride(ty_id, SpvDecorationMatrixStride); - if (stride != 0) return size * stride; - sz_ty = m_ty->element_type(); + if (col_major) { + return m_ty->element_count() * matrix_stride; + } else { + const analysis::Vector* v_ty = m_ty->element_type()->AsVector(); + return v_ty->element_count() * matrix_stride; + } } + uint32_t size = 1; if (sz_ty->kind() == analysis::Type::kVector) { const analysis::Vector* v_ty = sz_ty->AsVector(); - size = v_ty->element_count() * size; - sz_ty = v_ty->element_type(); + size = v_ty->element_count(); + const analysis::Type* comp_ty = v_ty->element_type(); + // if vector in row major matrix, the vector is strided so return the + // number of bytes spanned by the vector + if (in_matrix && !col_major && matrix_stride > 0) { + uint32_t comp_ty_id = type_mgr->GetId(comp_ty); + return (size - 1) * matrix_stride + ByteSize(comp_ty_id, 0, false, false); + } + sz_ty = comp_ty; } switch (sz_ty->kind()) { case analysis::Type::kFloat: { @@ -311,7 +368,7 @@ uint32_t InstBindlessCheckPass::ByteSize(uint32_t ty_id) { return size; } -uint32_t InstBindlessCheckPass::GenLastByteIdx(ref_analysis* ref, +uint32_t InstBindlessCheckPass::GenLastByteIdx(RefAnalysis* ref, InstructionBuilder* builder) { // Find outermost buffer type and its access chain index Instruction* var_inst = get_def_use_mgr()->GetDef(ref->var_id); @@ -333,21 +390,20 @@ uint32_t InstBindlessCheckPass::GenLastByteIdx(ref_analysis* ref, // Process remaining access chain indices Instruction* ac_inst = get_def_use_mgr()->GetDef(ref->ptr_id); uint32_t curr_ty_id = buff_ty_id; - uint32_t sum_id = 0; + uint32_t sum_id = 0u; + uint32_t matrix_stride = 0u; + bool col_major = false; + uint32_t matrix_stride_id = 0u; + bool in_matrix = false; while (ac_in_idx < ac_inst->NumInOperands()) { uint32_t curr_idx_id = ac_inst->GetSingleWordInOperand(ac_in_idx); - Instruction* curr_idx_inst = get_def_use_mgr()->GetDef(curr_idx_id); Instruction* curr_ty_inst = get_def_use_mgr()->GetDef(curr_ty_id); uint32_t curr_offset_id = 0; switch (curr_ty_inst->opcode()) { case SpvOpTypeArray: - case SpvOpTypeRuntimeArray: - case SpvOpTypeMatrix: { - // Get array/matrix stride and multiply by current index - uint32_t stride_deco = (curr_ty_inst->opcode() == SpvOpTypeMatrix) - ? SpvDecorationMatrixStride - : SpvDecorationArrayStride; - uint32_t arr_stride = FindStride(curr_ty_id, stride_deco); + case SpvOpTypeRuntimeArray: { + // Get array stride and multiply by current index + uint32_t arr_stride = FindStride(curr_ty_id, SpvDecorationArrayStride); uint32_t arr_stride_id = builder->GetUintConstantId(arr_stride); uint32_t curr_idx_32b_id = Gen32BitCvtCode(curr_idx_id, builder); Instruction* curr_offset_inst = builder->AddBinaryOp( @@ -356,34 +412,89 @@ uint32_t InstBindlessCheckPass::GenLastByteIdx(ref_analysis* ref, // Get element type for next step curr_ty_id = curr_ty_inst->GetSingleWordInOperand(0); } break; - case SpvOpTypeVector: { - // Stride is size of component type - uint32_t comp_ty_id = curr_ty_inst->GetSingleWordInOperand(0u); - uint32_t vec_stride = ByteSize(comp_ty_id); - uint32_t vec_stride_id = builder->GetUintConstantId(vec_stride); + case SpvOpTypeMatrix: { + assert(matrix_stride != 0 && "missing matrix stride"); + matrix_stride_id = builder->GetUintConstantId(matrix_stride); + uint32_t vec_ty_id = curr_ty_inst->GetSingleWordInOperand(0); + // If column major, multiply column index by matrix stride, otherwise + // by vector component size and save matrix stride for vector (row) + // index + uint32_t col_stride_id; + if (col_major) { + col_stride_id = matrix_stride_id; + } else { + Instruction* vec_ty_inst = get_def_use_mgr()->GetDef(vec_ty_id); + uint32_t comp_ty_id = vec_ty_inst->GetSingleWordInOperand(0u); + uint32_t col_stride = ByteSize(comp_ty_id, 0u, false, false); + col_stride_id = builder->GetUintConstantId(col_stride); + } uint32_t curr_idx_32b_id = Gen32BitCvtCode(curr_idx_id, builder); Instruction* curr_offset_inst = builder->AddBinaryOp( - GetUintId(), SpvOpIMul, vec_stride_id, curr_idx_32b_id); + GetUintId(), SpvOpIMul, col_stride_id, curr_idx_32b_id); curr_offset_id = curr_offset_inst->result_id(); // Get element type for next step + curr_ty_id = vec_ty_id; + in_matrix = true; + } break; + case SpvOpTypeVector: { + // If inside a row major matrix type, multiply index by matrix stride, + // else multiply by component size + uint32_t comp_ty_id = curr_ty_inst->GetSingleWordInOperand(0u); + uint32_t curr_idx_32b_id = Gen32BitCvtCode(curr_idx_id, builder); + if (in_matrix && !col_major) { + Instruction* curr_offset_inst = builder->AddBinaryOp( + GetUintId(), SpvOpIMul, matrix_stride_id, curr_idx_32b_id); + curr_offset_id = curr_offset_inst->result_id(); + } else { + uint32_t comp_ty_sz = ByteSize(comp_ty_id, 0u, false, false); + uint32_t comp_ty_sz_id = builder->GetUintConstantId(comp_ty_sz); + Instruction* curr_offset_inst = builder->AddBinaryOp( + GetUintId(), SpvOpIMul, comp_ty_sz_id, curr_idx_32b_id); + curr_offset_id = curr_offset_inst->result_id(); + } + // Get element type for next step curr_ty_id = comp_ty_id; } break; case SpvOpTypeStruct: { // Get buffer byte offset for the referenced member + Instruction* curr_idx_inst = get_def_use_mgr()->GetDef(curr_idx_id); assert(curr_idx_inst->opcode() == SpvOpConstant && "unexpected struct index"); uint32_t member_idx = curr_idx_inst->GetSingleWordInOperand(0); uint32_t member_offset = 0xdeadbeef; - bool found = !get_decoration_mgr()->WhileEachDecoration( + bool found = get_decoration_mgr()->FindDecoration( curr_ty_id, SpvDecorationOffset, [&member_idx, &member_offset](const Instruction& deco_inst) { if (deco_inst.GetSingleWordInOperand(1u) != member_idx) - return true; + return false; member_offset = deco_inst.GetSingleWordInOperand(3u); - return false; + return true; }); USE_ASSERT(found && "member offset not found"); curr_offset_id = builder->GetUintConstantId(member_offset); + // Look for matrix stride for this member if there is one. The matrix + // stride is not on the matrix type, but in a OpMemberDecorate on the + // enclosing struct type at the member index. If none found, reset + // stride to 0. + found = get_decoration_mgr()->FindDecoration( + curr_ty_id, SpvDecorationMatrixStride, + [&member_idx, &matrix_stride](const Instruction& deco_inst) { + if (deco_inst.GetSingleWordInOperand(1u) != member_idx) + return false; + matrix_stride = deco_inst.GetSingleWordInOperand(3u); + return true; + }); + if (!found) matrix_stride = 0; + // Look for column major decoration + found = get_decoration_mgr()->FindDecoration( + curr_ty_id, SpvDecorationColMajor, + [&member_idx, &col_major](const Instruction& deco_inst) { + if (deco_inst.GetSingleWordInOperand(1u) != member_idx) + return false; + col_major = true; + return true; + }); + if (!found) col_major = false; // Get element type for next step curr_ty_id = curr_ty_inst->GetSingleWordInOperand(member_idx); } break; @@ -399,7 +510,7 @@ uint32_t InstBindlessCheckPass::GenLastByteIdx(ref_analysis* ref, ++ac_in_idx; } // Add in offset of last byte of referenced object - uint32_t bsize = ByteSize(curr_ty_id); + uint32_t bsize = ByteSize(curr_ty_id, matrix_stride, col_major, in_matrix); uint32_t last = bsize - 1; uint32_t last_id = builder->GetUintConstantId(last); Instruction* sum_inst = @@ -409,7 +520,7 @@ uint32_t InstBindlessCheckPass::GenLastByteIdx(ref_analysis* ref, void InstBindlessCheckPass::GenCheckCode( uint32_t check_id, uint32_t error_id, uint32_t offset_id, - uint32_t length_id, uint32_t stage_idx, ref_analysis* ref, + uint32_t length_id, uint32_t stage_idx, RefAnalysis* ref, std::vector>* new_blocks) { BasicBlock* back_blk_ptr = &*new_blocks->back(); InstructionBuilder builder( @@ -443,7 +554,7 @@ void InstBindlessCheckPass::GenCheckCode( GenDebugStreamWrite(uid2offset_[ref->ref_inst->unique_id()], stage_idx, {error_id, u_index_id, u_offset_id, u_length_id}, &builder); - } else if (buffer_bounds_enabled_) { + } else if (buffer_bounds_enabled_ || texel_buffer_enabled_) { // Uninitialized Descriptor - Return additional unused zero so all error // modes will use same debug stream write function uint32_t u_length_id = GenUintCastCode(length_id, &builder); @@ -486,7 +597,7 @@ void InstBindlessCheckPass::GenDescIdxCheckCode( std::vector>* new_blocks) { // Look for reference through indexed descriptor. If found, analyze and // save components. If not, return. - ref_analysis ref; + RefAnalysis ref; if (!AnalyzeDescriptorReference(&*ref_inst_itr, &ref)) return; Instruction* ptr_inst = get_def_use_mgr()->GetDef(ref.ptr_id); if (ptr_inst->opcode() != SpvOp::SpvOpAccessChain) return; @@ -545,7 +656,7 @@ void InstBindlessCheckPass::GenDescInitCheckCode( UptrVectorIterator ref_block_itr, uint32_t stage_idx, std::vector>* new_blocks) { // Look for reference through descriptor. If not, return. - ref_analysis ref; + RefAnalysis ref; if (!AnalyzeDescriptorReference(&*ref_inst_itr, &ref)) return; // Determine if we can only do initialization check bool init_check = false; @@ -584,8 +695,10 @@ void InstBindlessCheckPass::GenDescInitCheckCode( // for the referenced value. Instruction* ult_inst = builder.AddBinaryOp(GetBoolId(), SpvOpULessThan, ref_id, init_id); - uint32_t error = - init_check ? kInstErrorBindlessUninit : kInstErrorBindlessBuffOOB; + uint32_t error = init_check ? kInstErrorBindlessUninit + : (ref.strg_class == SpvStorageClassUniform + ? kInstErrorBuffOOBUniform + : kInstErrorBuffOOBStorage); uint32_t error_id = builder.GetUintConstantId(error); GenCheckCode(ult_inst->result_id(), error_id, init_check ? 0 : ref_id, init_check ? builder.GetUintConstantId(0u) : init_id, stage_idx, @@ -596,12 +709,81 @@ void InstBindlessCheckPass::GenDescInitCheckCode( MovePostludeCode(ref_block_itr, back_blk_ptr); } +void InstBindlessCheckPass::GenTexBuffCheckCode( + BasicBlock::iterator ref_inst_itr, + UptrVectorIterator ref_block_itr, uint32_t stage_idx, + std::vector>* new_blocks) { + // Only process OpImageRead and OpImageWrite with no optional operands + Instruction* ref_inst = &*ref_inst_itr; + SpvOp op = ref_inst->opcode(); + uint32_t num_in_oprnds = ref_inst->NumInOperands(); + if (!((op == SpvOpImageRead && num_in_oprnds == 2) || + (op == SpvOpImageFetch && num_in_oprnds == 2) || + (op == SpvOpImageWrite && num_in_oprnds == 3))) + return; + // Pull components from descriptor reference + RefAnalysis ref; + if (!AnalyzeDescriptorReference(ref_inst, &ref)) return; + // Only process if image is texel buffer + Instruction* image_inst = get_def_use_mgr()->GetDef(ref.image_id); + uint32_t image_ty_id = image_inst->type_id(); + Instruction* image_ty_inst = get_def_use_mgr()->GetDef(image_ty_id); + if (image_ty_inst->GetSingleWordInOperand(kSpvTypeImageDim) != SpvDimBuffer) + return; + if (image_ty_inst->GetSingleWordInOperand(kSpvTypeImageDepth) != 0) return; + if (image_ty_inst->GetSingleWordInOperand(kSpvTypeImageArrayed) != 0) return; + if (image_ty_inst->GetSingleWordInOperand(kSpvTypeImageMS) != 0) return; + // Enable ImageQuery Capability if not yet enabled + if (!get_feature_mgr()->HasCapability(SpvCapabilityImageQuery)) { + std::unique_ptr cap_image_query_inst(new Instruction( + context(), SpvOpCapability, 0, 0, + std::initializer_list{ + {SPV_OPERAND_TYPE_CAPABILITY, {SpvCapabilityImageQuery}}})); + get_def_use_mgr()->AnalyzeInstDefUse(&*cap_image_query_inst); + context()->AddCapability(std::move(cap_image_query_inst)); + } + // Move original block's preceding instructions into first new block + std::unique_ptr new_blk_ptr; + MovePreludeCode(ref_inst_itr, ref_block_itr, &new_blk_ptr); + InstructionBuilder builder( + context(), &*new_blk_ptr, + IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping); + new_blocks->push_back(std::move(new_blk_ptr)); + // Get texel coordinate + uint32_t coord_id = + GenUintCastCode(ref_inst->GetSingleWordInOperand(1), &builder); + // If index id not yet set, binding is single descriptor, so set index to + // constant 0. + if (ref.desc_idx_id == 0) ref.desc_idx_id = builder.GetUintConstantId(0u); + // Get texel buffer size. + Instruction* size_inst = + builder.AddUnaryOp(GetUintId(), SpvOpImageQuerySize, ref.image_id); + uint32_t size_id = size_inst->result_id(); + // Generate runtime initialization/bounds test code with true branch + // being full reference and false branch being debug output and zero + // for the referenced value. + Instruction* ult_inst = + builder.AddBinaryOp(GetBoolId(), SpvOpULessThan, coord_id, size_id); + uint32_t error = + (image_ty_inst->GetSingleWordInOperand(kSpvTypeImageSampled) == 2) + ? kInstErrorBuffOOBStorageTexel + : kInstErrorBuffOOBUniformTexel; + uint32_t error_id = builder.GetUintConstantId(error); + GenCheckCode(ult_inst->result_id(), error_id, coord_id, size_id, stage_idx, + &ref, new_blocks); + // Move original block's remaining code into remainder/merge block and add + // to new blocks + BasicBlock* back_blk_ptr = &*new_blocks->back(); + MovePostludeCode(ref_block_itr, back_blk_ptr); +} + void InstBindlessCheckPass::InitializeInstBindlessCheck() { // Initialize base class InitializeInstrument(); - // If runtime array length support enabled, create variable mappings. Length - // support is always enabled if descriptor init check is enabled. - if (desc_idx_enabled_ || buffer_bounds_enabled_) + // If runtime array length support or buffer bounds checking are enabled, + // create variable mappings. Length support is always enabled if descriptor + // init check is enabled. + if (desc_idx_enabled_ || buffer_bounds_enabled_ || texel_buffer_enabled_) for (auto& anno : get_module()->annotations()) if (anno.opcode() == SpvOpDecorate) { if (anno.GetSingleWordInOperand(1u) == SpvDecorationDescriptorSet) @@ -624,8 +806,8 @@ Pass::Status InstBindlessCheckPass::ProcessImpl() { }; bool modified = InstProcessEntryPointCallTree(pfn); if (desc_init_enabled_ || buffer_bounds_enabled_) { - // Perform descriptor initialization check on each entry point function in - // module + // Perform descriptor initialization and/or buffer bounds check on each + // entry point function in module pfn = [this](BasicBlock::iterator ref_inst_itr, UptrVectorIterator ref_block_itr, uint32_t stage_idx, @@ -635,6 +817,18 @@ Pass::Status InstBindlessCheckPass::ProcessImpl() { }; modified |= InstProcessEntryPointCallTree(pfn); } + if (texel_buffer_enabled_) { + // Perform texel buffer bounds check on each entry point function in + // module. Generate after descriptor bounds and initialization checks. + pfn = [this](BasicBlock::iterator ref_inst_itr, + UptrVectorIterator ref_block_itr, + uint32_t stage_idx, + std::vector>* new_blocks) { + return GenTexBuffCheckCode(ref_inst_itr, ref_block_itr, stage_idx, + new_blocks); + }; + modified |= InstProcessEntryPointCallTree(pfn); + } return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange; } diff --git a/third_party/spirv-tools/source/opt/inst_bindless_check_pass.h b/third_party/spirv-tools/source/opt/inst_bindless_check_pass.h index 50dfd95d43..cd9618059f 100644 --- a/third_party/spirv-tools/source/opt/inst_bindless_check_pass.h +++ b/third_party/spirv-tools/source/opt/inst_bindless_check_pass.h @@ -28,24 +28,16 @@ namespace opt { // external design may change as the layer evolves. class InstBindlessCheckPass : public InstrumentPass { public: - // Old interface to support testing pre-buffer-overrun capability - InstBindlessCheckPass(uint32_t desc_set, uint32_t shader_id, - bool desc_idx_enable, bool desc_init_enable) - : InstrumentPass(desc_set, shader_id, kInstValidationIdBindless, false), - desc_idx_enabled_(desc_idx_enable), - desc_init_enabled_(desc_init_enable), - buffer_bounds_enabled_(false) {} - - // New interface supporting buffer overrun checking InstBindlessCheckPass(uint32_t desc_set, uint32_t shader_id, bool desc_idx_enable, bool desc_init_enable, - bool buffer_bounds_enable) - : InstrumentPass( - desc_set, shader_id, kInstValidationIdBindless, - desc_idx_enable || desc_init_enable || buffer_bounds_enable), + bool buffer_bounds_enable, bool texel_buffer_enable, + bool opt_direct_reads) + : InstrumentPass(desc_set, shader_id, kInstValidationIdBindless, + opt_direct_reads), desc_idx_enabled_(desc_idx_enable), desc_init_enabled_(desc_init_enable), - buffer_bounds_enabled_(buffer_bounds_enable) {} + buffer_bounds_enabled_(buffer_bounds_enable), + texel_buffer_enabled_(texel_buffer_enable) {} ~InstBindlessCheckPass() override = default; @@ -63,6 +55,10 @@ class InstBindlessCheckPass : public InstrumentPass { // checks that the referenced descriptor has been initialized, if the // SPV_EXT_descriptor_indexing extension is enabled, and initialized large // enough to handle the reference, if RobustBufferAccess is disabled. + // GenDescInitCheckCode checks for uniform and storage buffer overrun. + // GenTexBuffCheckCode checks for texel buffer overrun and should be + // run after GenDescInitCheckCode to first make sure that the descriptor + // is initialized because it uses OpImageQuerySize on the descriptor. // // The functions are designed to be passed to // InstrumentPass::InstProcessEntryPointCallTree(), which applies the @@ -109,6 +105,11 @@ class InstBindlessCheckPass : public InstrumentPass { UptrVectorIterator ref_block_itr, uint32_t stage_idx, std::vector>* new_blocks); + void GenTexBuffCheckCode( + BasicBlock::iterator ref_inst_itr, + UptrVectorIterator ref_block_itr, uint32_t stage_idx, + std::vector>* new_blocks); + // Generate instructions into |builder| to read length of runtime descriptor // array |var_id| from debug input buffer and return id of value. uint32_t GenDebugReadLength(uint32_t var_id, InstructionBuilder* builder); @@ -122,29 +123,36 @@ class InstBindlessCheckPass : public InstrumentPass { // Analysis data for descriptor reference components, generated by // AnalyzeDescriptorReference. It is necessary and sufficient for further // analysis and regeneration of the reference. - typedef struct ref_analysis { + typedef struct RefAnalysis { uint32_t desc_load_id; uint32_t image_id; uint32_t load_id; uint32_t ptr_id; uint32_t var_id; uint32_t desc_idx_id; + uint32_t strg_class; Instruction* ref_inst; - } ref_analysis; + } RefAnalysis; - // Return size of type |ty_id| in bytes. - uint32_t ByteSize(uint32_t ty_id); + // Return size of type |ty_id| in bytes. Use |matrix_stride| and |col_major| + // for matrix type, or for vector type if vector is |in_matrix|. + uint32_t ByteSize(uint32_t ty_id, uint32_t matrix_stride, bool col_major, + bool in_matrix); // Return stride of type |ty_id| with decoration |stride_deco|. Return 0 // if not found uint32_t FindStride(uint32_t ty_id, uint32_t stride_deco); // Generate index of last byte referenced by buffer reference |ref| - uint32_t GenLastByteIdx(ref_analysis* ref, InstructionBuilder* builder); + uint32_t GenLastByteIdx(RefAnalysis* ref, InstructionBuilder* builder); + + // Clone original image computation starting at |image_id| into |builder|. + // This may generate more than one instruction if neccessary. + uint32_t CloneOriginalImage(uint32_t image_id, InstructionBuilder* builder); // Clone original original reference encapsulated by |ref| into |builder|. // This may generate more than one instruction if neccessary. - uint32_t CloneOriginalReference(ref_analysis* ref, + uint32_t CloneOriginalReference(RefAnalysis* ref, InstructionBuilder* builder); // If |inst| references through an image, return the id of the image it @@ -156,7 +164,7 @@ class InstBindlessCheckPass : public InstrumentPass { // Analyze descriptor reference |ref_inst| and save components into |ref|. // Return true if |ref_inst| is a descriptor reference, false otherwise. - bool AnalyzeDescriptorReference(Instruction* ref_inst, ref_analysis* ref); + bool AnalyzeDescriptorReference(Instruction* ref_inst, RefAnalysis* ref); // Generate instrumentation code for generic test result |check_id|, starting // with |builder| of block |new_blk_ptr|, adding new blocks to |new_blocks|. @@ -166,7 +174,7 @@ class InstBindlessCheckPass : public InstrumentPass { // |stage_idx|. Generate merge block for valid and invalid branches. Kill // original reference. void GenCheckCode(uint32_t check_id, uint32_t error_id, uint32_t offset_id, - uint32_t length_id, uint32_t stage_idx, ref_analysis* ref, + uint32_t length_id, uint32_t stage_idx, RefAnalysis* ref, std::vector>* new_blocks); // Initialize state for instrumenting bindless checking @@ -182,9 +190,12 @@ class InstBindlessCheckPass : public InstrumentPass { // Enable instrumentation of descriptor initialization checking bool desc_init_enabled_; - // Enable instrumentation of buffer overrun checking + // Enable instrumentation of uniform and storage buffer overrun checking bool buffer_bounds_enabled_; + // Enable instrumentation of texel buffer overrun checking + bool texel_buffer_enabled_; + // Mapping from variable to descriptor set std::unordered_map var2desc_set_; diff --git a/third_party/spirv-tools/source/opt/inst_buff_addr_check_pass.cpp b/third_party/spirv-tools/source/opt/inst_buff_addr_check_pass.cpp index fa6c2c6a03..06acc7ea55 100644 --- a/third_party/spirv-tools/source/opt/inst_buff_addr_check_pass.cpp +++ b/third_party/spirv-tools/source/opt/inst_buff_addr_check_pass.cpp @@ -202,7 +202,6 @@ uint32_t InstBuffAddrCheckPass::GetSearchAndTestFuncId() { (void)builder.AddInstruction(MakeUnique( context(), SpvOpBranch, 0, 0, std::initializer_list{{SPV_OPERAND_TYPE_ID, {hdr_blk_id}}})); - first_blk_ptr->SetParent(&*input_func); input_func->AddBasicBlock(std::move(first_blk_ptr)); // Linear search loop header block // TODO(greg-lunarg): Implement binary search @@ -246,7 +245,6 @@ uint32_t InstBuffAddrCheckPass::GetSearchAndTestFuncId() { (void)builder.AddInstruction(MakeUnique( context(), SpvOpBranch, 0, 0, std::initializer_list{{SPV_OPERAND_TYPE_ID, {cont_blk_id}}})); - hdr_blk_ptr->SetParent(&*input_func); input_func->AddBasicBlock(std::move(hdr_blk_ptr)); // Continue/Work Block. Read next buffer pointer and break if greater // than ref_ptr arg. @@ -272,7 +270,6 @@ uint32_t InstBuffAddrCheckPass::GetSearchAndTestFuncId() { (void)builder.AddConditionalBranch(uptr_test_inst->result_id(), bound_test_blk_id, hdr_blk_id, kInvalidId, SpvSelectionControlMaskNone); - cont_blk_ptr->SetParent(&*input_func); input_func->AddBasicBlock(std::move(cont_blk_ptr)); // Bounds test block. Read length of selected buffer and test that // all len arg bytes are in buffer. @@ -333,7 +330,6 @@ uint32_t InstBuffAddrCheckPass::GetSearchAndTestFuncId() { std::initializer_list{ {SPV_OPERAND_TYPE_ID, {len_test_inst->result_id()}}})); // Close block - bound_test_blk_ptr->SetParent(&*input_func); input_func->AddBasicBlock(std::move(bound_test_blk_ptr)); // Close function and add function to module std::unique_ptr func_end_inst( diff --git a/third_party/spirv-tools/source/opt/instruction.h b/third_party/spirv-tools/source/opt/instruction.h index 252e8cb55d..3e557dd7bf 100644 --- a/third_party/spirv-tools/source/opt/instruction.h +++ b/third_party/spirv-tools/source/opt/instruction.h @@ -97,10 +97,14 @@ struct Operand { assert(type == SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER); assert(1 <= words.size()); assert(words.size() <= 2); - // Load the low word. - uint64_t result = uint64_t(words[0]); + uint64_t result = 0; + if (words.size() > 0) { // Needed to avoid maybe-uninitialized GCC warning + uint32_t low = words[0]; + result = uint64_t(low); + } if (words.size() > 1) { - result = result | (uint64_t(words[1]) << 32); + uint32_t high = words[1]; + result = result | (uint64_t(high) << 32); } return result; } @@ -205,7 +209,7 @@ class Instruction : public utils::IntrusiveNodeBase { Instruction(Instruction&&); Instruction& operator=(Instruction&&); - virtual ~Instruction() = default; + ~Instruction() override = default; // Returns a newly allocated instruction that has the same operands, result, // and type as |this|. The new instruction is not linked into any list. diff --git a/third_party/spirv-tools/source/opt/instruction_list.h b/third_party/spirv-tools/source/opt/instruction_list.h index 417cbd768b..b3e4274591 100644 --- a/third_party/spirv-tools/source/opt/instruction_list.h +++ b/third_party/spirv-tools/source/opt/instruction_list.h @@ -53,7 +53,7 @@ class InstructionList : public utils::IntrusiveList { } // Destroy this list and any instructions in the list. - inline virtual ~InstructionList(); + inline ~InstructionList() override; class iterator : public utils::IntrusiveList::iterator { public: diff --git a/third_party/spirv-tools/source/opt/instrument_pass.cpp b/third_party/spirv-tools/source/opt/instrument_pass.cpp index e7d97789c8..ed34fb0254 100644 --- a/third_party/spirv-tools/source/opt/instrument_pass.cpp +++ b/third_party/spirv-tools/source/opt/instrument_pass.cpp @@ -758,7 +758,6 @@ uint32_t InstrumentPass::GetStreamWriteFunctionId(uint32_t stage_idx, write_blk_id, merge_blk_id, merge_blk_id, SpvSelectionControlMaskNone); // Close safety test block and gen write block - new_blk_ptr->SetParent(&*output_func); output_func->AddBasicBlock(std::move(new_blk_ptr)); new_blk_ptr = MakeUnique(std::move(write_label)); builder.SetInsertPoint(&*new_blk_ptr); @@ -773,13 +772,11 @@ uint32_t InstrumentPass::GetStreamWriteFunctionId(uint32_t stage_idx, } // Close write block and gen merge block (void)builder.AddBranch(merge_blk_id); - new_blk_ptr->SetParent(&*output_func); output_func->AddBasicBlock(std::move(new_blk_ptr)); new_blk_ptr = MakeUnique(std::move(merge_label)); builder.SetInsertPoint(&*new_blk_ptr); // Close merge block and function and add function to module (void)builder.AddNullaryOp(0, SpvOpReturn); - new_blk_ptr->SetParent(&*output_func); output_func->AddBasicBlock(std::move(new_blk_ptr)); std::unique_ptr func_end_inst( new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {})); @@ -860,7 +857,6 @@ uint32_t InstrumentPass::GetDirectReadFunctionId(uint32_t param_cnt) { context(), SpvOpReturnValue, 0, 0, std::initializer_list{{SPV_OPERAND_TYPE_ID, {last_value_id}}})); // Close block and function and add function to module - new_blk_ptr->SetParent(&*input_func); input_func->AddBasicBlock(std::move(new_blk_ptr)); std::unique_ptr func_end_inst( new Instruction(get_module()->context(), SpvOpFunctionEnd, 0, 0, {})); diff --git a/third_party/spirv-tools/source/opt/interp_fixup_pass.cpp b/third_party/spirv-tools/source/opt/interp_fixup_pass.cpp new file mode 100644 index 0000000000..ad29e6a720 --- /dev/null +++ b/third_party/spirv-tools/source/opt/interp_fixup_pass.cpp @@ -0,0 +1,131 @@ +// Copyright (c) 2021 The Khronos Group Inc. +// Copyright (c) 2021 Valve Corporation +// Copyright (c) 2021 LunarG Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/opt/interp_fixup_pass.h" + +#include +#include + +#include "ir_builder.h" +#include "source/opt/ir_context.h" +#include "type_manager.h" + +namespace spvtools { +namespace opt { + +namespace { + +// Input Operand Indices +static const int kSpvVariableStorageClassInIdx = 0; + +// Avoid unused variable warning/error on Linux +#ifndef NDEBUG +#define USE_ASSERT(x) assert(x) +#else +#define USE_ASSERT(x) ((void)(x)) +#endif + +// Folding rule function which attempts to replace |op(OpLoad(a),...)| +// by |op(a,...)|, where |op| is one of the GLSLstd450 InterpolateAt* +// instructions. Returns true if replaced, false otherwise. +bool ReplaceInternalInterpolate(IRContext* ctx, Instruction* inst, + const std::vector&) { + uint32_t glsl450_ext_inst_id = + ctx->get_feature_mgr()->GetExtInstImportId_GLSLstd450(); + assert(glsl450_ext_inst_id != 0); + + uint32_t ext_opcode = inst->GetSingleWordInOperand(1); + + uint32_t op1_id = inst->GetSingleWordInOperand(2); + + Instruction* load_inst = ctx->get_def_use_mgr()->GetDef(op1_id); + if (load_inst->opcode() != SpvOpLoad) return false; + + Instruction* base_inst = load_inst->GetBaseAddress(); + USE_ASSERT(base_inst->opcode() == SpvOpVariable && + base_inst->GetSingleWordInOperand(kSpvVariableStorageClassInIdx) == + SpvStorageClassInput && + "unexpected interpolant in InterpolateAt*"); + + uint32_t ptr_id = load_inst->GetSingleWordInOperand(0); + uint32_t op2_id = (ext_opcode != GLSLstd450InterpolateAtCentroid) + ? inst->GetSingleWordInOperand(3) + : 0; + + Instruction::OperandList new_operands; + new_operands.push_back({SPV_OPERAND_TYPE_ID, {glsl450_ext_inst_id}}); + new_operands.push_back( + {SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER, {ext_opcode}}); + new_operands.push_back({SPV_OPERAND_TYPE_ID, {ptr_id}}); + if (op2_id != 0) new_operands.push_back({SPV_OPERAND_TYPE_ID, {op2_id}}); + + inst->SetInOperands(std::move(new_operands)); + ctx->UpdateDefUse(inst); + return true; +} + +class InterpFoldingRules : public FoldingRules { + public: + explicit InterpFoldingRules(IRContext* ctx) : FoldingRules(ctx) {} + + protected: + virtual void AddFoldingRules() override { + uint32_t extension_id = + context()->get_feature_mgr()->GetExtInstImportId_GLSLstd450(); + + if (extension_id != 0) { + ext_rules_[{extension_id, GLSLstd450InterpolateAtCentroid}].push_back( + ReplaceInternalInterpolate); + ext_rules_[{extension_id, GLSLstd450InterpolateAtSample}].push_back( + ReplaceInternalInterpolate); + ext_rules_[{extension_id, GLSLstd450InterpolateAtOffset}].push_back( + ReplaceInternalInterpolate); + } + } +}; + +class InterpConstFoldingRules : public ConstantFoldingRules { + public: + InterpConstFoldingRules(IRContext* ctx) : ConstantFoldingRules(ctx) {} + + protected: + virtual void AddFoldingRules() override {} +}; + +} // namespace + +Pass::Status InterpFixupPass::Process() { + bool changed = false; + + // Traverse the body of the functions to replace instructions that require + // the extensions. + InstructionFolder folder( + context(), + std::unique_ptr(new InterpFoldingRules(context())), + MakeUnique(context())); + for (Function& func : *get_module()) { + func.ForEachInst([&changed, &folder](Instruction* inst) { + if (folder.FoldInstruction(inst)) { + changed = true; + } + }); + } + + return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange; +} + +} // namespace opt +} // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/strip_atomic_counter_memory_pass.h b/third_party/spirv-tools/source/opt/interp_fixup_pass.h similarity index 70% rename from third_party/spirv-tools/source/opt/strip_atomic_counter_memory_pass.h rename to third_party/spirv-tools/source/opt/interp_fixup_pass.h index 62e274a197..e112b65157 100644 --- a/third_party/spirv-tools/source/opt/strip_atomic_counter_memory_pass.h +++ b/third_party/spirv-tools/source/opt/interp_fixup_pass.h @@ -1,4 +1,6 @@ -// Copyright (c) 2019 Google LLC. +// Copyright (c) 2021 The Khronos Group Inc. +// Copyright (c) 2021 Valve Corporation +// Copyright (c) 2021 LunarG Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,8 +14,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#ifndef SOURCE_OPT_STRIP_ATOMIC_COUNT_MEMORY_PASS_H_ -#define SOURCE_OPT_STRIP_ATOMIC_COUNT_MEMORY_PASS_H_ +#ifndef SOURCE_OPT_INTERP_FIXUP_H +#define SOURCE_OPT_INTERP_FIXUP_H #include "source/opt/ir_context.h" #include "source/opt/module.h" @@ -22,12 +24,13 @@ namespace spvtools { namespace opt { -// Removes the AtomicCounterMemory bit from the value being passed into memory -// semantics. This bit being set is ignored in Vulkan environments and -// forbidden WebGPU ones. -class StripAtomicCounterMemoryPass : public Pass { +// Replaces overloaded internal form for GLSLstd450Interpolate* instructions +// with external form. Specifically, removes OpLoad from the first argument +// and replaces it with the pointer for the OpLoad. glslang generates the +// internal form. This pass is called as part of glslang HLSL legalization. +class InterpFixupPass : public Pass { public: - const char* name() const override { return "strip-atomic-counter-memory"; } + const char* name() const override { return "interp-fixup"; } Status Process() override; IRContext::Analysis GetPreservedAnalyses() override { @@ -48,4 +51,4 @@ class StripAtomicCounterMemoryPass : public Pass { } // namespace opt } // namespace spvtools -#endif // SOURCE_OPT_STRIP_ATOMIC_COUNT_MEMORY_PASS_H_ +#endif // SOURCE_OPT_INTERP_FIXUP_H diff --git a/third_party/spirv-tools/source/opt/ir_context.cpp b/third_party/spirv-tools/source/opt/ir_context.cpp index 3e610d7079..74f387867b 100644 --- a/third_party/spirv-tools/source/opt/ir_context.cpp +++ b/third_party/spirv-tools/source/opt/ir_context.cpp @@ -214,10 +214,10 @@ Instruction* IRContext::KillInst(Instruction* inst) { return next_instruction; } -void IRContext::KillNonSemanticInfo(Instruction* inst) { +void IRContext::CollectNonSemanticTree( + Instruction* inst, std::unordered_set* to_kill) { if (!inst->HasResultId()) return; std::vector work_list; - std::vector to_kill; std::unordered_set seen; work_list.push_back(inst); @@ -225,17 +225,13 @@ void IRContext::KillNonSemanticInfo(Instruction* inst) { auto* i = work_list.back(); work_list.pop_back(); get_def_use_mgr()->ForEachUser( - i, [&work_list, &to_kill, &seen](Instruction* user) { + i, [&work_list, to_kill, &seen](Instruction* user) { if (user->IsNonSemanticInstruction() && seen.insert(user).second) { work_list.push_back(user); - to_kill.push_back(user); + to_kill->insert(user); } }); } - - for (auto* dead : to_kill) { - KillInst(dead); - } } bool IRContext::KillDef(uint32_t id) { @@ -475,7 +471,7 @@ void IRContext::AddCombinatorsForCapability(uint32_t capability) { SpvOpTypeSampledImage, SpvOpTypeAccelerationStructureNV, SpvOpTypeAccelerationStructureKHR, - SpvOpTypeRayQueryProvisionalKHR, + SpvOpTypeRayQueryKHR, SpvOpTypeArray, SpvOpTypeRuntimeArray, SpvOpTypeStruct, @@ -1038,5 +1034,11 @@ bool IRContext::CheckCFG() { return true; } + +bool IRContext::IsReachable(const opt::BasicBlock& bb) { + auto enclosing_function = bb.GetParent(); + return GetDominatorAnalysis(enclosing_function) + ->Dominates(enclosing_function->entry().get(), &bb); +} } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/ir_context.h b/third_party/spirv-tools/source/opt/ir_context.h index 5aa25acde3..f5f38a648e 100644 --- a/third_party/spirv-tools/source/opt/ir_context.h +++ b/third_party/spirv-tools/source/opt/ir_context.h @@ -403,8 +403,10 @@ class IRContext { // instruction exists. Instruction* KillInst(Instruction* inst); - // Removes the non-semantic instruction tree that uses |inst|'s result id. - void KillNonSemanticInfo(Instruction* inst); + // Collects the non-semantic instruction tree that uses |inst|'s result id + // to be killed later. + void CollectNonSemanticTree(Instruction* inst, + std::unordered_set* to_kill); // Returns true if all of the given analyses are valid. bool AreAnalysesValid(Analysis set) { return (set & valid_analyses_) == set; } @@ -596,10 +598,14 @@ class IRContext { bool ProcessCallTreeFromRoots(ProcessFunction& pfn, std::queue* roots); - // Emmits a error message to the message consumer indicating the error + // Emits a error message to the message consumer indicating the error // described by |message| occurred in |inst|. void EmitErrorMessage(std::string message, Instruction* inst); + // Returns true if and only if there is a path to |bb| from the entry block of + // the function that contains |bb|. + bool IsReachable(const opt::BasicBlock& bb); + private: // Builds the def-use manager from scratch, even if it was already valid. void BuildDefUseManager() { diff --git a/third_party/spirv-tools/source/opt/ir_loader.cpp b/third_party/spirv-tools/source/opt/ir_loader.cpp index 4a44309444..e443ebb5f3 100644 --- a/third_party/spirv-tools/source/opt/ir_loader.cpp +++ b/third_party/spirv-tools/source/opt/ir_loader.cpp @@ -41,6 +41,7 @@ bool IrLoader::AddInstruction(const spv_parsed_instruction_t* inst) { ++inst_index_; const auto opcode = static_cast(inst->opcode); if (IsDebugLineInst(opcode)) { + module()->SetContainsDebugInfo(); last_line_inst_.reset(); dbg_line_info_.push_back( Instruction(module()->context(), *inst, last_dbg_scope_)); @@ -61,12 +62,12 @@ bool IrLoader::AddInstruction(const spv_parsed_instruction_t* inst) { inlined_at = inst->words[kInlinedAtIndex]; last_dbg_scope_ = DebugScope(inst->words[kLexicalScopeIndex], inlined_at); - module()->SetContainsDebugScope(); + module()->SetContainsDebugInfo(); return true; } if (ext_inst_key == OpenCLDebugInfo100DebugNoScope) { last_dbg_scope_ = DebugScope(kNoDebugScope, kNoInlinedAt); - module()->SetContainsDebugScope(); + module()->SetContainsDebugInfo(); return true; } } else { @@ -78,12 +79,12 @@ bool IrLoader::AddInstruction(const spv_parsed_instruction_t* inst) { inlined_at = inst->words[kInlinedAtIndex]; last_dbg_scope_ = DebugScope(inst->words[kLexicalScopeIndex], inlined_at); - module()->SetContainsDebugScope(); + module()->SetContainsDebugInfo(); return true; } if (ext_inst_key == DebugInfoDebugNoScope) { last_dbg_scope_ = DebugScope(kNoDebugScope, kNoInlinedAt); - module()->SetContainsDebugScope(); + module()->SetContainsDebugInfo(); return true; } } @@ -92,7 +93,8 @@ bool IrLoader::AddInstruction(const spv_parsed_instruction_t* inst) { std::unique_ptr spv_inst( new Instruction(module()->context(), *inst, std::move(dbg_line_info_))); if (!spv_inst->dbg_line_insts().empty()) { - if (spv_inst->dbg_line_insts().back().opcode() != SpvOpNoLine) { + if (extra_line_tracking_ && + (spv_inst->dbg_line_insts().back().opcode() != SpvOpNoLine)) { last_line_inst_ = std::unique_ptr( spv_inst->dbg_line_insts().back().Clone(module()->context())); } @@ -136,7 +138,7 @@ bool IrLoader::AddInstruction(const spv_parsed_instruction_t* inst) { return false; } block_ = MakeUnique(std::move(spv_inst)); - } else if (IsTerminatorInst(opcode)) { + } else if (spvOpcodeIsBlockTerminator(opcode)) { if (function_ == nullptr) { Error(consumer_, src, loc, "terminator instruction outside function"); return false; diff --git a/third_party/spirv-tools/source/opt/ir_loader.h b/third_party/spirv-tools/source/opt/ir_loader.h index d0610f139e..16bc2c7c84 100644 --- a/third_party/spirv-tools/source/opt/ir_loader.h +++ b/third_party/spirv-tools/source/opt/ir_loader.h @@ -63,6 +63,10 @@ class IrLoader { // or a missing OpFunctionEnd. Resolves internal bookkeeping. void EndModule(); + // Sets whether extra OpLine instructions should be injected to better + // track line information. + void SetExtraLineTracking(bool flag) { extra_line_tracking_ = flag; } + private: // Consumer for communicating messages to outside. const MessageConsumer& consumer_; @@ -78,11 +82,17 @@ class IrLoader { std::unique_ptr block_; // Line related debug instructions accumulated thus far. std::vector dbg_line_info_; - // Line instruction that should be applied to the next instruction. + // If doing extra line tracking, this is the line instruction that should be + // applied to the next instruction. Otherwise it always contains null. std::unique_ptr last_line_inst_; // The last DebugScope information that IrLoader::AddInstruction() handled. DebugScope last_dbg_scope_; + + // When true, do extra line information tracking: Additional OpLine + // instructions will be injected to help track line info more robustly during + // transformations. + bool extra_line_tracking_ = true; }; } // namespace opt diff --git a/third_party/spirv-tools/source/opt/iterator.h b/third_party/spirv-tools/source/opt/iterator.h index 444d457c5c..2280582dfe 100644 --- a/third_party/spirv-tools/source/opt/iterator.h +++ b/third_party/spirv-tools/source/opt/iterator.h @@ -30,18 +30,14 @@ namespace opt { // std::unique_ptr managed elements in the vector, behaving like we are using // std::vector<|ValueType|>. template -class UptrVectorIterator - : public std::iterator::type> { +class UptrVectorIterator { public: - using super = std::iterator< - std::random_access_iterator_tag, - typename std::conditional::type>; + using iterator_category = std::random_access_iterator_tag; + using value_type = ValueType; - using pointer = typename super::pointer; - using reference = typename super::reference; - using difference_type = typename super::difference_type; + using pointer = value_type*; + using reference = value_type&; + using difference_type = std::ptrdiff_t; // Type aliases. We need to apply constness properly if |IsConst| is true. using Uptr = std::unique_ptr; @@ -174,11 +170,7 @@ inline IteratorRange make_const_range( // // Currently this iterator is always an input iterator. template -class FilterIterator - : public std::iterator< - std::input_iterator_tag, typename SubIterator::value_type, - typename SubIterator::difference_type, typename SubIterator::pointer, - typename SubIterator::reference> { +class FilterIterator { public: // Iterator interface. using iterator_category = typename SubIterator::iterator_category; diff --git a/third_party/spirv-tools/source/opt/legalize_vector_shuffle_pass.cpp b/third_party/spirv-tools/source/opt/legalize_vector_shuffle_pass.cpp deleted file mode 100644 index b5d5d5993c..0000000000 --- a/third_party/spirv-tools/source/opt/legalize_vector_shuffle_pass.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "source/opt/legalize_vector_shuffle_pass.h" - -#include "source/opt/ir_context.h" - -namespace spvtools { -namespace opt { - -Pass::Status LegalizeVectorShufflePass::Process() { - bool changed = false; - context()->module()->ForEachInst([&changed](Instruction* inst) { - if (inst->opcode() != SpvOpVectorShuffle) return; - - for (uint32_t idx = 2; idx < inst->NumInOperands(); ++idx) { - auto literal = inst->GetSingleWordInOperand(idx); - if (literal != 0xFFFFFFFF) continue; - changed = true; - inst->SetInOperand(idx, {0}); - } - }); - - return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange; -} - -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/legalize_vector_shuffle_pass.h b/third_party/spirv-tools/source/opt/legalize_vector_shuffle_pass.h deleted file mode 100644 index ca6e1dfbe2..0000000000 --- a/third_party/spirv-tools/source/opt/legalize_vector_shuffle_pass.h +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SOURCE_OPT_LEGALIZE_VECTOR_SHUFFLE_PASS_H_ -#define SOURCE_OPT_LEGALIZE_VECTOR_SHUFFLE_PASS_H_ - -#include "source/opt/ir_context.h" -#include "source/opt/module.h" -#include "source/opt/pass.h" - -namespace spvtools { -namespace opt { - -// Converts any usages of 0xFFFFFFFF for the literals in OpVectorShuffle to a -// literal 0. This is needed because using OxFFFFFFFF is forbidden by the WebGPU -// spec. 0xFFFFFFFF in the main spec indicates that the result for this -// component has no source, thus is undefined. Since this is undefined -// behaviour we are free to use 0. -class LegalizeVectorShufflePass : public Pass { - public: - const char* name() const override { return "legalize-vector-shuffle"; } - Status Process() override; - - IRContext::Analysis GetPreservedAnalyses() override { - return IRContext::kAnalysisInstrToBlockMapping | - IRContext::kAnalysisDecorations | IRContext::kAnalysisCombinators | - IRContext::kAnalysisCFG | IRContext::kAnalysisDominatorAnalysis | - IRContext::kAnalysisLoopAnalysis | IRContext::kAnalysisNameMap | - IRContext::kAnalysisScalarEvolution | - IRContext::kAnalysisRegisterPressure | - IRContext::kAnalysisValueNumberTable | - IRContext::kAnalysisStructuredCFG | - IRContext::kAnalysisBuiltinVarId | - IRContext::kAnalysisIdToFuncMapping | IRContext::kAnalysisTypes | - IRContext::kAnalysisDefUse | IRContext::kAnalysisConstants; - } -}; - -} // namespace opt -} // namespace spvtools - -#endif // SOURCE_OPT_LEGALIZE_VECTOR_SHUFFLE_PASS_H_ diff --git a/third_party/spirv-tools/source/opt/local_access_chain_convert_pass.cpp b/third_party/spirv-tools/source/opt/local_access_chain_convert_pass.cpp index 205cd7a319..5c10ecec78 100644 --- a/third_party/spirv-tools/source/opt/local_access_chain_convert_pass.cpp +++ b/third_party/spirv-tools/source/opt/local_access_chain_convert_pass.cpp @@ -418,6 +418,8 @@ void LocalAccessChainConvertPass::InitExtensions() { "SPV_KHR_ray_query", "SPV_EXT_fragment_invocation_density", "SPV_KHR_terminate_invocation", + "SPV_KHR_subgroup_uniform_control_flow", + "SPV_KHR_integer_dot_product", }); } diff --git a/third_party/spirv-tools/source/opt/local_single_block_elim_pass.cpp b/third_party/spirv-tools/source/opt/local_single_block_elim_pass.cpp index 5f35ee1a9f..05ed28ae8a 100644 --- a/third_party/spirv-tools/source/opt/local_single_block_elim_pass.cpp +++ b/third_party/spirv-tools/source/opt/local_single_block_elim_pass.cpp @@ -270,6 +270,8 @@ void LocalSingleBlockLoadStoreElimPass::InitExtensions() { "SPV_EXT_fragment_invocation_density", "SPV_EXT_physical_storage_buffer", "SPV_KHR_terminate_invocation", + "SPV_KHR_subgroup_uniform_control_flow", + "SPV_KHR_integer_dot_product", }); } diff --git a/third_party/spirv-tools/source/opt/local_single_store_elim_pass.cpp b/third_party/spirv-tools/source/opt/local_single_store_elim_pass.cpp index 99c0fb2da8..7eb4b1fda9 100644 --- a/third_party/spirv-tools/source/opt/local_single_store_elim_pass.cpp +++ b/third_party/spirv-tools/source/opt/local_single_store_elim_pass.cpp @@ -123,6 +123,8 @@ void LocalSingleStoreElimPass::InitExtensionAllowList() { "SPV_EXT_fragment_invocation_density", "SPV_EXT_physical_storage_buffer", "SPV_KHR_terminate_invocation", + "SPV_KHR_subgroup_uniform_control_flow", + "SPV_KHR_integer_dot_product", }); } bool LocalSingleStoreElimPass::ProcessVariable(Instruction* var_inst) { @@ -174,7 +176,8 @@ bool LocalSingleStoreElimPass::RewriteDebugDeclares(Instruction* store_inst, context()->GetDominatorAnalysis(store_block->GetParent()); for (auto* decl : invisible_decls) { if (dominator_analysis->Dominates(store_inst, decl)) { - context()->get_debug_info_mgr()->AddDebugValueForDecl(decl, value_id); + context()->get_debug_info_mgr()->AddDebugValueForDecl(decl, value_id, + decl, store_inst); modified = true; } } diff --git a/third_party/spirv-tools/source/opt/loop_peeling.cpp b/third_party/spirv-tools/source/opt/loop_peeling.cpp index 071c27cb10..34f0a8d265 100644 --- a/third_party/spirv-tools/source/opt/loop_peeling.cpp +++ b/third_party/spirv-tools/source/opt/loop_peeling.cpp @@ -351,7 +351,6 @@ BasicBlock* LoopPeeling::CreateBlockBefore(BasicBlock* bb) { std::unique_ptr new_bb = MakeUnique(std::unique_ptr(new Instruction( context_, SpvOpLabel, 0, context_->TakeNextId(), {}))); - new_bb->SetParent(loop_utils_.GetFunction()); // Update the loop descriptor. Loop* in_loop = (*loop_utils_.GetLoopDescriptor())[bb]; if (in_loop) { diff --git a/third_party/spirv-tools/source/opt/loop_unroller.cpp b/third_party/spirv-tools/source/opt/loop_unroller.cpp index 6cdced4640..df68bd20ed 100644 --- a/third_party/spirv-tools/source/opt/loop_unroller.cpp +++ b/third_party/spirv-tools/source/opt/loop_unroller.cpp @@ -797,6 +797,9 @@ void LoopUnrollerUtilsImpl::CloseUnrolledLoop(Loop* loop) { for (BasicBlock* block : loop_blocks_inorder_) { RemapOperands(block); } + for (auto& block_itr : blocks_to_add_) { + RemapOperands(block_itr.get()); + } // Rewrite the last phis, since they may still reference the original phi. for (Instruction* last_phi : state_.previous_phis_) { diff --git a/third_party/spirv-tools/source/opt/mem_pass.h b/third_party/spirv-tools/source/opt/mem_pass.h index dcc16b6574..5a77670dd0 100644 --- a/third_party/spirv-tools/source/opt/mem_pass.h +++ b/third_party/spirv-tools/source/opt/mem_pass.h @@ -38,7 +38,7 @@ namespace opt { // utility functions and supporting state. class MemPass : public Pass { public: - virtual ~MemPass() = default; + virtual ~MemPass() override = default; // Returns an undef value for the given |var_id|'s type. uint32_t GetUndefVal(uint32_t var_id) { diff --git a/third_party/spirv-tools/source/opt/merge_return_pass.cpp b/third_party/spirv-tools/source/opt/merge_return_pass.cpp index b43eb3178f..f1601049e9 100644 --- a/third_party/spirv-tools/source/opt/merge_return_pass.cpp +++ b/third_party/spirv-tools/source/opt/merge_return_pass.cpp @@ -182,7 +182,8 @@ void MergeReturnPass::CreateReturnBlock() { context()->AnalyzeDefUse(final_return_block_->GetLabelInst()); context()->set_instr_block(final_return_block_->GetLabelInst(), final_return_block_); - final_return_block_->SetParent(function_); + assert(final_return_block_->GetParent() == function_ && + "The function should have been set when the block was created."); } void MergeReturnPass::CreateReturn(BasicBlock* block) { diff --git a/third_party/spirv-tools/source/opt/module.cpp b/third_party/spirv-tools/source/opt/module.cpp index 9d3b0edc6e..0c88601097 100644 --- a/third_party/spirv-tools/source/opt/module.cpp +++ b/third_party/spirv-tools/source/opt/module.cpp @@ -188,7 +188,7 @@ void Module::ToBinary(std::vector* binary, bool skip_nop) const { i->ToBinaryWithoutAttachedDebugInsts(binary); } // Update the last line instruction. - if (IsTerminatorInst(opcode) || opcode == SpvOpNoLine) { + if (spvOpcodeIsBlockTerminator(opcode) || opcode == SpvOpNoLine) { last_line_inst = nullptr; } else if (opcode == SpvOpLoopMerge || opcode == SpvOpSelectionMerge) { between_merge_and_branch = true; diff --git a/third_party/spirv-tools/source/opt/module.h b/third_party/spirv-tools/source/opt/module.h index 75da8705bd..d609b603ab 100644 --- a/third_party/spirv-tools/source/opt/module.h +++ b/third_party/spirv-tools/source/opt/module.h @@ -49,7 +49,7 @@ class Module { using const_inst_iterator = InstructionList::const_iterator; // Creates an empty module with zero'd header. - Module() : header_({}), contains_debug_scope_(false) {} + Module() : header_({}), contains_debug_info_(false) {} // Sets the header to the given |header|. void SetHeader(const ModuleHeader& header) { header_ = header; } @@ -119,9 +119,9 @@ class Module { // Appends a function to this module. inline void AddFunction(std::unique_ptr f); - // Sets |contains_debug_scope_| as true. - inline void SetContainsDebugScope(); - inline bool ContainsDebugScope() { return contains_debug_scope_; } + // Sets |contains_debug_info_| as true. + inline void SetContainsDebugInfo(); + inline bool ContainsDebugInfo() { return contains_debug_info_; } // Returns a vector of pointers to type-declaration instructions in this // module. @@ -246,12 +246,6 @@ class Module { // If |skip_nop| is true and this is a OpNop, do nothing. void ToBinary(std::vector* binary, bool skip_nop) const; - // Pushes the binary segments for this instruction into the back of *|binary| - // including all OpLine and OpNoLine even if we can skip emitting some line - // instructions. If |skip_nop| is true and this is a OpNop, do nothing. - void ToBinaryWithAllOpLines(std::vector* binary, - bool skip_nop) const; - // Returns 1 more than the maximum Id value mentioned in the module. uint32_t ComputeIdBound() const; @@ -307,8 +301,8 @@ class Module { // any instruction. We record them here, so they will not be lost. std::vector trailing_dbg_line_info_; - // This module contains DebugScope or DebugNoScope. - bool contains_debug_scope_; + // This module contains DebugScope/DebugNoScope or OpLine/OpNoLine. + bool contains_debug_info_; }; // Pretty-prints |module| to |str|. Returns |str|. @@ -370,7 +364,7 @@ inline void Module::AddFunction(std::unique_ptr f) { functions_.emplace_back(std::move(f)); } -inline void Module::SetContainsDebugScope() { contains_debug_scope_ = true; } +inline void Module::SetContainsDebugInfo() { contains_debug_info_ = true; } inline Module::inst_iterator Module::capability_begin() { return capabilities_.begin(); diff --git a/third_party/spirv-tools/source/opt/optimizer.cpp b/third_party/spirv-tools/source/opt/optimizer.cpp index 1ded2ee9b3..69103b26c9 100644 --- a/third_party/spirv-tools/source/opt/optimizer.cpp +++ b/third_party/spirv-tools/source/opt/optimizer.cpp @@ -62,7 +62,9 @@ struct Optimizer::Impl { opt::PassManager pass_manager; // Internal implementation pass manager. }; -Optimizer::Optimizer(spv_target_env env) : impl_(new Impl(env)) {} +Optimizer::Optimizer(spv_target_env env) : impl_(new Impl(env)) { + assert(env != SPV_ENV_WEBGPU_0); +} Optimizer::~Optimizer() {} @@ -153,7 +155,8 @@ Optimizer& Optimizer::RegisterLegalizationPasses() { .RegisterPass(CreateVectorDCEPass()) .RegisterPass(CreateDeadInsertElimPass()) .RegisterPass(CreateReduceLoadSizePass()) - .RegisterPass(CreateAggressiveDCEPass()); + .RegisterPass(CreateAggressiveDCEPass()) + .RegisterPass(CreateInterpolateFixupPass()); } Optimizer& Optimizer::RegisterPerformancePasses() { @@ -239,23 +242,6 @@ Optimizer& Optimizer::RegisterSizePasses() { .RegisterPass(CreateCFGCleanupPass()); } -Optimizer& Optimizer::RegisterVulkanToWebGPUPasses() { - return RegisterPass(CreateStripAtomicCounterMemoryPass()) - .RegisterPass(CreateGenerateWebGPUInitializersPass()) - .RegisterPass(CreateLegalizeVectorShufflePass()) - .RegisterPass(CreateSplitInvalidUnreachablePass()) - .RegisterPass(CreateEliminateDeadConstantPass()) - .RegisterPass(CreateFlattenDecorationPass()) - .RegisterPass(CreateAggressiveDCEPass()) - .RegisterPass(CreateDeadBranchElimPass()) - .RegisterPass(CreateCompactIdsPass()); -} - -Optimizer& Optimizer::RegisterWebGPUToVulkanPasses() { - return RegisterPass(CreateDecomposeInitializedVariablesPass()) - .RegisterPass(CreateCompactIdsPass()); -} - bool Optimizer::RegisterPassesFromFlags(const std::vector& flags) { for (const auto& flag : flags) { if (!RegisterPassFromFlag(flag)) { @@ -298,9 +284,7 @@ bool Optimizer::RegisterPassFromFlag(const std::string& flag) { // // Both Pass::name() and Pass::desc() should be static class members so they // can be invoked without creating a pass instance. - if (pass_name == "strip-atomic-counter-memory") { - RegisterPass(CreateStripAtomicCounterMemoryPass()); - } else if (pass_name == "strip-debug") { + if (pass_name == "strip-debug") { RegisterPass(CreateStripDebugInfoPass()); } else if (pass_name == "strip-reflect") { RegisterPass(CreateStripReflectInfoPass()); @@ -425,7 +409,7 @@ bool Optimizer::RegisterPassFromFlag(const std::string& flag) { RegisterPass(CreateBlockMergePass()); RegisterPass(CreateAggressiveDCEPass()); } else if (pass_name == "inst-buff-oob-check") { - RegisterPass(CreateInstBindlessCheckPass(7, 23, false, false, true)); + RegisterPass(CreateInstBindlessCheckPass(7, 23, false, false, true, true)); RegisterPass(CreateSimplificationPass()); RegisterPass(CreateDeadBranchElimPass()); RegisterPass(CreateBlockMergePass()); @@ -505,20 +489,16 @@ bool Optimizer::RegisterPassFromFlag(const std::string& flag) { RegisterSizePasses(); } else if (pass_name == "legalize-hlsl") { RegisterLegalizationPasses(); - } else if (pass_name == "generate-webgpu-initializers") { - RegisterPass(CreateGenerateWebGPUInitializersPass()); - } else if (pass_name == "legalize-vector-shuffle") { - RegisterPass(CreateLegalizeVectorShufflePass()); - } else if (pass_name == "split-invalid-unreachable") { - RegisterPass(CreateSplitInvalidUnreachablePass()); - } else if (pass_name == "decompose-initialized-variables") { - RegisterPass(CreateDecomposeInitializedVariablesPass()); + } else if (pass_name == "remove-unused-interface-variables") { + RegisterPass(CreateRemoveUnusedInterfaceVariablesPass()); } else if (pass_name == "graphics-robust-access") { RegisterPass(CreateGraphicsRobustAccessPass()); } else if (pass_name == "wrap-opkill") { RegisterPass(CreateWrapOpKillPass()); } else if (pass_name == "amd-ext-to-khr") { RegisterPass(CreateAmdExtToKhrPass()); + } else if (pass_name == "interpolate-fixup") { + RegisterPass(CreateInterpolateFixupPass()); } else { Errorf(consumer(), nullptr, {}, "Unknown flag '--%s'. Use --help for a list of valid flags", @@ -583,10 +563,12 @@ bool Optimizer::Run(const uint32_t* original_binary, #ifndef NDEBUG // We do not keep the result id of DebugScope in struct DebugScope. // Instead, we assign random ids for them, which results in integrity + // check failures. In addition, propagating the OpLine/OpNoLine to preserve + // the debug information through transformations results in integrity // check failures. We want to skip the integrity check when the module - // contains DebugScope instructions. + // contains DebugScope or OpLine/OpNoLine instructions. if (status == opt::Pass::Status::SuccessWithoutChange && - !context->module()->ContainsDebugScope()) { + !context->module()->ContainsDebugInfo()) { std::vector optimized_binary_with_nop; context->module()->ToBinary(&optimized_binary_with_nop, /* skip_nop = */ false); @@ -627,11 +609,6 @@ Optimizer::PassToken CreateNullPass() { return MakeUnique(MakeUnique()); } -Optimizer::PassToken CreateStripAtomicCounterMemoryPass() { - return MakeUnique( - MakeUnique()); -} - Optimizer::PassToken CreateStripDebugInfoPass() { return MakeUnique( MakeUnique()); @@ -754,6 +731,11 @@ Optimizer::PassToken CreateAggressiveDCEPass() { MakeUnique()); } +Optimizer::PassToken CreateRemoveUnusedInterfaceVariablesPass() { + return MakeUnique( + MakeUnique()); +} + Optimizer::PassToken CreatePropagateLineInfoPass() { return MakeUnique(MakeUnique()); } @@ -892,15 +874,14 @@ Optimizer::PassToken CreateUpgradeMemoryModelPass() { MakeUnique()); } -Optimizer::PassToken CreateInstBindlessCheckPass(uint32_t desc_set, - uint32_t shader_id, - bool input_length_enable, - bool input_init_enable, - bool input_buff_oob_enable) { +Optimizer::PassToken CreateInstBindlessCheckPass( + uint32_t desc_set, uint32_t shader_id, bool desc_length_enable, + bool desc_init_enable, bool buff_oob_enable, bool texbuff_oob_enable) { return MakeUnique( MakeUnique( - desc_set, shader_id, input_length_enable, input_init_enable, - input_buff_oob_enable)); + desc_set, shader_id, desc_length_enable, desc_init_enable, + buff_oob_enable, texbuff_oob_enable, + desc_length_enable || desc_init_enable || buff_oob_enable)); } Optimizer::PassToken CreateInstDebugPrintfPass(uint32_t desc_set, @@ -930,31 +911,11 @@ Optimizer::PassToken CreateCodeSinkingPass() { MakeUnique()); } -Optimizer::PassToken CreateGenerateWebGPUInitializersPass() { - return MakeUnique( - MakeUnique()); -} - Optimizer::PassToken CreateFixStorageClassPass() { return MakeUnique( MakeUnique()); } -Optimizer::PassToken CreateLegalizeVectorShufflePass() { - return MakeUnique( - MakeUnique()); -} - -Optimizer::PassToken CreateDecomposeInitializedVariablesPass() { - return MakeUnique( - MakeUnique()); -} - -Optimizer::PassToken CreateSplitInvalidUnreachablePass() { - return MakeUnique( - MakeUnique()); -} - Optimizer::PassToken CreateGraphicsRobustAccessPass() { return MakeUnique( MakeUnique()); @@ -974,4 +935,9 @@ Optimizer::PassToken CreateAmdExtToKhrPass() { MakeUnique()); } +Optimizer::PassToken CreateInterpolateFixupPass() { + return MakeUnique( + MakeUnique()); +} + } // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/passes.h b/third_party/spirv-tools/source/opt/passes.h index d47cc1cee2..aeae44494d 100644 --- a/third_party/spirv-tools/source/opt/passes.h +++ b/third_party/spirv-tools/source/opt/passes.h @@ -30,7 +30,6 @@ #include "source/opt/dead_branch_elim_pass.h" #include "source/opt/dead_insert_elim_pass.h" #include "source/opt/dead_variable_elimination.h" -#include "source/opt/decompose_initialized_variables_pass.h" #include "source/opt/desc_sroa.h" #include "source/opt/eliminate_dead_constant_pass.h" #include "source/opt/eliminate_dead_functions_pass.h" @@ -40,7 +39,6 @@ #include "source/opt/flatten_decoration_pass.h" #include "source/opt/fold_spec_constant_op_and_composite_pass.h" #include "source/opt/freeze_spec_constant_value_pass.h" -#include "source/opt/generate_webgpu_initializers_pass.h" #include "source/opt/graphics_robust_access_pass.h" #include "source/opt/if_conversion.h" #include "source/opt/inline_exhaustive_pass.h" @@ -48,7 +46,7 @@ #include "source/opt/inst_bindless_check_pass.h" #include "source/opt/inst_buff_addr_check_pass.h" #include "source/opt/inst_debug_printf_pass.h" -#include "source/opt/legalize_vector_shuffle_pass.h" +#include "source/opt/interp_fixup_pass.h" #include "source/opt/licm_pass.h" #include "source/opt/local_access_chain_convert_pass.h" #include "source/opt/local_redundancy_elimination.h" @@ -66,14 +64,13 @@ #include "source/opt/redundancy_elimination.h" #include "source/opt/relax_float_ops_pass.h" #include "source/opt/remove_duplicates_pass.h" +#include "source/opt/remove_unused_interface_variables_pass.h" #include "source/opt/replace_invalid_opc.h" #include "source/opt/scalar_replacement_pass.h" #include "source/opt/set_spec_constant_default_value_pass.h" #include "source/opt/simplification_pass.h" -#include "source/opt/split_invalid_unreachable_pass.h" #include "source/opt/ssa_rewrite_pass.h" #include "source/opt/strength_reduction_pass.h" -#include "source/opt/strip_atomic_counter_memory_pass.h" #include "source/opt/strip_debug_info_pass.h" #include "source/opt/strip_reflect_info_pass.h" #include "source/opt/unify_const_pass.h" diff --git a/third_party/spirv-tools/source/opt/reflect.h b/third_party/spirv-tools/source/opt/reflect.h index 2e253add34..c7d46df548 100644 --- a/third_party/spirv-tools/source/opt/reflect.h +++ b/third_party/spirv-tools/source/opt/reflect.h @@ -47,7 +47,7 @@ inline bool IsTypeInst(SpvOp opcode) { opcode == SpvOpTypePipeStorage || opcode == SpvOpTypeNamedBarrier || opcode == SpvOpTypeAccelerationStructureNV || opcode == SpvOpTypeAccelerationStructureKHR || - opcode == SpvOpTypeRayQueryProvisionalKHR || + opcode == SpvOpTypeRayQueryKHR || opcode == SpvOpTypeCooperativeMatrixNV; } inline bool IsConstantInst(SpvOp opcode) { @@ -59,10 +59,6 @@ inline bool IsCompileTimeConstantInst(SpvOp opcode) { inline bool IsSpecConstantInst(SpvOp opcode) { return opcode >= SpvOpSpecConstantTrue && opcode <= SpvOpSpecConstantOp; } -inline bool IsTerminatorInst(SpvOp opcode) { - return (opcode >= SpvOpBranch && opcode <= SpvOpUnreachable) || - (opcode == SpvOpTerminateInvocation); -} } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/remove_unused_interface_variables_pass.cpp b/third_party/spirv-tools/source/opt/remove_unused_interface_variables_pass.cpp new file mode 100644 index 0000000000..31e87bd4b1 --- /dev/null +++ b/third_party/spirv-tools/source/opt/remove_unused_interface_variables_pass.cpp @@ -0,0 +1,93 @@ +// Copyright (c) 2021 ZHOU He +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "remove_unused_interface_variables_pass.h" +#include "source/spirv_constant.h" +namespace spvtools { +namespace opt { + +class RemoveUnusedInterfaceVariablesContext { + RemoveUnusedInterfaceVariablesPass& parent_; + Instruction& entry_; + std::unordered_set used_variables_; + IRContext::ProcessFunction pfn_ = + std::bind(&RemoveUnusedInterfaceVariablesContext::processFunction, this, + std::placeholders::_1); + + bool processFunction(Function* func) { + for (const auto& basic_block : *func) + for (const auto& instruction : basic_block) + instruction.ForEachInId([&](const uint32_t* id) { + if (used_variables_.count(*id)) return; + auto* var = parent_.get_def_use_mgr()->GetDef(*id); + if (!var || var->opcode() != SpvOpVariable) return; + auto storage_class = var->GetSingleWordInOperand(0); + if (storage_class != SpvStorageClassFunction && + (parent_.get_module()->version() >= + SPV_SPIRV_VERSION_WORD(1, 4) || + storage_class == SpvStorageClassInput || + storage_class == SpvStorageClassOutput)) + used_variables_.insert(*id); + }); + return false; + } + + public: + RemoveUnusedInterfaceVariablesContext( + RemoveUnusedInterfaceVariablesPass& parent, Instruction& entry) + : parent_(parent), entry_(entry) {} + + void CollectUsedVariables() { + std::queue roots; + roots.push(entry_.GetSingleWordInOperand(1)); + parent_.context()->ProcessCallTreeFromRoots(pfn_, &roots); + } + + bool ShouldModify() { + std::unordered_set old_variables; + for (int i = entry_.NumInOperands() - 1; i >= 3; --i) { + auto variable = entry_.GetInOperand(i).words[0]; + if (!used_variables_.count(variable)) return true; // It is unused. + if (old_variables.count(variable)) return true; // It is duplicate. + old_variables.insert(variable); + } + if (old_variables.size() != used_variables_.size()) // Missing IDs. + return true; + return false; + } + + void Modify() { + for (int i = entry_.NumInOperands() - 1; i >= 3; --i) + entry_.RemoveInOperand(i); + for (auto id : used_variables_) { + entry_.AddOperand(Operand(SPV_OPERAND_TYPE_ID, {id})); + } + } +}; + +RemoveUnusedInterfaceVariablesPass::Status +RemoveUnusedInterfaceVariablesPass::Process() { + bool modified = false; + for (auto& entry : get_module()->entry_points()) { + RemoveUnusedInterfaceVariablesContext context(*this, entry); + context.CollectUsedVariables(); + if (context.ShouldModify()) { + context.Modify(); + modified = true; + } + } + return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange); +} +} // namespace opt +} // namespace spvtools \ No newline at end of file diff --git a/third_party/spirv-tools/source/opt/remove_unused_interface_variables_pass.h b/third_party/spirv-tools/source/opt/remove_unused_interface_variables_pass.h new file mode 100644 index 0000000000..7f11187cac --- /dev/null +++ b/third_party/spirv-tools/source/opt/remove_unused_interface_variables_pass.h @@ -0,0 +1,26 @@ +// Copyright (c) 2021 ZHOU He +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/opt/pass.h" +namespace spvtools { +namespace opt { + +class RemoveUnusedInterfaceVariablesPass : public Pass { + const char* name() const override { + return "remove-unused-interface-variables-pass"; + } + Status Process() override; +}; +} // namespace opt +} // namespace spvtools \ No newline at end of file diff --git a/third_party/spirv-tools/source/opt/scalar_replacement_pass.cpp b/third_party/spirv-tools/source/opt/scalar_replacement_pass.cpp index d71d605bfd..4d47bdd8df 100644 --- a/third_party/spirv-tools/source/opt/scalar_replacement_pass.cpp +++ b/third_party/spirv-tools/source/opt/scalar_replacement_pass.cpp @@ -25,7 +25,6 @@ #include "source/opt/types.h" #include "source/util/make_unique.h" -static const uint32_t kDebugDeclareOperandLocalVariableIndex = 4; static const uint32_t kDebugValueOperandValueIndex = 5; static const uint32_t kDebugValueOperandExpressionIndex = 6; @@ -173,17 +172,20 @@ bool ScalarReplacementPass::ReplaceWholeDebugDeclare( // Add DebugValue instruction with Indexes operand and Deref operation. int32_t idx = 0; for (const auto* var : replacements) { - uint32_t dbg_local_variable = - dbg_decl->GetSingleWordOperand(kDebugDeclareOperandLocalVariableIndex); - uint32_t index_id = context()->get_constant_mgr()->GetSIntConst(idx); - Instruction* added_dbg_value = - context()->get_debug_info_mgr()->AddDebugValueWithIndex( - dbg_local_variable, - /*value_id=*/var->result_id(), /*expr_id=*/deref_expr->result_id(), - index_id, /*insert_before=*/var->NextNode()); + context()->get_debug_info_mgr()->AddDebugValueForDecl( + dbg_decl, /*value_id=*/var->result_id(), + /*insert_before=*/var->NextNode(), /*scope_and_line=*/dbg_decl); + if (added_dbg_value == nullptr) return false; - added_dbg_value->UpdateDebugInfoFrom(dbg_decl); + added_dbg_value->AddOperand( + {SPV_OPERAND_TYPE_ID, + {context()->get_constant_mgr()->GetSIntConst(idx)}}); + added_dbg_value->SetOperand(kDebugValueOperandExpressionIndex, + {deref_expr->result_id()}); + if (context()->AreAnalysesValid(IRContext::Analysis::kAnalysisDefUse)) { + context()->get_def_use_mgr()->AnalyzeInstUse(added_dbg_value); + } ++idx; } return true; @@ -859,6 +861,9 @@ bool ScalarReplacementPass::CheckUsesRelaxed(const Instruction* inst) const { case SpvOpStore: if (!CheckStore(user, index)) ok = false; break; + case SpvOpImageTexelPointer: + if (!CheckImageTexelPointer(index)) ok = false; + break; default: ok = false; break; @@ -868,6 +873,10 @@ bool ScalarReplacementPass::CheckUsesRelaxed(const Instruction* inst) const { return ok; } +bool ScalarReplacementPass::CheckImageTexelPointer(uint32_t index) const { + return index == 2u; +} + bool ScalarReplacementPass::CheckLoad(const Instruction* inst, uint32_t index) const { if (index != 2u) return false; diff --git a/third_party/spirv-tools/source/opt/scalar_replacement_pass.h b/third_party/spirv-tools/source/opt/scalar_replacement_pass.h index 1f6c928132..9e9f073948 100644 --- a/third_party/spirv-tools/source/opt/scalar_replacement_pass.h +++ b/third_party/spirv-tools/source/opt/scalar_replacement_pass.h @@ -142,6 +142,10 @@ class ScalarReplacementPass : public Pass { // of |inst| and the store is not to volatile memory. bool CheckStore(const Instruction* inst, uint32_t index) const; + // Returns true if |index| is the pointer operand of an OpImageTexelPointer + // instruction. + bool CheckImageTexelPointer(uint32_t index) const; + // Creates a variable of type |typeId| from the |index|'th element of // |varInst|. The new variable is added to |replacements|. If the variable // could not be created, then |nullptr| is appended to |replacements|. diff --git a/third_party/spirv-tools/source/opt/split_invalid_unreachable_pass.cpp b/third_party/spirv-tools/source/opt/split_invalid_unreachable_pass.cpp deleted file mode 100644 index 31cfbc330b..0000000000 --- a/third_party/spirv-tools/source/opt/split_invalid_unreachable_pass.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "source/opt/split_invalid_unreachable_pass.h" - -#include "source/opt/ir_builder.h" -#include "source/opt/ir_context.h" - -namespace spvtools { -namespace opt { - -Pass::Status SplitInvalidUnreachablePass::Process() { - bool changed = false; - std::unordered_set entry_points; - for (auto entry_point : context()->module()->entry_points()) { - entry_points.insert(entry_point.GetSingleWordOperand(1)); - } - - for (auto func = context()->module()->begin(); - func != context()->module()->end(); ++func) { - if (entry_points.find(func->result_id()) == entry_points.end()) continue; - std::unordered_set continue_targets; - std::unordered_set merge_blocks; - std::unordered_set unreachable_blocks; - for (auto block = func->begin(); block != func->end(); ++block) { - unreachable_blocks.insert(&*block); - uint32_t continue_target = block->ContinueBlockIdIfAny(); - if (continue_target != 0) continue_targets.insert(continue_target); - uint32_t merge_block = block->MergeBlockIdIfAny(); - if (merge_block != 0) merge_blocks.insert(merge_block); - } - - cfg()->ForEachBlockInPostOrder( - func->entry().get(), [&unreachable_blocks](BasicBlock* inner_block) { - unreachable_blocks.erase(inner_block); - }); - - for (auto unreachable : unreachable_blocks) { - uint32_t block_id = unreachable->id(); - if (continue_targets.find(block_id) == continue_targets.end() || - merge_blocks.find(block_id) == merge_blocks.end()) { - continue; - } - - std::vector> usages; - context()->get_def_use_mgr()->ForEachUse( - unreachable->GetLabelInst(), - [&usages](Instruction* use, uint32_t idx) { - if ((use->opcode() == SpvOpLoopMerge && idx == 0) || - use->opcode() == SpvOpSelectionMerge) { - usages.push_back(std::make_pair(use, idx)); - } - }); - - for (auto usage : usages) { - Instruction* use; - uint32_t idx; - std::tie(use, idx) = usage; - uint32_t new_id = context()->TakeNextId(); - std::unique_ptr new_label( - new Instruction(context(), SpvOpLabel, 0, new_id, {})); - get_def_use_mgr()->AnalyzeInstDefUse(new_label.get()); - std::unique_ptr new_block( - new BasicBlock(std::move(new_label))); - auto* block_ptr = new_block.get(); - InstructionBuilder builder(context(), new_block.get(), - IRContext::kAnalysisDefUse | - IRContext::kAnalysisInstrToBlockMapping); - builder.AddUnreachable(); - cfg()->RegisterBlock(block_ptr); - (&*func)->InsertBasicBlockBefore(std::move(new_block), unreachable); - use->SetInOperand(0, {new_id}); - get_def_use_mgr()->UpdateDefUse(use); - cfg()->AddEdges(block_ptr); - changed = true; - } - } - } - - return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange; -} - -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/split_invalid_unreachable_pass.h b/third_party/spirv-tools/source/opt/split_invalid_unreachable_pass.h deleted file mode 100644 index a5613448e7..0000000000 --- a/third_party/spirv-tools/source/opt/split_invalid_unreachable_pass.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef SOURCE_OPT_SPLIT_INVALID_UNREACHABLE_PASS_H_ -#define SOURCE_OPT_SPLIT_INVALID_UNREACHABLE_PASS_H_ - -#include "source/opt/ir_context.h" -#include "source/opt/module.h" -#include "source/opt/pass.h" - -namespace spvtools { -namespace opt { - -// Attempts to legalize for WebGPU by splitting up invalid unreachable blocks. -// Specifically, looking for cases of unreachable merge-blocks and -// continue-targets that are used more then once, which is illegal in WebGPU. -class SplitInvalidUnreachablePass : public Pass { - public: - const char* name() const override { return "split-invalid-unreachable"; } - Status Process() override; - - IRContext::Analysis GetPreservedAnalyses() override { - return IRContext::kAnalysisInstrToBlockMapping | - IRContext::kAnalysisDecorations | IRContext::kAnalysisCombinators | - IRContext::kAnalysisCFG | IRContext::kAnalysisDominatorAnalysis | - IRContext::kAnalysisLoopAnalysis | IRContext::kAnalysisNameMap | - IRContext::kAnalysisScalarEvolution | - IRContext::kAnalysisRegisterPressure | - IRContext::kAnalysisValueNumberTable | - IRContext::kAnalysisStructuredCFG | - IRContext::kAnalysisBuiltinVarId | - IRContext::kAnalysisIdToFuncMapping | IRContext::kAnalysisTypes | - IRContext::kAnalysisDefUse | IRContext::kAnalysisConstants; - } -}; - -} // namespace opt -} // namespace spvtools - -#endif // SOURCE_OPT_SPLIT_INVALID_UNREACHABLE_PASS_H_ diff --git a/third_party/spirv-tools/source/opt/ssa_rewrite_pass.cpp b/third_party/spirv-tools/source/opt/ssa_rewrite_pass.cpp index 3ff0361900..81770d779f 100644 --- a/third_party/spirv-tools/source/opt/ssa_rewrite_pass.cpp +++ b/third_party/spirv-tools/source/opt/ssa_rewrite_pass.cpp @@ -658,8 +658,8 @@ Pass::Status SSARewriter::AddDebugValuesForInvisibleDebugDecls(Function* fp) { // a = 3; // foo(3); // After inlining: - // a = 3; // we want to specify "DebugValue: %x = %int_3" - // foo and x disappeared! + // a = 3; + // foo and x disappeared but we want to specify "DebugValue: %x = %int_3". // // We want to specify the value for the variable using |defs_at_block_[bb]|, // where |bb| is the basic block contains the decl. @@ -680,17 +680,18 @@ Pass::Status SSARewriter::AddDebugValuesForInvisibleDebugDecls(Function* fp) { // If |value| dominates |decl|, we can set it as DebugValue. if (value && (pass_->context()->get_instr_block(value) == nullptr || dom_tree->Dominates(value, decl))) { - if (!pass_->context()->get_debug_info_mgr()->AddDebugValueForDecl( - decl, value->result_id())) { + if (pass_->context()->get_debug_info_mgr()->AddDebugValueForDecl( + decl, value->result_id(), decl, value) == nullptr) { return Pass::Status::Failure; } } else { // If |value| in the same basic block does not dominate |decl|, we can // assign the value in the immediate dominator. value_id = GetValueAtBlock(var_id, dom_tree->ImmediateDominator(bb)); + if (value_id) value = pass_->get_def_use_mgr()->GetDef(value_id); if (value_id && - !pass_->context()->get_debug_info_mgr()->AddDebugValueForDecl( - decl, value_id)) { + pass_->context()->get_debug_info_mgr()->AddDebugValueForDecl( + decl, value_id, decl, value) == nullptr) { return Pass::Status::Failure; } } diff --git a/third_party/spirv-tools/source/opt/strip_atomic_counter_memory_pass.cpp b/third_party/spirv-tools/source/opt/strip_atomic_counter_memory_pass.cpp deleted file mode 100644 index 47714b7469..0000000000 --- a/third_party/spirv-tools/source/opt/strip_atomic_counter_memory_pass.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "source/opt/strip_atomic_counter_memory_pass.h" -#include "source/opt/ir_context.h" - -namespace spvtools { -namespace opt { - -Pass::Status StripAtomicCounterMemoryPass::Process() { - bool changed = false; - context()->module()->ForEachInst([this, &changed](Instruction* inst) { - auto indices = spvOpcodeMemorySemanticsOperandIndices(inst->opcode()); - if (indices.empty()) return; - - for (auto idx : indices) { - auto mem_sem_id = inst->GetSingleWordOperand(idx); - const auto& mem_sem_inst = - context()->get_def_use_mgr()->GetDef(mem_sem_id); - // The spec explicitly says that this id must be an OpConstant - auto mem_sem_val = mem_sem_inst->GetSingleWordOperand(2); - if (!(mem_sem_val & SpvMemorySemanticsAtomicCounterMemoryMask)) { - continue; - } - mem_sem_val &= ~SpvMemorySemanticsAtomicCounterMemoryMask; - - analysis::Integer int_type(32, false); - const analysis::Type* uint32_type = - context()->get_type_mgr()->GetRegisteredType(&int_type); - auto* new_const = context()->get_constant_mgr()->GetConstant( - uint32_type, {mem_sem_val}); - auto* new_const_inst = - context()->get_constant_mgr()->GetDefiningInstruction(new_const); - auto new_const_id = new_const_inst->result_id(); - - inst->SetOperand(idx, {new_const_id}); - context()->UpdateDefUse(inst); - changed = true; - } - }); - - return changed ? Status::SuccessWithChange : Status::SuccessWithoutChange; -} - -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/source/opt/type_manager.cpp b/third_party/spirv-tools/source/opt/type_manager.cpp index 27c7199452..7935ad3313 100644 --- a/third_party/spirv-tools/source/opt/type_manager.cpp +++ b/third_party/spirv-tools/source/opt/type_manager.cpp @@ -223,7 +223,7 @@ uint32_t TypeManager::GetTypeInstruction(const Type* type) { case Type::k##kind: \ typeInst = MakeUnique(context(), SpvOpType##kind, 0, id, \ std::initializer_list{}); \ - break; + break DefineParameterlessCase(Void); DefineParameterlessCase(Bool); DefineParameterlessCase(Sampler); @@ -513,7 +513,7 @@ Type* TypeManager::RebuildType(const Type& type) { #define DefineNoSubtypeCase(kind) \ case Type::k##kind: \ rebuilt_ty.reset(type.Clone().release()); \ - return type_pool_.insert(std::move(rebuilt_ty)).first->get(); + return type_pool_.insert(std::move(rebuilt_ty)).first->get() DefineNoSubtypeCase(Void); DefineNoSubtypeCase(Bool); @@ -862,8 +862,8 @@ Type* TypeManager::RecordIfTypeDefinition(const Instruction& inst) { inst.GetSingleWordInOperand(2), inst.GetSingleWordInOperand(3)); break; - case SpvOpTypeRayQueryProvisionalKHR: - type = new RayQueryProvisionalKHR(); + case SpvOpTypeRayQueryKHR: + type = new RayQueryKHR(); break; default: SPIRV_UNIMPLEMENTED(consumer_, "unhandled type"); diff --git a/third_party/spirv-tools/source/opt/types.cpp b/third_party/spirv-tools/source/opt/types.cpp index 426d3ea445..b1eb3a5084 100644 --- a/third_party/spirv-tools/source/opt/types.cpp +++ b/third_party/spirv-tools/source/opt/types.cpp @@ -128,7 +128,7 @@ std::unique_ptr Type::Clone() const { DeclareKindCase(NamedBarrier); DeclareKindCase(AccelerationStructureNV); DeclareKindCase(CooperativeMatrixNV); - DeclareKindCase(RayQueryProvisionalKHR); + DeclareKindCase(RayQueryKHR); #undef DeclareKindCase default: assert(false && "Unhandled type"); @@ -174,7 +174,7 @@ bool Type::operator==(const Type& other) const { DeclareKindCase(NamedBarrier); DeclareKindCase(AccelerationStructureNV); DeclareKindCase(CooperativeMatrixNV); - DeclareKindCase(RayQueryProvisionalKHR); + DeclareKindCase(RayQueryKHR); #undef DeclareKindCase default: assert(false && "Unhandled type"); @@ -225,7 +225,7 @@ void Type::GetHashWords(std::vector* words, DeclareKindCase(NamedBarrier); DeclareKindCase(AccelerationStructureNV); DeclareKindCase(CooperativeMatrixNV); - DeclareKindCase(RayQueryProvisionalKHR); + DeclareKindCase(RayQueryKHR); #undef DeclareKindCase default: assert(false && "Unhandled type"); diff --git a/third_party/spirv-tools/source/opt/types.h b/third_party/spirv-tools/source/opt/types.h index ebeb476039..9ecd41a6b0 100644 --- a/third_party/spirv-tools/source/opt/types.h +++ b/third_party/spirv-tools/source/opt/types.h @@ -59,7 +59,7 @@ class PipeStorage; class NamedBarrier; class AccelerationStructureNV; class CooperativeMatrixNV; -class RayQueryProvisionalKHR; +class RayQueryKHR; // Abstract class for a SPIR-V type. It has a bunch of As() methods, // which is used as a way to probe the actual . @@ -96,12 +96,12 @@ class Type { kNamedBarrier, kAccelerationStructureNV, kCooperativeMatrixNV, - kRayQueryProvisionalKHR + kRayQueryKHR }; Type(Kind k) : kind_(k) {} - virtual ~Type() {} + virtual ~Type() = default; // Attaches a decoration directly on this type. void AddDecoration(std::vector&& d) { @@ -201,7 +201,7 @@ class Type { DeclareCastMethod(NamedBarrier) DeclareCastMethod(AccelerationStructureNV) DeclareCastMethod(CooperativeMatrixNV) - DeclareCastMethod(RayQueryProvisionalKHR) + DeclareCastMethod(RayQueryKHR) #undef DeclareCastMethod protected: @@ -662,7 +662,7 @@ DefineParameterlessType(Queue, queue); DefineParameterlessType(PipeStorage, pipe_storage); DefineParameterlessType(NamedBarrier, named_barrier); DefineParameterlessType(AccelerationStructureNV, accelerationStructureNV); -DefineParameterlessType(RayQueryProvisionalKHR, rayQueryProvisionalKHR); +DefineParameterlessType(RayQueryKHR, rayQueryKHR); #undef DefineParameterlessType } // namespace analysis diff --git a/third_party/spirv-tools/source/opt/wrap_opkill.cpp b/third_party/spirv-tools/source/opt/wrap_opkill.cpp index ae1000c7fb..51432a73b2 100644 --- a/third_party/spirv-tools/source/opt/wrap_opkill.cpp +++ b/third_party/spirv-tools/source/opt/wrap_opkill.cpp @@ -164,7 +164,6 @@ uint32_t WrapOpKill::GetKillingFuncId(SpvOp opcode) { bb->AddInstruction(std::move(kill_inst)); // Add the bb to the function - bb->SetParent((*killing_func).get()); (*killing_func)->AddBasicBlock(std::move(bb)); // Add the function to the module. diff --git a/third_party/spirv-tools/source/print.cpp b/third_party/spirv-tools/source/print.cpp index 128587ae2d..2418c5bc91 100644 --- a/third_party/spirv-tools/source/print.cpp +++ b/third_party/spirv-tools/source/print.cpp @@ -15,7 +15,7 @@ #include "source/print.h" #if defined(SPIRV_ANDROID) || defined(SPIRV_LINUX) || defined(SPIRV_MAC) || \ - defined(SPIRV_IOS) || defined(SPIRV_FREEBSD) || \ + defined(SPIRV_IOS) || defined(SPIRV_TVOS) || defined(SPIRV_FREEBSD) || \ defined(SPIRV_EMSCRIPTEN) || defined(SPIRV_FUCHSIA) namespace spvtools { diff --git a/third_party/spirv-tools/source/reduce/CMakeLists.txt b/third_party/spirv-tools/source/reduce/CMakeLists.txt index a3291c77b2..6fd8409f69 100644 --- a/third_party/spirv-tools/source/reduce/CMakeLists.txt +++ b/third_party/spirv-tools/source/reduce/CMakeLists.txt @@ -14,6 +14,8 @@ set(SPIRV_TOOLS_REDUCE_SOURCES change_operand_reduction_opportunity.h change_operand_to_undef_reduction_opportunity.h + conditional_branch_to_simple_conditional_branch_opportunity_finder.h + conditional_branch_to_simple_conditional_branch_reduction_opportunity.h merge_blocks_reduction_opportunity.h merge_blocks_reduction_opportunity_finder.h operand_to_const_reduction_opportunity_finder.h @@ -34,15 +36,17 @@ set(SPIRV_TOOLS_REDUCE_SOURCES remove_struct_member_reduction_opportunity.h remove_unused_instruction_reduction_opportunity_finder.h remove_unused_struct_member_reduction_opportunity_finder.h - structured_loop_to_selection_reduction_opportunity.h - structured_loop_to_selection_reduction_opportunity_finder.h - conditional_branch_to_simple_conditional_branch_opportunity_finder.h - conditional_branch_to_simple_conditional_branch_reduction_opportunity.h simple_conditional_branch_to_branch_opportunity_finder.h simple_conditional_branch_to_branch_reduction_opportunity.h + structured_construct_to_block_reduction_opportunity.h + structured_construct_to_block_reduction_opportunity_finder.h + structured_loop_to_selection_reduction_opportunity.h + structured_loop_to_selection_reduction_opportunity_finder.h change_operand_reduction_opportunity.cpp change_operand_to_undef_reduction_opportunity.cpp + conditional_branch_to_simple_conditional_branch_opportunity_finder.cpp + conditional_branch_to_simple_conditional_branch_reduction_opportunity.cpp merge_blocks_reduction_opportunity.cpp merge_blocks_reduction_opportunity_finder.cpp operand_to_const_reduction_opportunity_finder.cpp @@ -63,12 +67,12 @@ set(SPIRV_TOOLS_REDUCE_SOURCES remove_struct_member_reduction_opportunity.cpp remove_unused_instruction_reduction_opportunity_finder.cpp remove_unused_struct_member_reduction_opportunity_finder.cpp - structured_loop_to_selection_reduction_opportunity.cpp - structured_loop_to_selection_reduction_opportunity_finder.cpp - conditional_branch_to_simple_conditional_branch_opportunity_finder.cpp - conditional_branch_to_simple_conditional_branch_reduction_opportunity.cpp simple_conditional_branch_to_branch_opportunity_finder.cpp simple_conditional_branch_to_branch_reduction_opportunity.cpp + structured_construct_to_block_reduction_opportunity.cpp + structured_construct_to_block_reduction_opportunity_finder.cpp + structured_loop_to_selection_reduction_opportunity.cpp + structured_loop_to_selection_reduction_opportunity_finder.cpp ) if(MSVC AND (NOT ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang"))) diff --git a/third_party/spirv-tools/source/reduce/change_operand_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/change_operand_reduction_opportunity.cpp index c3f6fd7ba1..18e340bfbf 100644 --- a/third_party/spirv-tools/source/reduce/change_operand_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/change_operand_reduction_opportunity.cpp @@ -14,6 +14,8 @@ #include "source/reduce/change_operand_reduction_opportunity.h" +#include "source/opt/ir_context.h" + namespace spvtools { namespace reduce { @@ -26,6 +28,7 @@ bool ChangeOperandReductionOpportunity::PreconditionHolds() { void ChangeOperandReductionOpportunity::Apply() { inst_->SetOperand(operand_index_, {new_id_}); + inst_->context()->get_def_use_mgr()->UpdateDefUse(inst_); } } // namespace reduce diff --git a/third_party/spirv-tools/source/reduce/change_operand_to_undef_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/change_operand_to_undef_reduction_opportunity.cpp index 8e33da661e..7cc06a0375 100644 --- a/third_party/spirv-tools/source/reduce/change_operand_to_undef_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/change_operand_to_undef_reduction_opportunity.cpp @@ -35,6 +35,7 @@ void ChangeOperandToUndefReductionOpportunity::Apply() { assert(operand_type_id); auto undef_id = FindOrCreateGlobalUndef(context_, operand_type_id); inst_->SetOperand(operand_index_, {undef_id}); + context_->InvalidateAnalyses(opt::IRContext::kAnalysisDefUse); } } // namespace reduce diff --git a/third_party/spirv-tools/source/reduce/reducer.cpp b/third_party/spirv-tools/source/reduce/reducer.cpp index 18eeaeb663..b752f4152a 100644 --- a/third_party/spirv-tools/source/reduce/reducer.cpp +++ b/third_party/spirv-tools/source/reduce/reducer.cpp @@ -28,6 +28,7 @@ #include "source/reduce/remove_unused_instruction_reduction_opportunity_finder.h" #include "source/reduce/remove_unused_struct_member_reduction_opportunity_finder.h" #include "source/reduce/simple_conditional_branch_to_branch_opportunity_finder.h" +#include "source/reduce/structured_construct_to_block_reduction_opportunity_finder.h" #include "source/reduce/structured_loop_to_selection_reduction_opportunity_finder.h" #include "source/spirv_reducer_options.h" @@ -54,10 +55,10 @@ void Reducer::SetInterestingnessFunction( } Reducer::ReductionResultStatus Reducer::Run( - std::vector&& binary_in, std::vector* binary_out, + const std::vector& binary_in, std::vector* binary_out, spv_const_reducer_options options, spv_validator_options validator_options) { - std::vector current_binary(std::move(binary_in)); + std::vector current_binary(binary_in); spvtools::SpirvTools tools(target_env_); assert(tools.IsValid() && "Failed to create SPIRV-Tools interface"); @@ -112,6 +113,8 @@ void Reducer::AddDefaultReductionPasses() { spvtools::MakeUnique()); AddReductionPass( spvtools::MakeUnique()); + AddReductionPass(spvtools::MakeUnique< + StructuredConstructToBlockReductionOpportunityFinder>()); AddReductionPass(spvtools::MakeUnique< StructuredLoopToSelectionReductionOpportunityFinder>()); AddReductionPass( @@ -138,13 +141,13 @@ void Reducer::AddDefaultReductionPasses() { } void Reducer::AddReductionPass( - std::unique_ptr&& finder) { + std::unique_ptr finder) { passes_.push_back( spvtools::MakeUnique(target_env_, std::move(finder))); } void Reducer::AddCleanupReductionPass( - std::unique_ptr&& finder) { + std::unique_ptr finder) { cleanup_passes_.push_back( spvtools::MakeUnique(target_env_, std::move(finder))); } diff --git a/third_party/spirv-tools/source/reduce/reducer.h b/third_party/spirv-tools/source/reduce/reducer.h index 864ce75709..f3ba180668 100644 --- a/third_party/spirv-tools/source/reduce/reducer.h +++ b/third_party/spirv-tools/source/reduce/reducer.h @@ -84,17 +84,17 @@ class Reducer { // Adds a reduction pass based on the given finder to the sequence of passes // that will be iterated over. - void AddReductionPass(std::unique_ptr&& finder); + void AddReductionPass(std::unique_ptr finder); // Adds a cleanup reduction pass based on the given finder to the sequence of // passes that will run after other passes. void AddCleanupReductionPass( - std::unique_ptr&& finder); + std::unique_ptr finder); // Reduces the given SPIR-V module |binary_out|. // The reduced binary ends up in |binary_out|. // A status is returned. - ReductionResultStatus Run(std::vector&& binary_in, + ReductionResultStatus Run(const std::vector& binary_in, std::vector* binary_out, spv_const_reducer_options options, spv_validator_options validator_options); diff --git a/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.cpp index aa48105937..55e9576943 100644 --- a/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.cpp @@ -20,12 +20,11 @@ namespace spvtools { namespace reduce { RemoveBlockReductionOpportunity::RemoveBlockReductionOpportunity( - opt::Function* function, opt::BasicBlock* block) - : function_(function), block_(block) { + opt::IRContext* context, opt::Function* function, opt::BasicBlock* block) + : context_(context), function_(function), block_(block) { // precondition: assert(block_->begin() != block_->end() && - block_->begin()->context()->get_def_use_mgr()->NumUsers( - block_->id()) == 0 && + context_->get_def_use_mgr()->NumUsers(block_->id()) == 0 && "RemoveBlockReductionOpportunity block must have 0 references"); } @@ -38,10 +37,8 @@ void RemoveBlockReductionOpportunity::Apply() { // We need an iterator pointing to the block, hence the loop. for (auto bi = function_->begin(); bi != function_->end(); ++bi) { if (bi->id() == block_->id()) { - bi->KillAllInsts(true); bi.Erase(); - // Block removal changes the function, but we don't use analyses, so no - // need to invalidate them. + context_->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); return; } } diff --git a/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.h b/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.h index 4b358abc63..03fede529b 100644 --- a/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.h +++ b/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity.h @@ -27,7 +27,8 @@ namespace reduce { class RemoveBlockReductionOpportunity : public ReductionOpportunity { public: // Creates the opportunity to remove |block| in |function| in |context|. - RemoveBlockReductionOpportunity(opt::Function* function, + RemoveBlockReductionOpportunity(opt::IRContext* context, + opt::Function* function, opt::BasicBlock* block); bool PreconditionHolds() override; @@ -36,6 +37,7 @@ class RemoveBlockReductionOpportunity : public ReductionOpportunity { void Apply() override; private: + opt::IRContext* context_; opt::Function* function_; opt::BasicBlock* block_; }; diff --git a/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity_finder.cpp b/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity_finder.cpp index 27a4570c1e..3b13728ab4 100644 --- a/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity_finder.cpp +++ b/third_party/spirv-tools/source/reduce/remove_block_reduction_opportunity_finder.cpp @@ -32,8 +32,8 @@ RemoveBlockReductionOpportunityFinder::GetAvailableOpportunities( for (auto* function : GetTargetFunctions(context, target_function)) { for (auto bi = function->begin(); bi != function->end(); ++bi) { if (IsBlockValidOpportunity(context, function, &bi)) { - result.push_back( - MakeUnique(function, &*bi)); + result.push_back(MakeUnique( + context, function, &*bi)); } } } diff --git a/third_party/spirv-tools/source/reduce/remove_function_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/remove_function_reduction_opportunity.cpp index ecad670779..4b85058b37 100644 --- a/third_party/spirv-tools/source/reduce/remove_function_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/remove_function_reduction_opportunity.cpp @@ -29,8 +29,8 @@ void RemoveFunctionReductionOpportunity::Apply() { for (opt::Module::iterator function_it = context_->module()->begin(); function_it != context_->module()->end(); ++function_it) { if (&*function_it == function_) { - opt::eliminatedeadfunctionsutil::EliminateFunction(context_, - &function_it); + function_it.Erase(); + context_->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); return; } } diff --git a/third_party/spirv-tools/source/reduce/remove_struct_member_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/remove_struct_member_reduction_opportunity.cpp index 787c629b7a..da096e1ebe 100644 --- a/third_party/spirv-tools/source/reduce/remove_struct_member_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/remove_struct_member_reduction_opportunity.cpp @@ -129,6 +129,8 @@ void RemoveStructMemberReductionOpportunity::Apply() { // Remove the member from the struct type. struct_type_->RemoveInOperand(member_index_); + + context->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); } void RemoveStructMemberReductionOpportunity::AdjustAccessedIndices( diff --git a/third_party/spirv-tools/source/reduce/simple_conditional_branch_to_branch_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/simple_conditional_branch_to_branch_reduction_opportunity.cpp index ca17f9eb11..a2be0c4d9b 100644 --- a/third_party/spirv-tools/source/reduce/simple_conditional_branch_to_branch_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/simple_conditional_branch_to_branch_reduction_opportunity.cpp @@ -51,6 +51,8 @@ void SimpleConditionalBranchToBranchReductionOpportunity::Apply() { {{SPV_OPERAND_TYPE_ID, {conditional_branch_instruction_->GetSingleWordInOperand( kTrueBranchOperandIndex)}}}); + conditional_branch_instruction_->context()->InvalidateAnalysesExceptFor( + opt::IRContext::kAnalysisNone); } } // namespace reduce diff --git a/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity.cpp new file mode 100644 index 0000000000..ed738411a3 --- /dev/null +++ b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity.cpp @@ -0,0 +1,67 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/reduce/structured_construct_to_block_reduction_opportunity.h" + +namespace spvtools { +namespace reduce { + +bool StructuredConstructToBlockReductionOpportunity::PreconditionHolds() { + return context_->get_def_use_mgr()->GetDef(construct_header_) != nullptr; +} + +void StructuredConstructToBlockReductionOpportunity::Apply() { + auto header_block = context_->cfg()->block(construct_header_); + auto merge_block = context_->cfg()->block(header_block->MergeBlockId()); + + auto* enclosing_function = header_block->GetParent(); + + // A region of blocks is defined in terms of dominators and post-dominators, + // so we compute these for the enclosing function. + auto* dominators = context_->GetDominatorAnalysis(enclosing_function); + auto* postdominators = context_->GetPostDominatorAnalysis(enclosing_function); + + // For each block in the function, determine whether it is inside the region. + // If it is, delete it. + for (auto block_it = enclosing_function->begin(); + block_it != enclosing_function->end();) { + if (header_block != &*block_it && merge_block != &*block_it && + dominators->Dominates(header_block, &*block_it) && + postdominators->Dominates(merge_block, &*block_it)) { + block_it = block_it.Erase(); + } else { + ++block_it; + } + } + // Having removed some blocks from the module it is necessary to invalidate + // analyses, since the remaining patch-up work depends on various analyses + // which will otherwise reference blocks that have been deleted. + context_->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); + + // We demote the header of the region to a regular block by deleting its merge + // instruction. + context_->KillInst(header_block->GetMergeInst()); + + // The terminator for the header block is changed to be an unconditional + // branch to the merge block. + header_block->terminator()->SetOpcode(SpvOpBranch); + header_block->terminator()->SetInOperands( + {{SPV_OPERAND_TYPE_ID, {merge_block->id()}}}); + + // This is an intrusive change, so we invalidate all analyses. + context_->InvalidateAnalysesExceptFor(opt::IRContext::kAnalysisNone); +} + +} // namespace reduce +} // namespace spvtools diff --git a/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity.h b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity.h new file mode 100644 index 0000000000..f461a2f082 --- /dev/null +++ b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity.h @@ -0,0 +1,49 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_REDUCE_STRUCTURED_CONSTRUCT_TO_BLOCK_REDUCTION_OPPORTUNITY_H_ +#define SOURCE_REDUCE_STRUCTURED_CONSTRUCT_TO_BLOCK_REDUCTION_OPPORTUNITY_H_ + +#include "source/opt/ir_context.h" +#include "source/reduce/reduction_opportunity.h" + +namespace spvtools { +namespace reduce { + +// An opportunity to replace a skeletal structured control flow construct with a +// single block. +class StructuredConstructToBlockReductionOpportunity + : public ReductionOpportunity { + public: + // Constructs an opportunity from a header block id. + StructuredConstructToBlockReductionOpportunity(opt::IRContext* context, + uint32_t construct_header) + : context_(context), construct_header_(construct_header) {} + + // Returns true if and only if |construct_header_| exists in the module - + // another opportunity may have removed it. + bool PreconditionHolds() override; + + protected: + void Apply() override; + + private: + opt::IRContext* context_; + uint32_t construct_header_; +}; + +} // namespace reduce +} // namespace spvtools + +#endif // SOURCE_REDUCE_STRUCTURED_CONSTRUCT_TO_BLOCK_REDUCTION_OPPORTUNITY_H_ diff --git a/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity_finder.cpp b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity_finder.cpp new file mode 100644 index 0000000000..dc20f689bc --- /dev/null +++ b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity_finder.cpp @@ -0,0 +1,185 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/reduce/structured_construct_to_block_reduction_opportunity_finder.h" + +#include + +#include "source/reduce/structured_construct_to_block_reduction_opportunity.h" + +namespace spvtools { +namespace reduce { + +std::vector> +StructuredConstructToBlockReductionOpportunityFinder::GetAvailableOpportunities( + opt::IRContext* context, uint32_t target_function) const { + std::vector> result; + + // Consider every function in the module. + for (auto* function : GetTargetFunctions(context, target_function)) { + // For every header block in the function, there is potentially a region of + // blocks that could be collapsed. + std::unordered_map> + regions; + + // Regions are identified using dominators and postdominators, so we compute + // those for the function. + auto* dominators = context->GetDominatorAnalysis(function); + auto* postdominators = context->GetPostDominatorAnalysis(function); + + // Consider every block in the function. + for (auto& block : *function) { + // If a block has an unreachable predecessor then folding away a region in + // which that block is contained gets complicated, so we ignore regions + // that contain such blocks. We note whether this block suffers from this + // problem. + bool has_unreachable_predecessor = + HasUnreachablePredecessor(block, context); + + // Look through all the regions we have identified so far to see whether + // this block is part of a region, or spoils a region (by having an + // unreachable predecessor). + for (auto entry = regions.begin(); entry != regions.end();) { + // |block| is in this region if it is dominated by the header, + // post-dominated by the merge, and different from the merge. + assert(&block != entry->first && + "The block should not be the region's header because we only " + "make a region when we encounter its header."); + if (entry->first->MergeBlockId() != block.id() && + dominators->Dominates(entry->first, &block) && + postdominators->Dominates( + entry->first->GetMergeInst()->GetSingleWordInOperand(0), + block.id())) { + if (has_unreachable_predecessor) { + // The block would be in this region, but it has an unreachable + // predecessor. This spoils the region, so we remove it. + entry = regions.erase(entry); + continue; + } else { + // Add the block to the region. + entry->second.insert(&block); + } + } + ++entry; + } + if (block.MergeBlockIdIfAny() == 0) { + // The block isn't a header, so it doesn't constitute a new region. + continue; + } + if (!context->IsReachable(block)) { + // The block isn't reachable, so it doesn't constitute a new region. + continue; + } + auto* merge_block = context->cfg()->block( + block.GetMergeInst()->GetSingleWordInOperand(0)); + if (!context->IsReachable(*merge_block)) { + // The block's merge is unreachable, so it doesn't constitute a new + // region. + continue; + } + assert(dominators->Dominates(&block, merge_block) && + "The merge block is reachable, so the header must dominate it"); + if (!postdominators->Dominates(merge_block, &block)) { + // The block is not post-dominated by its merge. This happens for + // instance when there is a break from a conditional, or an early exit. + // This also means that we don't add a region. + continue; + } + // We have a reachable header block with a rechable merge that + // postdominates the header: this means we have a new region. + regions.emplace(&block, std::unordered_set()); + } + + // Now that we have found all the regions and blocks within them, we check + // whether any region defines an id that is used outside the region. If this + // is *not* the case, then we have an opportunity to collapse the region + // down to its header block and merge block. + for (auto& entry : regions) { + if (DefinitionsRestrictedToRegion(*entry.first, entry.second, context)) { + result.emplace_back( + MakeUnique( + context, entry.first->id())); + } + } + } + return result; +} + +bool StructuredConstructToBlockReductionOpportunityFinder:: + DefinitionsRestrictedToRegion( + const opt::BasicBlock& header, + const std::unordered_set& region, + opt::IRContext* context) { + // Consider every block in the region. + for (auto& block : region) { + // Consider every instruction in the block - this includes the label + // instruction + if (!block->WhileEachInst( + [context, &header, ®ion](opt::Instruction* inst) -> bool { + if (inst->result_id() == 0) { + // The instruction does not genreate a result id, thus it cannot + // be referred to outside the region - this is fine. + return true; + } + // Consider every use of the instruction's result id. + if (!context->get_def_use_mgr()->WhileEachUse( + inst->result_id(), + [context, &header, ®ion](opt::Instruction* user, + uint32_t) -> bool { + auto user_block = context->get_instr_block(user); + if (user == header.GetMergeInst() || + user == header.terminator()) { + // We are going to delete the header's merge + // instruction and rewrite its terminator, so it does + // not matter if the user is one of these + // instructions. + return true; + } + if (user_block == nullptr || + region.count(user_block) == 0) { + // The user is either a global instruction, or an + // instruction in a block outside the region. Removing + // the region would invalidate this user. + return false; + } + return true; + })) { + return false; + } + return true; + })) { + return false; + } + } + return true; +} + +bool StructuredConstructToBlockReductionOpportunityFinder:: + HasUnreachablePredecessor(const opt::BasicBlock& block, + opt::IRContext* context) { + for (auto pred : context->cfg()->preds(block.id())) { + if (!context->IsReachable(*context->cfg()->block(pred))) { + return true; + } + } + return false; +} + +std::string StructuredConstructToBlockReductionOpportunityFinder::GetName() + const { + return "StructuredConstructToBlockReductionOpportunityFinder"; +} + +} // namespace reduce +} // namespace spvtools diff --git a/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity_finder.h b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity_finder.h new file mode 100644 index 0000000000..28bbc17cfe --- /dev/null +++ b/third_party/spirv-tools/source/reduce/structured_construct_to_block_reduction_opportunity_finder.h @@ -0,0 +1,57 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef SOURCE_REDUCE_STRUCTURED_CONSTRUCT_TO_BLOCK_REDUCTION_OPPORTUNITY_FINDER_H +#define SOURCE_REDUCE_STRUCTURED_CONSTRUCT_TO_BLOCK_REDUCTION_OPPORTUNITY_FINDER_H + +#include "source/reduce/reduction_opportunity_finder.h" + +namespace spvtools { +namespace reduce { + +// A finder for opportunities to replace a skeletal structured control flow +// construct - that is, a construct that does not define anything that's used +// outside the construct - into its header block. +class StructuredConstructToBlockReductionOpportunityFinder + : public ReductionOpportunityFinder { + public: + StructuredConstructToBlockReductionOpportunityFinder() = default; + + ~StructuredConstructToBlockReductionOpportunityFinder() override = default; + + std::string GetName() const final; + + std::vector> GetAvailableOpportunities( + opt::IRContext* context, uint32_t target_function) const final; + + private: + // Returns true if and only if all instructions defined in |region| are used + // only inside |region|, with the exception that they may be used by the merge + // or terminator instruction of |header|, which must be the header block for + // the region. + static bool DefinitionsRestrictedToRegion( + const opt::BasicBlock& header, + const std::unordered_set& region, + opt::IRContext* context); + + // Returns true if and only if |block| has at least one predecessor that is + // unreachable in the control flow graph of its function. + static bool HasUnreachablePredecessor(const opt::BasicBlock& block, + opt::IRContext* context); +}; + +} // namespace reduce +} // namespace spvtools + +#endif // SOURCE_REDUCE_STRUCTURED_CONSTRUCT_TO_BLOCK_REDUCTION_OPPORTUNITY_FINDER_H diff --git a/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.cpp b/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.cpp index 0c004439f7..850af45661 100644 --- a/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.cpp +++ b/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.cpp @@ -27,16 +27,14 @@ const uint32_t kMergeNodeIndex = 0; bool StructuredLoopToSelectionReductionOpportunity::PreconditionHolds() { // Is the loop header reachable? - return loop_construct_header_->GetLabel() - ->context() - ->GetDominatorAnalysis(enclosing_function_) - ->IsReachable(loop_construct_header_); + return loop_construct_header_->GetLabel()->context()->IsReachable( + *loop_construct_header_); } void StructuredLoopToSelectionReductionOpportunity::Apply() { // Force computation of dominator analysis, CFG and structured CFG analysis // before we start to mess with edges in the function. - context_->GetDominatorAnalysis(enclosing_function_); + context_->GetDominatorAnalysis(loop_construct_header_->GetParent()); context_->cfg(); context_->GetStructuredCFGAnalysis(); @@ -78,8 +76,7 @@ void StructuredLoopToSelectionReductionOpportunity::RedirectToClosestMergeBlock( } already_seen.insert(pred); - if (!context_->GetDominatorAnalysis(enclosing_function_) - ->IsReachable(pred)) { + if (!context_->IsReachable(*context_->cfg()->block(pred))) { // We do not care about unreachable predecessors (and dominance // information, and thus the notion of structured control flow, makes // little sense for unreachable blocks). @@ -216,7 +213,7 @@ void StructuredLoopToSelectionReductionOpportunity::ChangeLoopToSelection() { void StructuredLoopToSelectionReductionOpportunity::FixNonDominatedIdUses() { // Consider each instruction in the function. - for (auto& block : *enclosing_function_) { + for (auto& block : *loop_construct_header_->GetParent()) { for (auto& def : block) { if (def.opcode() == SpvOpVariable) { // Variables are defined at the start of the function, and can be @@ -243,7 +240,7 @@ void StructuredLoopToSelectionReductionOpportunity::FixNonDominatedIdUses() { case SpvStorageClassFunction: use->SetOperand( index, {FindOrCreateFunctionVariable( - context_, enclosing_function_, + context_, loop_construct_header_->GetParent(), context_->get_type_mgr()->GetId(pointer_type))}); break; default: @@ -276,11 +273,11 @@ bool StructuredLoopToSelectionReductionOpportunity:: if (use->opcode() == SpvOpPhi) { // A use in a phi doesn't need to be dominated by its definition, but the // associated parent block does need to be dominated by the definition. - return context_->GetDominatorAnalysis(enclosing_function_) + return context_->GetDominatorAnalysis(loop_construct_header_->GetParent()) ->Dominates(def_block.id(), use->GetSingleWordOperand(use_index + 1)); } // In non-phi cases, a use needs to be dominated by its definition. - return context_->GetDominatorAnalysis(enclosing_function_) + return context_->GetDominatorAnalysis(loop_construct_header_->GetParent()) ->Dominates(def, use); } diff --git a/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.h b/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.h index 4c576196e1..0e3c840af6 100644 --- a/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.h +++ b/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity.h @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#ifndef SOURCE_REDUCE_CUT_LOOP_REDUCTION_OPPORTUNITY_H_ -#define SOURCE_REDUCE_CUT_LOOP_REDUCTION_OPPORTUNITY_H_ +#ifndef SOURCE_REDUCE_STRUCTURED_LOOP_TO_SELECTION_REDUCTION_OPPORTUNITY_H_ +#define SOURCE_REDUCE_STRUCTURED_LOOP_TO_SELECTION_REDUCTION_OPPORTUNITY_H_ #include "source/opt/def_use_manager.h" #include "source/opt/dominator_analysis.h" @@ -30,11 +30,8 @@ class StructuredLoopToSelectionReductionOpportunity // Constructs an opportunity from a loop header block and the function that // encloses it. explicit StructuredLoopToSelectionReductionOpportunity( - opt::IRContext* context, opt::BasicBlock* loop_construct_header, - opt::Function* enclosing_function) - : context_(context), - loop_construct_header_(loop_construct_header), - enclosing_function_(enclosing_function) {} + opt::IRContext* context, opt::BasicBlock* loop_construct_header) + : context_(context), loop_construct_header_(loop_construct_header) {} // Returns true if the loop header is reachable. A structured loop might // become unreachable as a result of turning another structured loop into @@ -88,10 +85,9 @@ class StructuredLoopToSelectionReductionOpportunity opt::IRContext* context_; opt::BasicBlock* loop_construct_header_; - opt::Function* enclosing_function_; }; } // namespace reduce } // namespace spvtools -#endif // SOURCE_REDUCE_CUT_LOOP_REDUCTION_OPPORTUNITY_H_ +#endif // SOURCE_REDUCE_STRUCTURED_LOOP_TO_SELECTION_REDUCTION_OPPORTUNITY_H_ diff --git a/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity_finder.cpp b/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity_finder.cpp index fdf3ab043a..3fe6128038 100644 --- a/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity_finder.cpp +++ b/third_party/spirv-tools/source/reduce/structured_loop_to_selection_reduction_opportunity_finder.cpp @@ -86,8 +86,8 @@ StructuredLoopToSelectionReductionOpportunityFinder::GetAvailableOpportunities( // We can turn this structured loop into a selection, so add the // opportunity to do so. result.push_back( - MakeUnique( - context, &block, function)); + MakeUnique(context, + &block)); } } return result; diff --git a/third_party/spirv-tools/source/spirv_target_env.cpp b/third_party/spirv-tools/source/spirv_target_env.cpp index e2ff99cb04..f20ebb4fb5 100644 --- a/third_party/spirv-tools/source/spirv_target_env.cpp +++ b/third_party/spirv-tools/source/spirv_target_env.cpp @@ -14,6 +14,7 @@ #include "source/spirv_target_env.h" +#include #include #include @@ -61,7 +62,8 @@ const char* spvTargetEnvDescription(spv_target_env env) { case SPV_ENV_VULKAN_1_1: return "SPIR-V 1.3 (under Vulkan 1.1 semantics)"; case SPV_ENV_WEBGPU_0: - return "SPIR-V 1.3 (under WIP WebGPU semantics)"; + assert(false); + break; case SPV_ENV_UNIVERSAL_1_4: return "SPIR-V 1.4"; case SPV_ENV_VULKAN_1_1_SPIRV_1_4: @@ -98,8 +100,10 @@ uint32_t spvVersionForTargetEnv(spv_target_env env) { return SPV_SPIRV_VERSION_WORD(1, 2); case SPV_ENV_UNIVERSAL_1_3: case SPV_ENV_VULKAN_1_1: - case SPV_ENV_WEBGPU_0: return SPV_SPIRV_VERSION_WORD(1, 3); + case SPV_ENV_WEBGPU_0: + assert(false); + break; case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_VULKAN_1_1_SPIRV_1_4: return SPV_SPIRV_VERSION_WORD(1, 4); @@ -134,7 +138,6 @@ static const std::pair spvTargetEnvNameMap[] = { {"opengl4.2", SPV_ENV_OPENGL_4_2}, {"opengl4.3", SPV_ENV_OPENGL_4_3}, {"opengl4.5", SPV_ENV_OPENGL_4_5}, - {"webgpu0", SPV_ENV_WEBGPU_0}, }; bool spvParseTargetEnv(const char* s, spv_target_env* env) { @@ -200,7 +203,6 @@ bool spvIsVulkanEnv(spv_target_env env) { case SPV_ENV_OPENCL_2_2: case SPV_ENV_OPENCL_EMBEDDED_2_2: case SPV_ENV_UNIVERSAL_1_3: - case SPV_ENV_WEBGPU_0: case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_UNIVERSAL_1_5: return false; @@ -209,6 +211,9 @@ bool spvIsVulkanEnv(spv_target_env env) { case SPV_ENV_VULKAN_1_1_SPIRV_1_4: case SPV_ENV_VULKAN_1_2: return true; + case SPV_ENV_WEBGPU_0: + assert(false); + break; } return false; } @@ -226,7 +231,6 @@ bool spvIsOpenCLEnv(spv_target_env env) { case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_3: case SPV_ENV_VULKAN_1_1: - case SPV_ENV_WEBGPU_0: case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_VULKAN_1_1_SPIRV_1_4: case SPV_ENV_UNIVERSAL_1_5: @@ -241,38 +245,9 @@ bool spvIsOpenCLEnv(spv_target_env env) { case SPV_ENV_OPENCL_2_1: case SPV_ENV_OPENCL_2_2: return true; - } - return false; -} - -bool spvIsWebGPUEnv(spv_target_env env) { - switch (env) { - case SPV_ENV_UNIVERSAL_1_0: - case SPV_ENV_VULKAN_1_0: - case SPV_ENV_UNIVERSAL_1_1: - case SPV_ENV_OPENGL_4_0: - case SPV_ENV_OPENGL_4_1: - case SPV_ENV_OPENGL_4_2: - case SPV_ENV_OPENGL_4_3: - case SPV_ENV_OPENGL_4_5: - case SPV_ENV_UNIVERSAL_1_2: - case SPV_ENV_UNIVERSAL_1_3: - case SPV_ENV_VULKAN_1_1: - case SPV_ENV_OPENCL_1_2: - case SPV_ENV_OPENCL_EMBEDDED_1_2: - case SPV_ENV_OPENCL_2_0: - case SPV_ENV_OPENCL_EMBEDDED_2_0: - case SPV_ENV_OPENCL_EMBEDDED_2_1: - case SPV_ENV_OPENCL_EMBEDDED_2_2: - case SPV_ENV_OPENCL_2_1: - case SPV_ENV_OPENCL_2_2: - case SPV_ENV_UNIVERSAL_1_4: - case SPV_ENV_VULKAN_1_1_SPIRV_1_4: - case SPV_ENV_UNIVERSAL_1_5: - case SPV_ENV_VULKAN_1_2: - return false; case SPV_ENV_WEBGPU_0: - return true; + assert(false); + break; } return false; } @@ -293,7 +268,6 @@ bool spvIsOpenGLEnv(spv_target_env env) { case SPV_ENV_OPENCL_EMBEDDED_2_2: case SPV_ENV_OPENCL_2_1: case SPV_ENV_OPENCL_2_2: - case SPV_ENV_WEBGPU_0: case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_VULKAN_1_1_SPIRV_1_4: case SPV_ENV_UNIVERSAL_1_5: @@ -305,14 +279,13 @@ bool spvIsOpenGLEnv(spv_target_env env) { case SPV_ENV_OPENGL_4_3: case SPV_ENV_OPENGL_4_5: return true; + case SPV_ENV_WEBGPU_0: + assert(false); + break; } return false; } -bool spvIsVulkanOrWebGPUEnv(spv_target_env env) { - return spvIsVulkanEnv(env) || spvIsWebGPUEnv(env); -} - std::string spvLogStringForEnv(spv_target_env env) { switch (env) { case SPV_ENV_OPENCL_1_2: @@ -338,9 +311,6 @@ std::string spvLogStringForEnv(spv_target_env env) { case SPV_ENV_VULKAN_1_2: return "Vulkan"; } - case SPV_ENV_WEBGPU_0: { - return "WebGPU"; - } case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: @@ -349,6 +319,9 @@ std::string spvLogStringForEnv(spv_target_env env) { case SPV_ENV_UNIVERSAL_1_5: { return "Universal"; } + case SPV_ENV_WEBGPU_0: + assert(false); + break; } return "Unknown"; } diff --git a/third_party/spirv-tools/source/spirv_target_env.h b/third_party/spirv-tools/source/spirv_target_env.h index 1bdedf917f..a804d615c5 100644 --- a/third_party/spirv-tools/source/spirv_target_env.h +++ b/third_party/spirv-tools/source/spirv_target_env.h @@ -25,20 +25,14 @@ bool spvIsVulkanEnv(spv_target_env env); // Returns true if |env| is an OPENCL environment, false otherwise. bool spvIsOpenCLEnv(spv_target_env env); -// Returns true if |env| is an WEBGPU environment, false otherwise. -bool spvIsWebGPUEnv(spv_target_env env); - // Returns true if |env| is an OPENGL environment, false otherwise. bool spvIsOpenGLEnv(spv_target_env env); -// Returns true if |env| is a VULKAN or WEBGPU environment, false otherwise. -bool spvIsVulkanOrWebGPUEnv(spv_target_env env); - // Returns the version number for the given SPIR-V target environment. uint32_t spvVersionForTargetEnv(spv_target_env env); // Returns a string to use in logging messages that indicates the class of -// environment, i.e. "Vulkan", "WebGPU", "OpenCL", etc. +// environment, i.e. "Vulkan", "OpenCL", etc. std::string spvLogStringForEnv(spv_target_env env); // Returns a formatted list of all SPIR-V target environment names that diff --git a/third_party/spirv-tools/source/spirv_validator_options.cpp b/third_party/spirv-tools/source/spirv_validator_options.cpp index 01aa79747b..2716cca9be 100644 --- a/third_party/spirv-tools/source/spirv_validator_options.cpp +++ b/third_party/spirv-tools/source/spirv_validator_options.cpp @@ -111,6 +111,11 @@ void spvValidatorOptionsSetScalarBlockLayout(spv_validator_options options, options->scalar_block_layout = val; } +void spvValidatorOptionsSetWorkgroupScalarBlockLayout(spv_validator_options options, + bool val) { + options->workgroup_scalar_block_layout = val; +} + void spvValidatorOptionsSetSkipBlockLayout(spv_validator_options options, bool val) { options->skip_block_layout = val; diff --git a/third_party/spirv-tools/source/spirv_validator_options.h b/third_party/spirv-tools/source/spirv_validator_options.h index b7da5d8eae..baaa5359e9 100644 --- a/third_party/spirv-tools/source/spirv_validator_options.h +++ b/third_party/spirv-tools/source/spirv_validator_options.h @@ -45,6 +45,7 @@ struct spv_validator_options_t { relax_block_layout(false), uniform_buffer_standard_layout(false), scalar_block_layout(false), + workgroup_scalar_block_layout(false), skip_block_layout(false), before_hlsl_legalization(false) {} @@ -54,6 +55,7 @@ struct spv_validator_options_t { bool relax_block_layout; bool uniform_buffer_standard_layout; bool scalar_block_layout; + bool workgroup_scalar_block_layout; bool skip_block_layout; bool before_hlsl_legalization; }; diff --git a/third_party/spirv-tools/source/table.cpp b/third_party/spirv-tools/source/table.cpp index 8340e8e210..d4a2d7e967 100644 --- a/third_party/spirv-tools/source/table.cpp +++ b/third_party/spirv-tools/source/table.cpp @@ -38,7 +38,6 @@ spv_context spvContextCreate(spv_target_env env) { case SPV_ENV_UNIVERSAL_1_3: case SPV_ENV_VULKAN_1_1: case SPV_ENV_VULKAN_1_1_SPIRV_1_4: - case SPV_ENV_WEBGPU_0: case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_UNIVERSAL_1_5: case SPV_ENV_VULKAN_1_2: diff --git a/third_party/spirv-tools/source/val/basic_block.h b/third_party/spirv-tools/source/val/basic_block.h index 5eea4f9283..5af4b9e4d2 100644 --- a/third_party/spirv-tools/source/val/basic_block.h +++ b/third_party/spirv-tools/source/val/basic_block.h @@ -139,9 +139,14 @@ class BasicBlock { /// @brief A BasicBlock dominator iterator class /// /// This iterator will iterate over the (post)dominators of the block - class DominatorIterator - : public std::iterator { + class DominatorIterator { public: + using iterator_category = std::forward_iterator_tag; + using value_type = BasicBlock*; + using pointer = value_type*; + using reference = value_type&; + using difference_type = std::ptrdiff_t; + /// @brief Constructs the end of dominator iterator /// /// This will create an iterator which will represent the element diff --git a/third_party/spirv-tools/source/val/construct.cpp b/third_party/spirv-tools/source/val/construct.cpp index 733856cb84..5300869062 100644 --- a/third_party/spirv-tools/source/val/construct.cpp +++ b/third_party/spirv-tools/source/val/construct.cpp @@ -78,7 +78,12 @@ Construct::ConstructBlockSet Construct::blocks(Function* function) const { ConstructBlockSet construct_blocks; std::unordered_set corresponding_headers; for (auto& other : corresponding_constructs()) { - corresponding_headers.insert(other->entry_block()); + // The corresponding header can be the same block as this construct's + // header for loops with no loop construct. In those cases, don't add the + // loop header as it prevents finding any blocks in the construct. + if (type() != ConstructType::kContinue || other->entry_block() != header) { + corresponding_headers.insert(other->entry_block()); + } } std::vector stack; stack.push_back(const_cast(header)); diff --git a/third_party/spirv-tools/source/val/validate.cpp b/third_party/spirv-tools/source/val/validate.cpp index d6e992b15b..45b6a463e6 100644 --- a/third_party/spirv-tools/source/val/validate.cpp +++ b/third_party/spirv-tools/source/val/validate.cpp @@ -111,57 +111,6 @@ spv_result_t ValidateForwardDecls(ValidationState_t& _) { << id_str.substr(0, id_str.size() - 1); } -std::vector CalculateNamesForEntryPoint(ValidationState_t& _, - const uint32_t id) { - auto id_descriptions = _.entry_point_descriptions(id); - auto id_names = std::vector(); - id_names.reserve((id_descriptions.size())); - - for (auto description : id_descriptions) id_names.push_back(description.name); - - return id_names; -} - -spv_result_t ValidateEntryPointNameUnique(ValidationState_t& _, - const uint32_t id) { - auto id_names = CalculateNamesForEntryPoint(_, id); - const auto names = - std::unordered_set(id_names.begin(), id_names.end()); - - if (id_names.size() != names.size()) { - std::sort(id_names.begin(), id_names.end()); - for (size_t i = 0; i < id_names.size() - 1; i++) { - if (id_names[i] == id_names[i + 1]) { - return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(id)) - << "Entry point name \"" << id_names[i] - << "\" is not unique, which is not allow in WebGPU env."; - } - } - } - - for (const auto other_id : _.entry_points()) { - if (other_id == id) continue; - const auto other_id_names = CalculateNamesForEntryPoint(_, other_id); - for (const auto& other_id_name : other_id_names) { - if (names.find(other_id_name) != names.end()) { - return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(id)) - << "Entry point name \"" << other_id_name - << "\" is not unique, which is not allow in WebGPU env."; - } - } - } - - return SPV_SUCCESS; -} - -spv_result_t ValidateEntryPointNamesUnique(ValidationState_t& _) { - for (const auto id : _.entry_points()) { - auto result = ValidateEntryPointNameUnique(_, id); - if (result != SPV_SUCCESS) return result; - } - return SPV_SUCCESS; -} - // Entry point validation. Based on 2.16.1 (Universal Validation Rules) of the // SPIRV spec: // * There is at least one OpEntryPoint instruction, unless the Linkage @@ -169,8 +118,7 @@ spv_result_t ValidateEntryPointNamesUnique(ValidationState_t& _) { // * No function can be targeted by both an OpEntryPoint instruction and an // OpFunctionCall instruction. // -// Additionally enforces that entry points for Vulkan and WebGPU should not have -// recursion. And that entry names should be unique for WebGPU. +// Additionally enforces that entry points for Vulkan should not have recursion. spv_result_t ValidateEntryPoints(ValidationState_t& _) { _.ComputeFunctionToEntryPointMapping(); _.ComputeRecursiveEntryPoints(); @@ -189,21 +137,16 @@ spv_result_t ValidateEntryPoints(ValidationState_t& _) { "an OpFunctionCall instruction."; } - // For Vulkan and WebGPU, the static function-call graph for an entry point + // For Vulkan, the static function-call graph for an entry point // must not contain cycles. - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (_.recursive_entry_points().find(entry_point) != _.recursive_entry_points().end()) { return _.diag(SPV_ERROR_INVALID_BINARY, _.FindDef(entry_point)) + << _.VkErrorID(4634) << "Entry points may not have a call graph with cycles."; } } - - // For WebGPU all entry point names must be unique. - if (spvIsWebGPUEnv(_.context()->target_env)) { - const auto result = ValidateEntryPointNamesUnique(_); - if (result != SPV_SUCCESS) return result; - } } return SPV_SUCCESS; @@ -223,12 +166,6 @@ spv_result_t ValidateBinaryUsingContextAndValidationState( << "Invalid SPIR-V magic number."; } - if (spvIsWebGPUEnv(context.target_env) && endian != SPV_ENDIANNESS_LITTLE) { - return DiagnosticStream(position, context.consumer, "", - SPV_ERROR_INVALID_BINARY) - << "WebGPU requires SPIR-V to be little endian."; - } - spv_header_t header; if (spvBinaryHeaderGet(binary.get(), endian, &header)) { return DiagnosticStream(position, context.consumer, "", @@ -321,13 +258,6 @@ spv_result_t ValidateBinaryUsingContextAndValidationState( } const auto called_id = inst->GetOperandAs(2); - if (spvIsWebGPUEnv(context.target_env) && - !vstate->IsFunctionCallDefined(called_id)) { - return vstate->diag(SPV_ERROR_INVALID_LAYOUT, &instruction) - << "For WebGPU, functions need to be defined before being " - "called."; - } - vstate->AddFunctionCallTarget(called_id); } diff --git a/third_party/spirv-tools/source/val/validate_annotation.cpp b/third_party/spirv-tools/source/val/validate_annotation.cpp index df38f1b163..85d2b7515a 100644 --- a/third_party/spirv-tools/source/val/validate_annotation.cpp +++ b/third_party/spirv-tools/source/val/validate_annotation.cpp @@ -22,36 +22,6 @@ namespace spvtools { namespace val { namespace { -bool IsValidWebGPUDecoration(uint32_t decoration) { - switch (decoration) { - case SpvDecorationSpecId: - case SpvDecorationBlock: - case SpvDecorationRowMajor: - case SpvDecorationColMajor: - case SpvDecorationArrayStride: - case SpvDecorationMatrixStride: - case SpvDecorationBuiltIn: - case SpvDecorationNoPerspective: - case SpvDecorationFlat: - case SpvDecorationCentroid: - case SpvDecorationRestrict: - case SpvDecorationAliased: - case SpvDecorationNonWritable: - case SpvDecorationNonReadable: - case SpvDecorationUniform: - case SpvDecorationLocation: - case SpvDecorationComponent: - case SpvDecorationIndex: - case SpvDecorationBinding: - case SpvDecorationDescriptorSet: - case SpvDecorationOffset: - case SpvDecorationNoContraction: - return true; - default: - return false; - } -} - std::string LogStringForDecoration(uint32_t decoration) { switch (decoration) { case SpvDecorationRelaxedPrecision: @@ -212,11 +182,14 @@ spv_result_t ValidateDecorate(ValidationState_t& _, const Instruction* inst) { } } - if (spvIsWebGPUEnv(_.context()->target_env) && - !IsValidWebGPUDecoration(decoration)) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpDecorate decoration '" << LogStringForDecoration(decoration) - << "' is not valid for the WebGPU execution environment."; + if (spvIsVulkanEnv(_.context()->target_env)) { + if ((decoration == SpvDecorationGLSLShared) || + (decoration == SpvDecorationGLSLPacked)) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << _.VkErrorID(4669) << "OpDecorate decoration '" + << LogStringForDecoration(decoration) + << "' is not valid for the Vulkan execution environment."; + } } if (DecorationTakesIdParameters(decoration)) { @@ -261,25 +234,11 @@ spv_result_t ValidateMemberDecorate(ValidationState_t& _, << " members. Largest valid index is " << member_count - 1 << "."; } - const auto decoration = inst->GetOperandAs(2); - if (spvIsWebGPUEnv(_.context()->target_env) && - !IsValidWebGPUDecoration(decoration)) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpMemberDecorate decoration '" << _.getIdName(decoration) - << "' is not valid for the WebGPU execution environment."; - } - return SPV_SUCCESS; } spv_result_t ValidateDecorationGroup(ValidationState_t& _, const Instruction* inst) { - if (spvIsWebGPUEnv(_.context()->target_env)) { - return _.diag(SPV_ERROR_INVALID_BINARY, inst) - << "OpDecorationGroup is not allowed in the WebGPU execution " - << "environment."; - } - const auto decoration_group_id = inst->GetOperandAs(0); const auto decoration_group = _.FindDef(decoration_group_id); for (auto pair : decoration_group->uses()) { @@ -299,12 +258,6 @@ spv_result_t ValidateDecorationGroup(ValidationState_t& _, spv_result_t ValidateGroupDecorate(ValidationState_t& _, const Instruction* inst) { - if (spvIsWebGPUEnv(_.context()->target_env)) { - return _.diag(SPV_ERROR_INVALID_BINARY, inst) - << "OpGroupDecorate is not allowed in the WebGPU execution " - << "environment."; - } - const auto decoration_group_id = inst->GetOperandAs(0); auto decoration_group = _.FindDef(decoration_group_id); if (!decoration_group || SpvOpDecorationGroup != decoration_group->opcode()) { @@ -327,12 +280,6 @@ spv_result_t ValidateGroupDecorate(ValidationState_t& _, spv_result_t ValidateGroupMemberDecorate(ValidationState_t& _, const Instruction* inst) { - if (spvIsWebGPUEnv(_.context()->target_env)) { - return _.diag(SPV_ERROR_INVALID_BINARY, inst) - << "OpGroupMemberDecorate is not allowed in the WebGPU execution " - << "environment."; - } - const auto decoration_group_id = inst->GetOperandAs(0); const auto decoration_group = _.FindDef(decoration_group_id); if (!decoration_group || SpvOpDecorationGroup != decoration_group->opcode()) { diff --git a/third_party/spirv-tools/source/val/validate_atomics.cpp b/third_party/spirv-tools/source/val/validate_atomics.cpp index 3f1f561755..da023b80c5 100644 --- a/third_party/spirv-tools/source/val/validate_atomics.cpp +++ b/third_party/spirv-tools/source/val/validate_atomics.cpp @@ -47,25 +47,31 @@ bool IsStorageClassAllowedByUniversalRules(uint32_t storage_class) { } } -} // namespace - -namespace spvtools { -namespace val { - -// Validates correctness of atomic instructions. -spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { - const SpvOp opcode = inst->opcode(); - const uint32_t result_type = inst->type_id(); - bool is_atomic_float_opcode = false; - if (opcode == SpvOpAtomicLoad || opcode == SpvOpAtomicStore || - opcode == SpvOpAtomicFAddEXT || opcode == SpvOpAtomicExchange) { - is_atomic_float_opcode = true; - } +bool HasReturnType(uint32_t opcode) { switch (opcode) { - case SpvOpAtomicLoad: case SpvOpAtomicStore: - case SpvOpAtomicExchange: + case SpvOpAtomicFlagClear: + return false; + break; + default: + return true; + } +} + +bool HasOnlyFloatReturnType(uint32_t opcode) { + switch (opcode) { case SpvOpAtomicFAddEXT: + case SpvOpAtomicFMinEXT: + case SpvOpAtomicFMaxEXT: + return true; + break; + default: + return false; + } +} + +bool HasOnlyIntReturnType(uint32_t opcode) { + switch (opcode) { case SpvOpAtomicCompareExchange: case SpvOpAtomicCompareExchangeWeak: case SpvOpAtomicIIncrement: @@ -78,124 +84,97 @@ spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { case SpvOpAtomicUMax: case SpvOpAtomicAnd: case SpvOpAtomicOr: + case SpvOpAtomicXor: + return true; + break; + default: + return false; + } +} + +bool HasIntOrFloatReturnType(uint32_t opcode) { + switch (opcode) { + case SpvOpAtomicLoad: + case SpvOpAtomicExchange: + return true; + break; + default: + return false; + } +} + +bool HasOnlyBoolReturnType(uint32_t opcode) { + switch (opcode) { + case SpvOpAtomicFlagTestAndSet: + return true; + break; + default: + return false; + } +} + +} // namespace + +namespace spvtools { +namespace val { + +// Validates correctness of atomic instructions. +spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { + const SpvOp opcode = inst->opcode(); + switch (opcode) { + case SpvOpAtomicLoad: + case SpvOpAtomicStore: + case SpvOpAtomicExchange: + case SpvOpAtomicFAddEXT: + case SpvOpAtomicCompareExchange: + case SpvOpAtomicCompareExchangeWeak: + case SpvOpAtomicIIncrement: + case SpvOpAtomicIDecrement: + case SpvOpAtomicIAdd: + case SpvOpAtomicISub: + case SpvOpAtomicSMin: + case SpvOpAtomicUMin: + case SpvOpAtomicFMinEXT: + case SpvOpAtomicSMax: + case SpvOpAtomicUMax: + case SpvOpAtomicFMaxEXT: + case SpvOpAtomicAnd: + case SpvOpAtomicOr: case SpvOpAtomicXor: case SpvOpAtomicFlagTestAndSet: case SpvOpAtomicFlagClear: { - if (_.HasCapability(SpvCapabilityKernel) && - (opcode == SpvOpAtomicLoad || opcode == SpvOpAtomicExchange || - opcode == SpvOpAtomicCompareExchange)) { - if (!_.IsFloatScalarType(result_type) && - !_.IsIntScalarType(result_type)) { + const uint32_t result_type = inst->type_id(); + + // All current atomics only are scalar result + // Validate return type first so can just check if pointer type is same + // (if applicable) + if (HasReturnType(opcode)) { + if (HasOnlyFloatReturnType(opcode) && + !_.IsFloatScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) - << ": expected Result Type to be int or float scalar type"; - } - } else if (opcode == SpvOpAtomicFlagTestAndSet) { - if (!_.IsBoolScalarType(result_type)) { + << ": expected Result Type to be float scalar type"; + } else if (HasOnlyIntReturnType(opcode) && + !_.IsIntScalarType(result_type)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": expected Result Type to be integer scalar type"; + } else if (HasIntOrFloatReturnType(opcode) && + !_.IsFloatScalarType(result_type) && + !_.IsIntScalarType(result_type)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": expected Result Type to be integer or float scalar type"; + } else if (HasOnlyBoolReturnType(opcode) && + !_.IsBoolScalarType(result_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": expected Result Type to be bool scalar type"; } - } else if (opcode == SpvOpAtomicFlagClear || opcode == SpvOpAtomicStore) { - assert(result_type == 0); - } else { - if (_.IsFloatScalarType(result_type)) { - if (is_atomic_float_opcode) { - if (opcode == SpvOpAtomicFAddEXT) { - if ((_.GetBitWidth(result_type) == 32) && - (!_.HasCapability(SpvCapabilityAtomicFloat32AddEXT))) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": float add atomics require the AtomicFloat32AddEXT " - "capability"; - } - if ((_.GetBitWidth(result_type) == 64) && - (!_.HasCapability(SpvCapabilityAtomicFloat64AddEXT))) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": float add atomics require the AtomicFloat64AddEXT " - "capability"; - } - } - } else { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": expected Result Type to be int scalar type"; - } - } else if (_.IsIntScalarType(result_type) && - opcode == SpvOpAtomicFAddEXT) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": expected Result Type to be float scalar type"; - } else if (!_.IsFloatScalarType(result_type) && - !_.IsIntScalarType(result_type)) { - switch (opcode) { - case SpvOpAtomicFAddEXT: - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": expected Result Type to be float scalar type"; - case SpvOpAtomicIIncrement: - case SpvOpAtomicIDecrement: - case SpvOpAtomicIAdd: - case SpvOpAtomicISub: - case SpvOpAtomicSMin: - case SpvOpAtomicSMax: - case SpvOpAtomicUMin: - case SpvOpAtomicUMax: - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": expected Result Type to be integer scalar type"; - default: - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": expected Result Type to be int or float scalar type"; - } - } - - if (spvIsVulkanEnv(_.context()->target_env) && - (_.GetBitWidth(result_type) != 32 && - (_.GetBitWidth(result_type) != 64 || - !_.HasCapability(SpvCapabilityInt64ImageEXT)))) { - switch (opcode) { - case SpvOpAtomicSMin: - case SpvOpAtomicUMin: - case SpvOpAtomicSMax: - case SpvOpAtomicUMax: - case SpvOpAtomicAnd: - case SpvOpAtomicOr: - case SpvOpAtomicXor: - case SpvOpAtomicIAdd: - case SpvOpAtomicISub: - case SpvOpAtomicFAddEXT: - case SpvOpAtomicLoad: - case SpvOpAtomicStore: - case SpvOpAtomicExchange: - case SpvOpAtomicIIncrement: - case SpvOpAtomicIDecrement: - case SpvOpAtomicCompareExchangeWeak: - case SpvOpAtomicCompareExchange: { - if (_.GetBitWidth(result_type) == 64 && - _.IsIntScalarType(result_type) && - !_.HasCapability(SpvCapabilityInt64Atomics)) - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": 64-bit atomics require the Int64Atomics " - "capability"; - } break; - default: - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": according to the Vulkan spec atomic Result Type " - "needs " - "to be a 32-bit int scalar type"; - } - } } - uint32_t operand_index = - opcode == SpvOpAtomicFlagClear || opcode == SpvOpAtomicStore ? 0 : 2; + uint32_t operand_index = HasReturnType(opcode) ? 2 : 0; const uint32_t pointer_type = _.GetOperandTypeId(inst, operand_index++); - uint32_t data_type = 0; uint32_t storage_class = 0; if (!_.GetPointerTypeInfo(pointer_type, &data_type, &storage_class)) { @@ -204,6 +183,14 @@ spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { << ": expected Pointer to be of type OpTypePointer"; } + // Can't use result_type because OpAtomicStore doesn't have a result + if (_.GetBitWidth(data_type) == 64 && _.IsIntScalarType(data_type) && + !_.HasCapability(SpvCapabilityInt64Atomics)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": 64-bit atomics require the Int64Atomics capability"; + } + // Validate storage class against universal rules if (!IsStorageClassAllowedByUniversalRules(storage_class)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) @@ -213,12 +200,73 @@ spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { // Then Shader rules if (_.HasCapability(SpvCapabilityShader)) { - if (storage_class == SpvStorageClassFunction) { + // Vulkan environment rule + if (spvIsVulkanEnv(_.context()->target_env)) { + if ((storage_class != SpvStorageClassUniform) && + (storage_class != SpvStorageClassStorageBuffer) && + (storage_class != SpvStorageClassWorkgroup) && + (storage_class != SpvStorageClassImage) && + (storage_class != SpvStorageClassPhysicalStorageBuffer)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4686) << spvOpcodeString(opcode) + << ": Vulkan spec only allows storage classes for atomic to " + "be: Uniform, Workgroup, Image, StorageBuffer, or " + "PhysicalStorageBuffer."; + } + } else if (storage_class == SpvStorageClassFunction) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) << ": Function storage class forbidden when the Shader " "capability is declared."; } + + if (opcode == SpvOpAtomicFAddEXT) { + // result type being float checked already + if ((_.GetBitWidth(result_type) == 16) && + (!_.HasCapability(SpvCapabilityAtomicFloat16AddEXT))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": float add atomics require the AtomicFloat32AddEXT " + "capability"; + } + if ((_.GetBitWidth(result_type) == 32) && + (!_.HasCapability(SpvCapabilityAtomicFloat32AddEXT))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": float add atomics require the AtomicFloat32AddEXT " + "capability"; + } + if ((_.GetBitWidth(result_type) == 64) && + (!_.HasCapability(SpvCapabilityAtomicFloat64AddEXT))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": float add atomics require the AtomicFloat64AddEXT " + "capability"; + } + } else if (opcode == SpvOpAtomicFMinEXT || + opcode == SpvOpAtomicFMaxEXT) { + if ((_.GetBitWidth(result_type) == 16) && + (!_.HasCapability(SpvCapabilityAtomicFloat16MinMaxEXT))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": float min/max atomics require the " + "AtomicFloat16MinMaxEXT capability"; + } + if ((_.GetBitWidth(result_type) == 32) && + (!_.HasCapability(SpvCapabilityAtomicFloat32MinMaxEXT))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": float min/max atomics require the " + "AtomicFloat32MinMaxEXT capability"; + } + if ((_.GetBitWidth(result_type) == 64) && + (!_.HasCapability(SpvCapabilityAtomicFloat64MinMaxEXT))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": float min/max atomics require the " + "AtomicFloat64MinMaxEXT capability"; + } + } } // And finally OpenCL environment rules @@ -242,27 +290,27 @@ spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { } } + // If result and pointer type are different, need to do special check here if (opcode == SpvOpAtomicFlagTestAndSet || opcode == SpvOpAtomicFlagClear) { if (!_.IsIntScalarType(data_type) || _.GetBitWidth(data_type) != 32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) - << ": expected Pointer to point to a value of 32-bit int type"; + << ": expected Pointer to point to a value of 32-bit integer " + "type"; } } else if (opcode == SpvOpAtomicStore) { if (!_.IsFloatScalarType(data_type) && !_.IsIntScalarType(data_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << spvOpcodeString(opcode) - << ": expected Pointer to be a pointer to int or float " + << ": expected Pointer to be a pointer to integer or float " << "scalar type"; } - } else { - if (data_type != result_type) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": expected Pointer to point to a value of type Result " - "Type"; - } + } else if (data_type != result_type) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << spvOpcodeString(opcode) + << ": expected Pointer to point to a value of type Result " + "Type"; } auto memory_scope = inst->GetOperandAs(operand_index++); @@ -271,14 +319,15 @@ spv_result_t AtomicsPass(ValidationState_t& _, const Instruction* inst) { } const auto equal_semantics_index = operand_index++; - if (auto error = ValidateMemorySemantics(_, inst, equal_semantics_index)) + if (auto error = ValidateMemorySemantics(_, inst, equal_semantics_index, + memory_scope)) return error; if (opcode == SpvOpAtomicCompareExchange || opcode == SpvOpAtomicCompareExchangeWeak) { const auto unequal_semantics_index = operand_index++; - if (auto error = - ValidateMemorySemantics(_, inst, unequal_semantics_index)) + if (auto error = ValidateMemorySemantics( + _, inst, unequal_semantics_index, memory_scope)) return error; // Volatile bits must match for equal and unequal semantics. Previous diff --git a/third_party/spirv-tools/source/val/validate_barriers.cpp b/third_party/spirv-tools/source/val/validate_barriers.cpp index b499c8c085..3a9e3e7c56 100644 --- a/third_party/spirv-tools/source/val/validate_barriers.cpp +++ b/third_party/spirv-tools/source/val/validate_barriers.cpp @@ -69,7 +69,7 @@ spv_result_t BarriersPass(ValidationState_t& _, const Instruction* inst) { return error; } - if (auto error = ValidateMemorySemantics(_, inst, 2)) { + if (auto error = ValidateMemorySemantics(_, inst, 2, memory_scope)) { return error; } break; @@ -82,7 +82,7 @@ spv_result_t BarriersPass(ValidationState_t& _, const Instruction* inst) { return error; } - if (auto error = ValidateMemorySemantics(_, inst, 1)) { + if (auto error = ValidateMemorySemantics(_, inst, 1, memory_scope)) { return error; } break; @@ -119,7 +119,7 @@ spv_result_t BarriersPass(ValidationState_t& _, const Instruction* inst) { return error; } - if (auto error = ValidateMemorySemantics(_, inst, 2)) { + if (auto error = ValidateMemorySemantics(_, inst, 2, memory_scope)) { return error; } break; diff --git a/third_party/spirv-tools/source/val/validate_builtins.cpp b/third_party/spirv-tools/source/val/validate_builtins.cpp index 2c5604cd56..3c9df9fc2d 100644 --- a/third_party/spirv-tools/source/val/validate_builtins.cpp +++ b/third_party/spirv-tools/source/val/validate_builtins.cpp @@ -16,6 +16,7 @@ // Validates correctness of built-in variables. +#include #include #include #include @@ -112,25 +113,128 @@ SpvStorageClass GetStorageClass(const Instruction& inst) { return SpvStorageClassMax; } -bool IsBuiltInValidForWebGPU(SpvBuiltIn label) { - switch (label) { - case SpvBuiltInPosition: - case SpvBuiltInVertexIndex: - case SpvBuiltInInstanceIndex: - case SpvBuiltInFrontFacing: - case SpvBuiltInFragCoord: - case SpvBuiltInFragDepth: - case SpvBuiltInNumWorkgroups: - case SpvBuiltInWorkgroupSize: - case SpvBuiltInLocalInvocationId: - case SpvBuiltInGlobalInvocationId: - case SpvBuiltInLocalInvocationIndex: { - return true; +typedef enum VUIDError_ { + VUIDErrorExecutionModel = 0, + VUIDErrorStorageClass = 1, + VUIDErrorType = 2, + VUIDErrorMax, +} VUIDError; + +const static uint32_t NumVUIDBuiltins = 33; + +typedef struct { + SpvBuiltIn builtIn; + uint32_t vuid[VUIDErrorMax]; // execution mode, storage class, type VUIDs +} BuiltinVUIDMapping; + +std::array builtinVUIDInfo = {{ + // clang-format off + {SpvBuiltInSubgroupEqMask, {0, 4370, 4371}}, + {SpvBuiltInSubgroupGeMask, {0, 4372, 4373}}, + {SpvBuiltInSubgroupGtMask, {0, 4374, 4375}}, + {SpvBuiltInSubgroupLeMask, {0, 4376, 4377}}, + {SpvBuiltInSubgroupLtMask, {0, 4378, 4379}}, + {SpvBuiltInSubgroupLocalInvocationId, {0, 4380, 4381}}, + {SpvBuiltInSubgroupSize, {0, 4382, 4383}}, + {SpvBuiltInGlobalInvocationId, {4236, 4237, 4238}}, + {SpvBuiltInLocalInvocationId, {4281, 4282, 4283}}, + {SpvBuiltInNumWorkgroups, {4296, 4297, 4298}}, + {SpvBuiltInNumSubgroups, {4293, 4294, 4295}}, + {SpvBuiltInSubgroupId, {4367, 4368, 4369}}, + {SpvBuiltInWorkgroupId, {4422, 4423, 4424}}, + {SpvBuiltInHitKindKHR, {4242, 4243, 4244}}, + {SpvBuiltInHitTNV, {4245, 4246, 4247}}, + {SpvBuiltInInstanceCustomIndexKHR, {4251, 4252, 4253}}, + {SpvBuiltInInstanceId, {4254, 4255, 4256}}, + {SpvBuiltInRayGeometryIndexKHR, {4345, 4346, 4347}}, + {SpvBuiltInObjectRayDirectionKHR, {4299, 4300, 4301}}, + {SpvBuiltInObjectRayOriginKHR, {4302, 4303, 4304}}, + {SpvBuiltInObjectToWorldKHR, {4305, 4306, 4307}}, + {SpvBuiltInWorldToObjectKHR, {4434, 4435, 4436}}, + {SpvBuiltInIncomingRayFlagsKHR, {4248, 4249, 4250}}, + {SpvBuiltInRayTminKHR, {4351, 4352, 4353}}, + {SpvBuiltInRayTmaxKHR, {4348, 4349, 4350}}, + {SpvBuiltInWorldRayDirectionKHR, {4428, 4429, 4430}}, + {SpvBuiltInWorldRayOriginKHR, {4431, 4432, 4433}}, + {SpvBuiltInLaunchIdKHR, {4266, 4267, 4268}}, + {SpvBuiltInLaunchSizeKHR, {4269, 4270, 4271}}, + {SpvBuiltInFragInvocationCountEXT, {4217, 4218, 4219}}, + {SpvBuiltInFragSizeEXT, {4220, 4221, 4222}}, + {SpvBuiltInFragStencilRefEXT, {4223, 4224, 4225}}, + {SpvBuiltInFullyCoveredEXT, {4232, 4233, 4234}}, + // clang-format off +} }; + +uint32_t GetVUIDForBuiltin(SpvBuiltIn builtIn, VUIDError type) { + uint32_t vuid = 0; + for (const auto& iter: builtinVUIDInfo) { + if (iter.builtIn == builtIn) { + assert(type < VUIDErrorMax); + vuid = iter.vuid[type]; + break; } + } + return vuid; +} + +bool IsExecutionModelValidForRtBuiltIn(SpvBuiltIn builtin, + SpvExecutionModel stage) { + switch (builtin) { + case SpvBuiltInHitKindKHR: + case SpvBuiltInHitTNV: + if (stage == SpvExecutionModelAnyHitKHR || + stage == SpvExecutionModelClosestHitKHR) { + return true; + } + break; + case SpvBuiltInInstanceCustomIndexKHR: + case SpvBuiltInInstanceId: + case SpvBuiltInRayGeometryIndexKHR: + case SpvBuiltInObjectRayDirectionKHR: + case SpvBuiltInObjectRayOriginKHR: + case SpvBuiltInObjectToWorldKHR: + case SpvBuiltInWorldToObjectKHR: + switch (stage) { + case SpvExecutionModelIntersectionKHR: + case SpvExecutionModelAnyHitKHR: + case SpvExecutionModelClosestHitKHR: + return true; + default: + return false; + } + break; + case SpvBuiltInIncomingRayFlagsKHR: + case SpvBuiltInRayTminKHR: + case SpvBuiltInRayTmaxKHR: + case SpvBuiltInWorldRayDirectionKHR: + case SpvBuiltInWorldRayOriginKHR: + switch (stage) { + case SpvExecutionModelIntersectionKHR: + case SpvExecutionModelAnyHitKHR: + case SpvExecutionModelClosestHitKHR: + case SpvExecutionModelMissKHR: + return true; + default: + return false; + } + break; + case SpvBuiltInLaunchIdKHR: + case SpvBuiltInLaunchSizeKHR: + switch (stage) { + case SpvExecutionModelRayGenerationKHR: + case SpvExecutionModelIntersectionKHR: + case SpvExecutionModelAnyHitKHR: + case SpvExecutionModelClosestHitKHR: + case SpvExecutionModelMissKHR: + case SpvExecutionModelCallableKHR: + return true; + default: + return false; + } + break; default: break; } - return false; } @@ -200,8 +304,8 @@ class BuiltInsValidator { const Instruction& inst); spv_result_t ValidateVertexIndexAtDefinition(const Decoration& decoration, const Instruction& inst); - spv_result_t ValidateVertexIdOrInstanceIdAtDefinition( - const Decoration& decoration, const Instruction& inst); + spv_result_t ValidateVertexIdAtDefinition(const Decoration& decoration, + const Instruction& inst); spv_result_t ValidateLocalInvocationIndexAtDefinition( const Decoration& decoration, const Instruction& inst); spv_result_t ValidateWorkgroupSizeAtDefinition(const Decoration& decoration, @@ -214,6 +318,14 @@ class BuiltInsValidator { const Instruction& inst); spv_result_t ValidateDeviceIndexAtDefinition(const Decoration& decoration, const Instruction& inst); + spv_result_t ValidateFragInvocationCountAtDefinition(const Decoration& decoration, + const Instruction& inst); + spv_result_t ValidateFragSizeAtDefinition(const Decoration& decoration, + const Instruction& inst); + spv_result_t ValidateFragStencilRefAtDefinition(const Decoration& decoration, + const Instruction& inst); + spv_result_t ValidateFullyCoveredAtDefinition(const Decoration& decoration, + const Instruction& inst); // Used for GlobalInvocationId, LocalInvocationId, NumWorkgroups, WorkgroupId. spv_result_t ValidateComputeShaderI32Vec3InputAtDefinition( const Decoration& decoration, const Instruction& inst); @@ -237,6 +349,9 @@ class BuiltInsValidator { spv_result_t ValidateShadingRateAtDefinition(const Decoration& decoration, const Instruction& inst); + spv_result_t ValidateRayTracingBuiltinsAtDefinition( + const Decoration& decoration, const Instruction& inst); + // The following section contains functions which are called when id defined // by |referenced_inst| is // 1. referenced by |referenced_from_inst| @@ -269,11 +384,6 @@ class BuiltInsValidator { const Instruction& referenced_inst, const Instruction& referenced_from_inst); - spv_result_t ValidateInstanceIdAtReference( - const Decoration& decoration, const Instruction& built_in_inst, - const Instruction& referenced_inst, - const Instruction& referenced_from_inst); - spv_result_t ValidateInstanceIndexAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, @@ -374,6 +484,26 @@ class BuiltInsValidator { const Instruction& referenced_inst, const Instruction& referenced_from_inst); + spv_result_t ValidateFragInvocationCountAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst); + + spv_result_t ValidateFragSizeAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst); + + spv_result_t ValidateFragStencilRefAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst); + + spv_result_t ValidateFullyCoveredAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst); + // Used for GlobalInvocationId, LocalInvocationId, NumWorkgroups, WorkgroupId. spv_result_t ValidateComputeShaderI32Vec3InputAtReference( const Decoration& decoration, const Instruction& built_in_inst, @@ -400,9 +530,15 @@ class BuiltInsValidator { const Instruction& referenced_inst, const Instruction& referenced_from_inst); + spv_result_t ValidateRayTracingBuiltinsAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst); + // Validates that |built_in_inst| is not (even indirectly) referenced from // within a function which can be called with |execution_model|. // + // |vuid| - Vulkan ID for the error, or a negative value if none. // |comment| - text explaining why the restriction was imposed. // |decoration| - BuiltIn decoration which causes the restriction. // |referenced_inst| - instruction which is dependent on |built_in_inst| and @@ -410,7 +546,7 @@ class BuiltInsValidator { // |referenced_from_inst| - instruction which references id defined by // |referenced_inst| from within a function. spv_result_t ValidateNotCalledWithExecutionModel( - std::string comment, SpvExecutionModel execution_model, + int vuid, const char* comment, SpvExecutionModel execution_model, const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst); @@ -421,6 +557,9 @@ class BuiltInsValidator { spv_result_t ValidateBool( const Decoration& decoration, const Instruction& inst, const std::function& diag); + spv_result_t ValidateI( + const Decoration& decoration, const Instruction& inst, + const std::function& diag); spv_result_t ValidateI32( const Decoration& decoration, const Instruction& inst, const std::function& diag); @@ -475,6 +614,10 @@ class BuiltInsValidator { uint32_t num_components, const std::function& diag, uint32_t underlying_type); + spv_result_t ValidateF32Mat( + const Decoration& decoration, const Instruction& inst, + uint32_t req_num_rows, uint32_t req_num_columns, + const std::function& diag); // Generates strings like "Member #0 of struct ID <2>". std::string GetDefinitionDesc(const Decoration& decoration, @@ -609,6 +752,22 @@ spv_result_t BuiltInsValidator::ValidateBool( return SPV_SUCCESS; } +spv_result_t BuiltInsValidator::ValidateI( + const Decoration& decoration, const Instruction& inst, + const std::function& diag) { + uint32_t underlying_type = 0; + if (spv_result_t error = + GetUnderlyingType(_, decoration, inst, &underlying_type)) { + return error; + } + + if (!_.IsIntScalarType(underlying_type)) { + return diag(GetDefinitionDesc(decoration, inst) + " is not an int scalar."); + } + + return SPV_SUCCESS; +} + spv_result_t BuiltInsValidator::ValidateI32( const Decoration& decoration, const Instruction& inst, const std::function& diag) { @@ -908,8 +1067,34 @@ spv_result_t BuiltInsValidator::ValidateF32ArrHelper( return SPV_SUCCESS; } +spv_result_t BuiltInsValidator::ValidateF32Mat( + const Decoration& decoration, const Instruction& inst, + uint32_t req_num_rows, uint32_t req_num_columns, + const std::function& diag) { + uint32_t underlying_type = 0; + uint32_t num_rows = 0; + uint32_t num_cols = 0; + uint32_t col_type = 0; + uint32_t component_type = 0; + if (spv_result_t error = + GetUnderlyingType(_, decoration, inst, &underlying_type)) { + return error; + } + if (!_.GetMatrixTypeInfo(underlying_type, &num_rows, &num_cols, &col_type, + &component_type) || + num_rows != req_num_rows || num_cols != req_num_columns) { + std::ostringstream ss; + ss << GetDefinitionDesc(decoration, inst) << " has columns " << num_cols + << " and rows " << num_rows << " not equal to expected " + << req_num_columns << "x" << req_num_rows << "."; + return diag(ss.str()); + } + + return ValidateF32VecHelper(decoration, inst, req_num_rows, diag, col_type); +} + spv_result_t BuiltInsValidator::ValidateNotCalledWithExecutionModel( - std::string comment, SpvExecutionModel execution_model, + int vuid, const char* comment, SpvExecutionModel execution_model, const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { @@ -920,7 +1105,8 @@ spv_result_t BuiltInsValidator::ValidateNotCalledWithExecutionModel( const char* built_in_str = _.grammar().lookupOperandName( SPV_OPERAND_TYPE_BUILT_IN, decoration.params()[0]); return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << comment << " " << GetIdDesc(referenced_inst) << " depends on " + << (vuid < 0 ? std::string("") : _.VkErrorID(vuid)) << comment + << " " << GetIdDesc(referenced_inst) << " depends on " << GetIdDesc(built_in_inst) << " which is decorated with BuiltIn " << built_in_str << "." << " Id <" << referenced_inst.id() << "> is later referenced by " @@ -932,7 +1118,7 @@ spv_result_t BuiltInsValidator::ValidateNotCalledWithExecutionModel( // Propagate this rule to all dependant ids in the global scope. id_to_at_reference_checks_[referenced_from_inst.id()].push_back( std::bind(&BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - comment, execution_model, decoration, built_in_inst, + vuid, comment, execution_model, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); } return SPV_SUCCESS; @@ -954,8 +1140,9 @@ spv_result_t BuiltInsValidator::ValidateClipOrCullDistanceAtReference( if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput && storage_class != SpvStorageClassOutput) { + uint32_t vuid = (decoration.params()[0] == SpvBuiltInClipDistance) ? 4190 : 4199; return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "Vulkan spec allows BuiltIn " + << _.VkErrorID(vuid) << "Vulkan spec allows BuiltIn " << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, operand) << " to be only used for variables with Input or Output storage " @@ -967,19 +1154,28 @@ spv_result_t BuiltInsValidator::ValidateClipOrCullDistanceAtReference( if (storage_class == SpvStorageClassInput) { assert(function_id_ == 0); + uint32_t vuid = (decoration.params()[0] == SpvBuiltInClipDistance) ? 4188 : 4197; id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, vuid, "Vulkan spec doesn't allow BuiltIn ClipDistance/CullDistance to be " "used for variables with Input storage class if execution model is " "Vertex.", SpvExecutionModelVertex, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, vuid, + "Vulkan spec doesn't allow BuiltIn ClipDistance/CullDistance to be " + "used for variables with Input storage class if execution model is " + "Vertex.", + SpvExecutionModelMeshNV, decoration, built_in_inst, + referenced_from_inst, std::placeholders::_1)); } if (storage_class == SpvStorageClassOutput) { assert(function_id_ == 0); + uint32_t vuid = (decoration.params()[0] == SpvBuiltInClipDistance) ? 4189 : 4198; id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, vuid, "Vulkan spec doesn't allow BuiltIn ClipDistance/CullDistance to be " "used for variables with Output storage class if execution model is " "Fragment.", @@ -1093,7 +1289,7 @@ spv_result_t BuiltInsValidator::ValidateClipOrCullDistanceAtReference( spv_result_t BuiltInsValidator::ValidateFragCoordAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (spv_result_t error = ValidateF32Vec( decoration, inst, 4, [this, &inst](const std::string& message) -> spv_result_t { @@ -1117,7 +1313,7 @@ spv_result_t BuiltInsValidator::ValidateFragCoordAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { @@ -1155,7 +1351,7 @@ spv_result_t BuiltInsValidator::ValidateFragCoordAtReference( spv_result_t BuiltInsValidator::ValidateFragDepthAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (spv_result_t error = ValidateF32( decoration, inst, [this, &inst](const std::string& message) -> spv_result_t { @@ -1178,7 +1374,7 @@ spv_result_t BuiltInsValidator::ValidateFragDepthAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassOutput) { @@ -1231,7 +1427,7 @@ spv_result_t BuiltInsValidator::ValidateFragDepthAtReference( spv_result_t BuiltInsValidator::ValidateFrontFacingAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (spv_result_t error = ValidateBool( decoration, inst, [this, &inst](const std::string& message) -> spv_result_t { @@ -1254,7 +1450,7 @@ spv_result_t BuiltInsValidator::ValidateFrontFacingAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { @@ -1412,7 +1608,7 @@ spv_result_t BuiltInsValidator::ValidateInvocationIdAtReference( spv_result_t BuiltInsValidator::ValidateInstanceIndexAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (spv_result_t error = ValidateI32( decoration, inst, [this, &inst](const std::string& message) -> spv_result_t { @@ -1435,7 +1631,7 @@ spv_result_t BuiltInsValidator::ValidateInstanceIndexAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { @@ -1619,12 +1815,10 @@ spv_result_t BuiltInsValidator::ValidatePointSizeAtReference( if (storage_class == SpvStorageClassInput) { assert(function_id_ == 0); id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string( - _.VkErrorID(4315) + - "Vulkan spec doesn't allow BuiltIn PointSize to be used for " - "variables with Input storage class if execution model is " - "Vertex."), + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4315, + "Vulkan spec doesn't allow BuiltIn PointSize to be used for " + "variables with Input storage class if execution model is " + "Vertex.", SpvExecutionModelVertex, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); } @@ -1727,7 +1921,7 @@ spv_result_t BuiltInsValidator::ValidatePositionAtReference( storage_class != SpvStorageClassInput && storage_class != SpvStorageClassOutput) { return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "Vulkan spec allows BuiltIn Position to be only used for " + << _.VkErrorID(4320) << "Vulkan spec allows BuiltIn Position to be only used for " "variables with Input or Output storage class. " << GetReferenceDesc(decoration, built_in_inst, referenced_inst, referenced_from_inst) @@ -1737,13 +1931,19 @@ spv_result_t BuiltInsValidator::ValidatePositionAtReference( if (storage_class == SpvStorageClassInput) { assert(function_id_ == 0); id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string(_.VkErrorID(4320) + - "Vulkan spec doesn't allow BuiltIn Position to be used " - "for variables " - "with Input storage class if execution model is Vertex."), + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4319, + "Vulkan spec doesn't allow BuiltIn Position to be used " + "for variables " + "with Input storage class if execution model is Vertex.", SpvExecutionModelVertex, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4319, + "Vulkan spec doesn't allow BuiltIn Position to be used " + "for variables " + "with Input storage class if execution model is MeshNV.", + SpvExecutionModelMeshNV, decoration, built_in_inst, + referenced_from_inst, std::placeholders::_1)); } for (const SpvExecutionModel execution_model : execution_models_) { @@ -1821,46 +2021,6 @@ spv_result_t BuiltInsValidator::ValidatePositionAtReference( } } - if (spvIsWebGPUEnv(_.context()->target_env)) { - const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); - if (storage_class != SpvStorageClassMax && - storage_class != SpvStorageClassOutput) { - return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "WebGPU spec allows BuiltIn Position to be only used for " - "variables with Output storage class. " - << GetReferenceDesc(decoration, built_in_inst, referenced_inst, - referenced_from_inst) - << " " << GetStorageClassDesc(referenced_from_inst); - } - - for (const SpvExecutionModel execution_model : execution_models_) { - switch (execution_model) { - case SpvExecutionModelVertex: { - if (spv_result_t error = ValidateF32Vec( - decoration, built_in_inst, 4, - [this, &referenced_from_inst]( - const std::string& message) -> spv_result_t { - return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "According to the WebGPU spec BuiltIn Position " - "variable needs to be a 4-component 32-bit float " - "vector. " - << message; - })) { - return error; - } - break; - } - default: { - return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "WebGPU spec allows BuiltIn Position to be used only " - "with the Vertex execution model. " - << GetReferenceDesc(decoration, built_in_inst, referenced_inst, - referenced_from_inst, execution_model); - } - } - } - } - if (function_id_ == 0) { // Propagate this rule to all dependant ids in the global scope. id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( @@ -1928,32 +2088,47 @@ spv_result_t BuiltInsValidator::ValidatePrimitiveIdAtReference( if (storage_class == SpvStorageClassOutput) { assert(function_id_ == 0); id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string( - _.VkErrorID(4334) + - "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " - "variables with Output storage class if execution model is " - "TessellationControl."), + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4334, + "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " + "variables with Output storage class if execution model is " + "TessellationControl.", SpvExecutionModelTessellationControl, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string( - _.VkErrorID(4334) + - "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " - "variables with Output storage class if execution model is " - "TessellationEvaluation."), + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4334, + "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " + "variables with Output storage class if execution model is " + "TessellationEvaluation.", SpvExecutionModelTessellationEvaluation, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string( - _.VkErrorID(4334) + - "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " - "variables with Output storage class if execution model is " - "Fragment."), + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4334, + "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " + "variables with Output storage class if execution model is " + "Fragment.", SpvExecutionModelFragment, decoration, built_in_inst, referenced_from_inst, std::placeholders::_1)); + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4334, + "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " + "variables with Output storage class if execution model is " + "IntersectionKHR.", + SpvExecutionModelIntersectionKHR, decoration, built_in_inst, + referenced_from_inst, std::placeholders::_1)); + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4334, + "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " + "variables with Output storage class if execution model is " + "AnyHitKHR.", + SpvExecutionModelAnyHitKHR, decoration, built_in_inst, + referenced_from_inst, std::placeholders::_1)); + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, 4334, + "Vulkan spec doesn't allow BuiltIn PrimitiveId to be used for " + "variables with Output storage class if execution model is " + "ClosestHitKHR.", + SpvExecutionModelClosestHitKHR, decoration, built_in_inst, + referenced_from_inst, std::placeholders::_1)); } for (const SpvExecutionModel execution_model : execution_models_) { @@ -1963,12 +2138,9 @@ spv_result_t BuiltInsValidator::ValidatePrimitiveIdAtReference( case SpvExecutionModelTessellationEvaluation: case SpvExecutionModelGeometry: case SpvExecutionModelMeshNV: - case SpvExecutionModelRayGenerationNV: - case SpvExecutionModelIntersectionNV: - case SpvExecutionModelAnyHitNV: - case SpvExecutionModelClosestHitNV: - case SpvExecutionModelMissNV: - case SpvExecutionModelCallableNV: { + case SpvExecutionModelIntersectionKHR: + case SpvExecutionModelAnyHitKHR: + case SpvExecutionModelClosestHitKHR: { // Ok. break; } @@ -1978,7 +2150,9 @@ spv_result_t BuiltInsValidator::ValidatePrimitiveIdAtReference( << _.VkErrorID(4330) << "Vulkan spec allows BuiltIn PrimitiveId to be used only " "with Fragment, TessellationControl, " - "TessellationEvaluation or Geometry execution models. " + "TessellationEvaluation, Geometry, MeshNV, " + "IntersectionKHR, " + "AnyHitKHR, and ClosestHitKHR execution models. " << GetReferenceDesc(decoration, built_in_inst, referenced_inst, referenced_from_inst, execution_model); } @@ -2303,8 +2477,9 @@ spv_result_t BuiltInsValidator::ValidateTessLevelAtReference( if (storage_class == SpvStorageClassInput) { assert(function_id_ == 0); + uint32_t vuid = (decoration.params()[0] == SpvBuiltInTessLevelOuter) ? 4391 : 4395; id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, vuid, "Vulkan spec doesn't allow TessLevelOuter/TessLevelInner to be " "used " "for variables with Input storage class if execution model is " @@ -2315,8 +2490,9 @@ spv_result_t BuiltInsValidator::ValidateTessLevelAtReference( if (storage_class == SpvStorageClassOutput) { assert(function_id_ == 0); + uint32_t vuid = (decoration.params()[0] == SpvBuiltInTessLevelOuter) ? 4392 : 4396; id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, + &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, vuid, "Vulkan spec doesn't allow TessLevelOuter/TessLevelInner to be " "used " "for variables with Output storage class if execution model is " @@ -2360,7 +2536,7 @@ spv_result_t BuiltInsValidator::ValidateTessLevelAtReference( spv_result_t BuiltInsValidator::ValidateVertexIndexAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (spv_result_t error = ValidateI32( decoration, inst, [this, &inst](const std::string& message) -> spv_result_t { @@ -2379,55 +2555,13 @@ spv_result_t BuiltInsValidator::ValidateVertexIndexAtDefinition( return ValidateVertexIndexAtReference(decoration, inst, inst, inst); } -spv_result_t BuiltInsValidator::ValidateVertexIdOrInstanceIdAtDefinition( +spv_result_t BuiltInsValidator::ValidateVertexIdAtDefinition( const Decoration& decoration, const Instruction& inst) { - const SpvBuiltIn label = SpvBuiltIn(decoration.params()[0]); - bool allow_instance_id = - (_.HasCapability(SpvCapabilityRayTracingNV) || - _.HasCapability(SpvCapabilityRayTracingProvisionalKHR)) && - label == SpvBuiltInInstanceId; - - if (spvIsVulkanEnv(_.context()->target_env) && !allow_instance_id) { - return _.diag(SPV_ERROR_INVALID_DATA, &inst) - << "Vulkan spec doesn't allow BuiltIn VertexId/InstanceId " - "to be used."; - } - - if (label == SpvBuiltInInstanceId) { - return ValidateInstanceIdAtReference(decoration, inst, inst, inst); - } - return SPV_SUCCESS; -} - -spv_result_t BuiltInsValidator::ValidateInstanceIdAtReference( - const Decoration& decoration, const Instruction& built_in_inst, - const Instruction& referenced_inst, - const Instruction& referenced_from_inst) { + (void)decoration; if (spvIsVulkanEnv(_.context()->target_env)) { - for (const SpvExecutionModel execution_model : execution_models_) { - switch (execution_model) { - case SpvExecutionModelIntersectionNV: - case SpvExecutionModelClosestHitNV: - case SpvExecutionModelAnyHitNV: - // Do nothing, valid stages - break; - default: - return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "Vulkan spec allows BuiltIn InstanceId to be used " - "only with IntersectionNV, ClosestHitNV and AnyHitNV " - "execution models. " - << GetReferenceDesc(decoration, built_in_inst, referenced_inst, - referenced_from_inst); - break; - } - } - } - - if (function_id_ == 0) { - // Propagate this rule to all dependant ids in the global scope. - id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateInstanceIdAtReference, this, decoration, - built_in_inst, referenced_from_inst, std::placeholders::_1)); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << "Vulkan spec doesn't allow BuiltIn VertexId " + "to be used."; } return SPV_SUCCESS; @@ -2435,51 +2569,14 @@ spv_result_t BuiltInsValidator::ValidateInstanceIdAtReference( spv_result_t BuiltInsValidator::ValidateLocalInvocationIndexAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsWebGPUEnv(_.context()->target_env)) { - if (spv_result_t error = ValidateI32( - decoration, inst, - [this, &inst](const std::string& message) -> spv_result_t { - return _.diag(SPV_ERROR_INVALID_DATA, &inst) - << "According to the WebGPU spec BuiltIn " - "LocalInvocationIndex variable needs to be a 32-bit " - "int." - << message; - })) { - return error; - } - } - // Seed at reference checks with this built-in. return ValidateLocalInvocationIndexAtReference(decoration, inst, inst, inst); } spv_result_t BuiltInsValidator::ValidateLocalInvocationIndexAtReference( const Decoration& decoration, const Instruction& built_in_inst, - const Instruction& referenced_inst, + const Instruction&, const Instruction& referenced_from_inst) { - if (spvIsWebGPUEnv(_.context()->target_env)) { - const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); - if (storage_class != SpvStorageClassMax && - storage_class != SpvStorageClassInput) { - return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "WebGPU spec allows BuiltIn LocalInvocationIndex to be only " - "used for variables with Input storage class. " - << GetReferenceDesc(decoration, built_in_inst, referenced_inst, - referenced_from_inst) - << " " << GetStorageClassDesc(referenced_from_inst); - } - - for (const SpvExecutionModel execution_model : execution_models_) { - if (execution_model != SpvExecutionModelGLCompute) { - return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "WebGPU spec allows BuiltIn VertexIndex to be used only " - "with GLCompute execution model. " - << GetReferenceDesc(decoration, built_in_inst, referenced_inst, - referenced_from_inst, execution_model); - } - } - } - if (function_id_ == 0) { // Propagate this rule to all dependant ids in the global scope. id_to_at_reference_checks_[referenced_from_inst.id()].push_back( @@ -2495,7 +2592,7 @@ spv_result_t BuiltInsValidator::ValidateVertexIndexAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { @@ -2605,32 +2702,30 @@ spv_result_t BuiltInsValidator::ValidateLayerOrViewportIndexAtReference( {SpvExecutionModelVertex, SpvExecutionModelTessellationEvaluation, SpvExecutionModelGeometry, SpvExecutionModelMeshNV}) { id_to_at_reference_checks_[referenced_from_inst.id()].push_back( - std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string( - _.VkErrorID((operand == SpvBuiltInLayer) ? 4274 : 4406) + - "Vulkan spec doesn't allow BuiltIn Layer and " - "ViewportIndex to be " - "used for variables with Input storage class if " - "execution model is Vertex, TessellationEvaluation, " - "Geometry, or MeshNV."), - em, decoration, built_in_inst, referenced_from_inst, - std::placeholders::_1)); + std::bind(&BuiltInsValidator::ValidateNotCalledWithExecutionModel, + this, ((operand == SpvBuiltInLayer) ? 4274 : 4406), + "Vulkan spec doesn't allow BuiltIn Layer and " + "ViewportIndex to be " + "used for variables with Input storage class if " + "execution model is Vertex, TessellationEvaluation, " + "Geometry, or MeshNV.", + em, decoration, built_in_inst, referenced_from_inst, + std::placeholders::_1)); } } if (storage_class == SpvStorageClassOutput) { assert(function_id_ == 0); - id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( - &BuiltInsValidator::ValidateNotCalledWithExecutionModel, this, - std::string(_.VkErrorID((operand == SpvBuiltInLayer) ? 4275 : 4407) + - "Vulkan spec doesn't allow BuiltIn Layer and " - "ViewportIndex to be " - "used for variables with Output storage class if " - "execution model is " - "Fragment."), - SpvExecutionModelFragment, decoration, built_in_inst, - referenced_from_inst, std::placeholders::_1)); + id_to_at_reference_checks_[referenced_from_inst.id()].push_back( + std::bind(&BuiltInsValidator::ValidateNotCalledWithExecutionModel, + this, ((operand == SpvBuiltInLayer) ? 4275 : 4407), + "Vulkan spec doesn't allow BuiltIn Layer and " + "ViewportIndex to be " + "used for variables with Output storage class if " + "execution model is " + "Fragment.", + SpvExecutionModelFragment, decoration, built_in_inst, + referenced_from_inst, std::placeholders::_1)); } for (const SpvExecutionModel execution_model : execution_models_) { @@ -2657,8 +2752,9 @@ spv_result_t BuiltInsValidator::ValidateLayerOrViewportIndexAtReference( if (operand == SpvBuiltInLayer) capability = "ShaderViewportIndexLayerEXT or ShaderLayer"; + uint32_t vuid = (operand == SpvBuiltInLayer) ? 4273 : 4405; return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) - << "Using BuiltIn " + << _.VkErrorID(vuid) << "Using BuiltIn " << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, operand) << " in Vertex or Tessellation execution model requires the " @@ -2694,33 +2790,18 @@ spv_result_t BuiltInsValidator::ValidateLayerOrViewportIndexAtReference( spv_result_t BuiltInsValidator::ValidateComputeShaderI32Vec3InputAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); if (spv_result_t error = ValidateI32Vec( decoration, inst, 3, - [this, &decoration, - &inst](const std::string& message) -> spv_result_t { - uint32_t operand = decoration.params()[0]; - uint32_t vuid = 0; - switch (operand) { - case SpvBuiltInGlobalInvocationId: - vuid = 4238; - break; - case SpvBuiltInLocalInvocationId: - vuid = 4283; - break; - case SpvBuiltInNumWorkgroups: - vuid = 4298; - break; - case SpvBuiltInWorkgroupId: - vuid = 4424; - break; - }; + [this, &inst, builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); return _.diag(SPV_ERROR_INVALID_DATA, &inst) << _.VkErrorID(vuid) << "According to the " << spvLogStringForEnv(_.context()->target_env) << " spec BuiltIn " << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - operand) + builtin) << " variable needs to be a 3-component 32-bit int " "vector. " << message; @@ -2738,31 +2819,16 @@ spv_result_t BuiltInsValidator::ValidateComputeShaderI32Vec3InputAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - uint32_t operand = decoration.params()[0]; - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { - uint32_t vuid = 0; - switch (operand) { - case SpvBuiltInGlobalInvocationId: - vuid = 4237; - break; - case SpvBuiltInLocalInvocationId: - vuid = 4282; - break; - case SpvBuiltInNumWorkgroups: - vuid = 4297; - break; - case SpvBuiltInWorkgroupId: - vuid = 4423; - break; - }; + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) << " spec allows BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " to be only used for variables with Input storage class. " << GetReferenceDesc(decoration, built_in_inst, referenced_inst, referenced_from_inst) @@ -2773,30 +2839,13 @@ spv_result_t BuiltInsValidator::ValidateComputeShaderI32Vec3InputAtReference( bool has_vulkan_model = execution_model == SpvExecutionModelGLCompute || execution_model == SpvExecutionModelTaskNV || execution_model == SpvExecutionModelMeshNV; - bool has_webgpu_model = execution_model == SpvExecutionModelGLCompute; - if ((spvIsVulkanEnv(_.context()->target_env) && !has_vulkan_model) || - (spvIsWebGPUEnv(_.context()->target_env) && !has_webgpu_model)) { - uint32_t vuid = 0; - switch (operand) { - case SpvBuiltInGlobalInvocationId: - vuid = 4236; - break; - case SpvBuiltInLocalInvocationId: - vuid = 4281; - break; - case SpvBuiltInNumWorkgroups: - vuid = 4296; - break; - case SpvBuiltInWorkgroupId: - vuid = 4422; - break; - }; + if (spvIsVulkanEnv(_.context()->target_env) && !has_vulkan_model) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) << " spec allows BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " to be used only with GLCompute execution model. " << GetReferenceDesc(decoration, built_in_inst, referenced_inst, referenced_from_inst, execution_model); @@ -2818,23 +2867,23 @@ spv_result_t BuiltInsValidator::ValidateComputeShaderI32Vec3InputAtReference( spv_result_t BuiltInsValidator::ValidateComputeI32InputAtDefinition( const Decoration& decoration, const Instruction& inst) { if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); if (decoration.struct_member_index() != Decoration::kInvalidMember) { return _.diag(SPV_ERROR_INVALID_DATA, &inst) << "BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " cannot be used as a member decoration "; } if (spv_result_t error = ValidateI32( decoration, inst, - [this, &decoration, - &inst](const std::string& message) -> spv_result_t { + [this, &inst, builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " << spvLogStringForEnv(_.context()->target_env) << " spec BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " variable needs to be a 32-bit int " "vector. " << message; @@ -2852,14 +2901,16 @@ spv_result_t BuiltInsValidator::ValidateComputeI32InputAtReference( const Instruction& referenced_inst, const Instruction& referenced_from_inst) { if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) << " spec allows BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " to be only used for variables with Input storage class. " << GetReferenceDesc(decoration, built_in_inst, referenced_inst, referenced_from_inst) @@ -2871,11 +2922,12 @@ spv_result_t BuiltInsValidator::ValidateComputeI32InputAtReference( execution_model == SpvExecutionModelTaskNV || execution_model == SpvExecutionModelMeshNV; if (spvIsVulkanEnv(_.context()->target_env) && !has_vulkan_model) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) << " spec allows BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " to be used only with GLCompute execution model. " << GetReferenceDesc(decoration, built_in_inst, referenced_inst, referenced_from_inst, execution_model); @@ -2897,23 +2949,23 @@ spv_result_t BuiltInsValidator::ValidateComputeI32InputAtReference( spv_result_t BuiltInsValidator::ValidateI32InputAtDefinition( const Decoration& decoration, const Instruction& inst) { if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); if (decoration.struct_member_index() != Decoration::kInvalidMember) { return _.diag(SPV_ERROR_INVALID_DATA, &inst) << "BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " cannot be used as a member decoration "; } if (spv_result_t error = ValidateI32( decoration, inst, - [this, &decoration, - &inst](const std::string& message) -> spv_result_t { + [this, &inst, builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " << spvLogStringForEnv(_.context()->target_env) << " spec BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " variable needs to be a 32-bit int. " << message; })) { return error; @@ -2922,11 +2974,12 @@ spv_result_t BuiltInsValidator::ValidateI32InputAtDefinition( const SpvStorageClass storage_class = GetStorageClass(inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) << " spec allows BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " to be only used for variables with Input storage class. " << GetReferenceDesc(decoration, inst, inst, inst) << " " << GetStorageClassDesc(inst); @@ -2939,23 +2992,23 @@ spv_result_t BuiltInsValidator::ValidateI32InputAtDefinition( spv_result_t BuiltInsValidator::ValidateI32Vec4InputAtDefinition( const Decoration& decoration, const Instruction& inst) { if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); if (decoration.struct_member_index() != Decoration::kInvalidMember) { return _.diag(SPV_ERROR_INVALID_DATA, &inst) << "BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " cannot be used as a member decoration "; } if (spv_result_t error = ValidateI32Vec( decoration, inst, 4, - [this, &decoration, - &inst](const std::string& message) -> spv_result_t { + [this, &inst, builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " << spvLogStringForEnv(_.context()->target_env) << " spec BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " variable needs to be a 4-component 32-bit int " "vector. " << message; @@ -2966,11 +3019,12 @@ spv_result_t BuiltInsValidator::ValidateI32Vec4InputAtDefinition( const SpvStorageClass storage_class = GetStorageClass(inst); if (storage_class != SpvStorageClassMax && storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) << " spec allows BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]) + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) << " to be only used for variables with Input storage class. " << GetReferenceDesc(decoration, inst, inst, inst) << " " << GetStorageClassDesc(inst); @@ -2982,7 +3036,7 @@ spv_result_t BuiltInsValidator::ValidateI32Vec4InputAtDefinition( spv_result_t BuiltInsValidator::ValidateWorkgroupSizeAtDefinition( const Decoration& decoration, const Instruction& inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { if (spvIsVulkanEnv(_.context()->target_env) && !spvOpcodeIsConstant(inst.opcode())) { return _.diag(SPV_ERROR_INVALID_DATA, &inst) @@ -3014,7 +3068,7 @@ spv_result_t BuiltInsValidator::ValidateWorkgroupSizeAtReference( const Decoration& decoration, const Instruction& built_in_inst, const Instruction& referenced_inst, const Instruction& referenced_from_inst) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { + if (spvIsVulkanEnv(_.context()->target_env)) { for (const SpvExecutionModel execution_model : execution_models_) { if (execution_model != SpvExecutionModelGLCompute) { return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) @@ -3293,6 +3347,287 @@ spv_result_t BuiltInsValidator::ValidateDeviceIndexAtReference( return SPV_SUCCESS; } +spv_result_t BuiltInsValidator::ValidateFragInvocationCountAtDefinition(const Decoration& decoration, + const Instruction& inst) { + + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + if (spv_result_t error = ValidateI32( + decoration, inst, + [this, &inst, &builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " + << spvLogStringForEnv(_.context()->target_env) + << " spec BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, + builtin) + << " variable needs to be a 32-bit int scalar. " + << message; + })) { + return error; + } + } + + return ValidateFragInvocationCountAtReference(decoration, inst, inst, inst); +} + +spv_result_t BuiltInsValidator::ValidateFragInvocationCountAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst) { + + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); + if (storage_class != SpvStorageClassMax && + storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be only used for variables with Input storage class. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst) + << " " << GetStorageClassDesc(referenced_from_inst); + } + + for (const SpvExecutionModel execution_model : execution_models_) { + if (execution_model != SpvExecutionModelFragment) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) + << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be used only with Fragment execution model. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst, execution_model); + } + } + } + + if (function_id_ == 0) { + // Propagate this rule to all dependant ids in the global scope. + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateFragInvocationCountAtReference, this, decoration, + built_in_inst, referenced_from_inst, std::placeholders::_1)); + } + + return SPV_SUCCESS; +} + +spv_result_t BuiltInsValidator::ValidateFragSizeAtDefinition(const Decoration& decoration, + const Instruction& inst) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + if (spv_result_t error = ValidateI32Vec( + decoration, inst, 2, + [this, &inst, &builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " + << spvLogStringForEnv(_.context()->target_env) + << " spec BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, + builtin) + << " variable needs to be a 2-component 32-bit int vector. " + << message; + })) { + return error; + } + } + + return ValidateFragSizeAtReference(decoration, inst, inst, inst); +} + +spv_result_t BuiltInsValidator::ValidateFragSizeAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst) { + + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); + if (storage_class != SpvStorageClassMax && + storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be only used for variables with Input storage class. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst) + << " " << GetStorageClassDesc(referenced_from_inst); + } + + for (const SpvExecutionModel execution_model : execution_models_) { + if (execution_model != SpvExecutionModelFragment) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) + << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be used only with Fragment execution model. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst, execution_model); + } + } + } + + if (function_id_ == 0) { + // Propagate this rule to all dependant ids in the global scope. + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateFragSizeAtReference, this, decoration, + built_in_inst, referenced_from_inst, std::placeholders::_1)); + } + + return SPV_SUCCESS; +} + +spv_result_t BuiltInsValidator::ValidateFragStencilRefAtDefinition(const Decoration& decoration, + const Instruction& inst) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + if (spv_result_t error = ValidateI( + decoration, inst, + [this, &inst, &builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " + << spvLogStringForEnv(_.context()->target_env) + << " spec BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, + builtin) + << " variable needs to be a int scalar. " + << message; + })) { + return error; + } + } + + return ValidateFragStencilRefAtReference(decoration, inst, inst, inst); +} + +spv_result_t BuiltInsValidator::ValidateFragStencilRefAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst) { + + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); + if (storage_class != SpvStorageClassMax && + storage_class != SpvStorageClassOutput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be only used for variables with Output storage class. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst) + << " " << GetStorageClassDesc(referenced_from_inst); + } + + for (const SpvExecutionModel execution_model : execution_models_) { + if (execution_model != SpvExecutionModelFragment) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) + << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be used only with Fragment execution model. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst, execution_model); + } + } + } + + if (function_id_ == 0) { + // Propagate this rule to all dependant ids in the global scope. + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateFragStencilRefAtReference, this, decoration, + built_in_inst, referenced_from_inst, std::placeholders::_1)); + } + + return SPV_SUCCESS; +} + +spv_result_t BuiltInsValidator::ValidateFullyCoveredAtDefinition(const Decoration& decoration, + const Instruction& inst) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + if (spv_result_t error = ValidateBool( + decoration, inst, + [this, &inst, &builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) << "According to the " + << spvLogStringForEnv(_.context()->target_env) + << " spec BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, + builtin) + << " variable needs to be a bool scalar. " + << message; + })) { + return error; + } + } + + return ValidateFullyCoveredAtReference(decoration, inst, inst, inst); +} + +spv_result_t BuiltInsValidator::ValidateFullyCoveredAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst) { + + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); + if (storage_class != SpvStorageClassMax && + storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be only used for variables with Input storage class. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst) + << " " << GetStorageClassDesc(referenced_from_inst); + } + + for (const SpvExecutionModel execution_model : execution_models_) { + if (execution_model != SpvExecutionModelFragment) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) + << spvLogStringForEnv(_.context()->target_env) + << " spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " to be used only with Fragment execution model. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst, execution_model); + } + } + } + + if (function_id_ == 0) { + // Propagate this rule to all dependant ids in the global scope. + id_to_at_reference_checks_[referenced_from_inst.id()].push_back(std::bind( + &BuiltInsValidator::ValidateFullyCoveredAtReference, this, decoration, + built_in_inst, referenced_from_inst, std::placeholders::_1)); + } + + return SPV_SUCCESS; +} + spv_result_t BuiltInsValidator::ValidateSMBuiltinsAtDefinition( const Decoration& decoration, const Instruction& inst) { if (spvIsVulkanEnv(_.context()->target_env)) { @@ -3484,6 +3819,174 @@ spv_result_t BuiltInsValidator::ValidateShadingRateAtReference( return SPV_SUCCESS; } +spv_result_t BuiltInsValidator::ValidateRayTracingBuiltinsAtDefinition( + const Decoration& decoration, const Instruction& inst) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + switch (builtin) { + case SpvBuiltInHitTNV: + case SpvBuiltInRayTminKHR: + case SpvBuiltInRayTmaxKHR: + // f32 scalar + if (spv_result_t error = ValidateF32( + decoration, inst, + [this, &inst, + builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) + << "According to the Vulkan spec BuiltIn " + << _.grammar().lookupOperandName( + SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " variable needs to be a 32-bit float scalar. " + << message; + })) { + return error; + } + break; + case SpvBuiltInHitKindKHR: + case SpvBuiltInInstanceCustomIndexKHR: + case SpvBuiltInInstanceId: + case SpvBuiltInRayGeometryIndexKHR: + case SpvBuiltInIncomingRayFlagsKHR: + // i32 scalar + if (spv_result_t error = ValidateI32( + decoration, inst, + [this, &inst, + builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) + << "According to the Vulkan spec BuiltIn " + << _.grammar().lookupOperandName( + SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " variable needs to be a 32-bit int scalar. " + << message; + })) { + return error; + } + break; + case SpvBuiltInObjectRayDirectionKHR: + case SpvBuiltInObjectRayOriginKHR: + case SpvBuiltInWorldRayDirectionKHR: + case SpvBuiltInWorldRayOriginKHR: + // f32 vec3 + if (spv_result_t error = ValidateF32Vec( + decoration, inst, 3, + [this, &inst, + builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) + << "According to the Vulkan spec BuiltIn " + << _.grammar().lookupOperandName( + SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " variable needs to be a 3-component 32-bit float " + "vector. " + << message; + })) { + return error; + } + break; + case SpvBuiltInLaunchIdKHR: + case SpvBuiltInLaunchSizeKHR: + // i32 vec3 + if (spv_result_t error = ValidateI32Vec( + decoration, inst, 3, + [this, &inst, + builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) + << "According to the Vulkan spec BuiltIn " + << _.grammar().lookupOperandName( + SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " variable needs to be a 3-component 32-bit int " + "vector. " + << message; + })) { + return error; + } + break; + case SpvBuiltInObjectToWorldKHR: + case SpvBuiltInWorldToObjectKHR: + // f32 mat4x3 + if (spv_result_t error = ValidateF32Mat( + decoration, inst, 3, 4, + [this, &inst, + builtin](const std::string& message) -> spv_result_t { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorType); + return _.diag(SPV_ERROR_INVALID_DATA, &inst) + << _.VkErrorID(vuid) + << "According to the Vulkan spec BuiltIn " + << _.grammar().lookupOperandName( + SPV_OPERAND_TYPE_BUILT_IN, builtin) + << " variable needs to be a matrix with" + << " 4 columns of 3-component vectors of 32-bit " + "floats. " + << message; + })) { + return error; + } + break; + default: + assert(0 && "Unexpected ray tracing builtin"); + break; + } + } + + // Seed at reference checks with this built-in. + return ValidateRayTracingBuiltinsAtReference(decoration, inst, inst, inst); +} + +spv_result_t BuiltInsValidator::ValidateRayTracingBuiltinsAtReference( + const Decoration& decoration, const Instruction& built_in_inst, + const Instruction& referenced_inst, + const Instruction& referenced_from_inst) { + if (spvIsVulkanEnv(_.context()->target_env)) { + const SpvBuiltIn builtin = SpvBuiltIn(decoration.params()[0]); + const SpvStorageClass storage_class = GetStorageClass(referenced_from_inst); + if (storage_class != SpvStorageClassMax && + storage_class != SpvStorageClassInput) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorStorageClass); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << "Vulkan spec allows BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, + decoration.params()[0]) + << " to be only used for variables with Input storage class. " + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst) + << " " << GetStorageClassDesc(referenced_from_inst); + } + + for (const SpvExecutionModel execution_model : execution_models_) { + if (!IsExecutionModelValidForRtBuiltIn(builtin, execution_model)) { + uint32_t vuid = GetVUIDForBuiltin(builtin, VUIDErrorExecutionModel); + return _.diag(SPV_ERROR_INVALID_DATA, &referenced_from_inst) + << _.VkErrorID(vuid) << "Vulkan spec does not allow BuiltIn " + << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, + decoration.params()[0]) + << " to be used with the execution model " + << _.grammar().lookupOperandName( + SPV_OPERAND_TYPE_EXECUTION_MODEL, execution_model) + << ".\n" + << GetReferenceDesc(decoration, built_in_inst, referenced_inst, + referenced_from_inst, execution_model); + } + } + } + + if (function_id_ == 0) { + // Propagate this rule to all dependant ids in the global scope. + id_to_at_reference_checks_[referenced_from_inst.id()].push_back( + std::bind(&BuiltInsValidator::ValidateRayTracingBuiltinsAtReference, + this, decoration, built_in_inst, referenced_from_inst, + std::placeholders::_1)); + } + + return SPV_SUCCESS; +} + spv_result_t BuiltInsValidator::ValidateSingleBuiltInAtDefinition( const Decoration& decoration, const Instruction& inst) { const SpvBuiltIn label = SpvBuiltIn(decoration.params()[0]); @@ -3496,26 +3999,17 @@ spv_result_t BuiltInsValidator::ValidateSingleBuiltInAtDefinition( << "BuiltIns can only target variables, structs or constants"; } - if (!spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { - // Early return. All currently implemented rules are based on Vulkan or - // WebGPU spec. + if (!spvIsVulkanEnv(_.context()->target_env)) { + // Early return. All currently implemented rules are based on Vulkan spec. // // TODO: If you are adding validation rules for environments other than - // Vulkan or WebGPU (or general rules which are not environment - // independent), then you need to modify or remove this condition. Consider - // also adding early returns into BuiltIn-specific rules, so that the system - // doesn't spawn new rules which don't do anything. + // Vulkan (or general rules which are not environment independent), then + // you need to modify or remove this condition. Consider also adding early + // returns into BuiltIn-specific rules, so that the system doesn't spawn new + // rules which don't do anything. return SPV_SUCCESS; } - if (spvIsWebGPUEnv(_.context()->target_env) && - !IsBuiltInValidForWebGPU(label)) { - return _.diag(SPV_ERROR_INVALID_DATA, &inst) - << "WebGPU does not allow BuiltIn " - << _.grammar().lookupOperandName(SPV_OPERAND_TYPE_BUILT_IN, - decoration.params()[0]); - } - // If you are adding a new BuiltIn enum, please register it here. // If the newly added enum has validation rules associated with it // consider leaving a TODO and/or creating an issue. @@ -3606,9 +4100,8 @@ spv_result_t BuiltInsValidator::ValidateSingleBuiltInAtDefinition( case SpvBuiltInWorkgroupSize: { return ValidateWorkgroupSizeAtDefinition(decoration, inst); } - case SpvBuiltInVertexId: - case SpvBuiltInInstanceId: { - return ValidateVertexIdOrInstanceIdAtDefinition(decoration, inst); + case SpvBuiltInVertexId: { + return ValidateVertexIdAtDefinition(decoration, inst); } case SpvBuiltInLocalInvocationIndex: { return ValidateLocalInvocationIndexAtDefinition(decoration, inst); @@ -3632,6 +4125,41 @@ spv_result_t BuiltInsValidator::ValidateSingleBuiltInAtDefinition( case SpvBuiltInDeviceIndex: { return ValidateDeviceIndexAtDefinition(decoration, inst); } + case SpvBuiltInFragInvocationCountEXT: { + // alias SpvBuiltInInvocationsPerPixelNV + return ValidateFragInvocationCountAtDefinition(decoration, inst); + } + case SpvBuiltInFragSizeEXT: { + // alias SpvBuiltInFragmentSizeNV + return ValidateFragSizeAtDefinition(decoration, inst); + } + case SpvBuiltInFragStencilRefEXT: { + return ValidateFragStencilRefAtDefinition(decoration, inst); + } + case SpvBuiltInFullyCoveredEXT:{ + return ValidateFullyCoveredAtDefinition(decoration, inst); + } + // Ray tracing builtins + case SpvBuiltInHitKindKHR: // alias SpvBuiltInHitKindNV + case SpvBuiltInHitTNV: // NOT present in KHR + case SpvBuiltInInstanceId: + case SpvBuiltInLaunchIdKHR: // alias SpvBuiltInLaunchIdNV + case SpvBuiltInLaunchSizeKHR: // alias SpvBuiltInLaunchSizeNV + case SpvBuiltInWorldRayOriginKHR: // alias SpvBuiltInWorldRayOriginNV + case SpvBuiltInWorldRayDirectionKHR: // alias SpvBuiltInWorldRayDirectionNV + case SpvBuiltInObjectRayOriginKHR: // alias SpvBuiltInObjectRayOriginNV + case SpvBuiltInObjectRayDirectionKHR: // alias + // SpvBuiltInObjectRayDirectionNV + case SpvBuiltInRayTminKHR: // alias SpvBuiltInRayTminNV + case SpvBuiltInRayTmaxKHR: // alias SpvBuiltInRayTmaxNV + case SpvBuiltInInstanceCustomIndexKHR: // alias + // SpvBuiltInInstanceCustomIndexNV + case SpvBuiltInObjectToWorldKHR: // alias SpvBuiltInObjectToWorldNV + case SpvBuiltInWorldToObjectKHR: // alias SpvBuiltInWorldToObjectNV + case SpvBuiltInIncomingRayFlagsKHR: // alias SpvBuiltInIncomingRayFlagsNV + case SpvBuiltInRayGeometryIndexKHR: { // NOT present in NV + return ValidateRayTracingBuiltinsAtDefinition(decoration, inst); + } case SpvBuiltInWorkDim: case SpvBuiltInGlobalSize: case SpvBuiltInEnqueuedWorkgroupSize: @@ -3646,13 +4174,11 @@ spv_result_t BuiltInsValidator::ValidateSingleBuiltInAtDefinition( case SpvBuiltInBaryCoordSmoothCentroidAMD: case SpvBuiltInBaryCoordSmoothSampleAMD: case SpvBuiltInBaryCoordPullModelAMD: - case SpvBuiltInFragStencilRefEXT: case SpvBuiltInViewportMaskNV: case SpvBuiltInSecondaryPositionNV: case SpvBuiltInSecondaryViewportMaskNV: case SpvBuiltInPositionPerViewNV: case SpvBuiltInViewportMaskPerViewNV: - case SpvBuiltInFullyCoveredEXT: case SpvBuiltInMax: case SpvBuiltInTaskCountNV: case SpvBuiltInPrimitiveCountNV: @@ -3664,31 +4190,14 @@ spv_result_t BuiltInsValidator::ValidateSingleBuiltInAtDefinition( case SpvBuiltInMeshViewIndicesNV: case SpvBuiltInBaryCoordNV: case SpvBuiltInBaryCoordNoPerspNV: - case SpvBuiltInFragmentSizeNV: // alias SpvBuiltInFragSizeEXT - case SpvBuiltInInvocationsPerPixelNV: // alias - // SpvBuiltInFragInvocationCountEXT - case SpvBuiltInLaunchIdNV: - case SpvBuiltInLaunchSizeNV: - case SpvBuiltInWorldRayOriginNV: - case SpvBuiltInWorldRayDirectionNV: - case SpvBuiltInObjectRayOriginNV: - case SpvBuiltInObjectRayDirectionNV: - case SpvBuiltInRayTminNV: - case SpvBuiltInRayTmaxNV: - case SpvBuiltInInstanceCustomIndexNV: - case SpvBuiltInObjectToWorldNV: - case SpvBuiltInWorldToObjectNV: - case SpvBuiltInHitTNV: - case SpvBuiltInHitKindNV: - case SpvBuiltInIncomingRayFlagsNV: - case SpvBuiltInRayGeometryIndexKHR: { // No validation rules (for the moment). break; - case SpvBuiltInPrimitiveShadingRateKHR: - return ValidatePrimitiveShadingRateAtDefinition(decoration, inst); - case SpvBuiltInShadingRateKHR: - return ValidateShadingRateAtDefinition(decoration, inst); + case SpvBuiltInPrimitiveShadingRateKHR: { + return ValidatePrimitiveShadingRateAtDefinition(decoration, inst); + } + case SpvBuiltInShadingRateKHR: { + return ValidateShadingRateAtDefinition(decoration, inst); } } return SPV_SUCCESS; diff --git a/third_party/spirv-tools/source/val/validate_capability.cpp b/third_party/spirv-tools/source/val/validate_capability.cpp index 4b98bc19c2..8efd55420d 100644 --- a/third_party/spirv-tools/source/val/validate_capability.cpp +++ b/third_party/spirv-tools/source/val/validate_capability.cpp @@ -260,19 +260,6 @@ bool IsEnabledByCapabilityOpenCL_2_0(ValidationState_t& _, return false; } -bool IsSupportGuaranteedWebGPU(uint32_t capability) { - switch (capability) { - case SpvCapabilityMatrix: - case SpvCapabilityShader: - case SpvCapabilitySampled1D: - case SpvCapabilityImage1D: - case SpvCapabilityDerivativeControl: - case SpvCapabilityImageQuery: - return true; - } - return false; -} - } // namespace // Validates that capability declarations use operands allowed in the current @@ -365,14 +352,6 @@ spv_result_t CapabilityPass(ValidationState_t& _, const Instruction* inst) { << " Profile specification" << " (or requires extension or capability)"; } - } else if (env == SPV_ENV_WEBGPU_0) { - if (!IsSupportGuaranteedWebGPU(capability) && - !IsEnabledByExtension(_, capability)) { - return _.diag(SPV_ERROR_INVALID_CAPABILITY, inst) - << "Capability " << capability_str() - << " is not allowed by WebGPU specification" - << " (or requires extension)"; - } } return SPV_SUCCESS; diff --git a/third_party/spirv-tools/source/val/validate_cfg.cpp b/third_party/spirv-tools/source/val/validate_cfg.cpp index 8babd355d1..36f632a8d8 100644 --- a/third_party/spirv-tools/source/val/validate_cfg.cpp +++ b/third_party/spirv-tools/source/val/validate_cfg.cpp @@ -48,11 +48,11 @@ spv_result_t ValidatePhi(ValidationState_t& _, const Instruction* inst) { "basic blocks."; } - const Instruction* type_inst = _.FindDef(inst->type_id()); - assert(type_inst); - - const SpvOp type_opcode = type_inst->opcode(); - if (type_opcode == SpvOpTypePointer && + if (_.IsVoidType(inst->type_id())) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "OpPhi must not have void result type"; + } + if (_.IsPointerType(inst->type_id()) && _.addressing_model() == SpvAddressingModelLogical) { if (!_.features().variable_pointers && !_.features().variable_pointers_storage_buffer) { @@ -62,6 +62,10 @@ spv_result_t ValidatePhi(ValidationState_t& _, const Instruction* inst) { } } + const Instruction* type_inst = _.FindDef(inst->type_id()); + assert(type_inst); + const SpvOp type_opcode = type_inst->opcode(); + if (!_.options()->before_hlsl_legalization) { if (type_opcode == SpvOpTypeSampledImage || (_.HasCapability(SpvCapabilityShader) && @@ -650,18 +654,15 @@ spv_result_t ValidateStructuredSelections( << "Selection must be structured"; } } else if (terminator->opcode() == SpvOpSwitch) { - uint32_t count = 0; - // Mark the targets as seen now, but only error out if this block was - // missing a merge instruction and there were multiple unseen labels. + if (!merge) { + return _.diag(SPV_ERROR_INVALID_CFG, terminator) + << "OpSwitch must be preceeded by an OpSelectionMerge " + "instruction"; + } + // Mark the targets as seen. for (uint32_t i = 1; i < terminator->operands().size(); i += 2) { const auto target = terminator->GetOperandAs(i); - if (seen.insert(target).second) { - count++; - } - } - if (!merge && count > 1) { - return _.diag(SPV_ERROR_INVALID_CFG, terminator) - << "Selection must be structured"; + seen.insert(target); } } } @@ -816,120 +817,6 @@ spv_result_t StructuredControlFlowChecks( return SPV_SUCCESS; } -spv_result_t PerformWebGPUCfgChecks(ValidationState_t& _, Function* function) { - for (auto& block : function->ordered_blocks()) { - if (block->reachable()) continue; - if (block->is_type(kBlockTypeMerge)) { - // 1. Find the referencing merge and confirm that it is reachable. - BasicBlock* merge_header = function->GetMergeHeader(block); - assert(merge_header != nullptr); - if (!merge_header->reachable()) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable merge-blocks must be referenced by " - "a reachable merge instruction."; - } - - // 2. Check that the only instructions are OpLabel and OpUnreachable. - auto* label_inst = block->label(); - auto* terminator_inst = block->terminator(); - assert(label_inst != nullptr); - assert(terminator_inst != nullptr); - - if (terminator_inst->opcode() != SpvOpUnreachable) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable merge-blocks must terminate with " - "OpUnreachable."; - } - - auto label_idx = label_inst - &_.ordered_instructions()[0]; - auto terminator_idx = terminator_inst - &_.ordered_instructions()[0]; - if (label_idx + 1 != terminator_idx) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable merge-blocks must only contain an " - "OpLabel and OpUnreachable instruction."; - } - - // 3. Use label instruction to confirm there is no uses by branches. - for (auto use : label_inst->uses()) { - const auto* use_inst = use.first; - if (spvOpcodeIsBranch(use_inst->opcode())) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable merge-blocks cannot be the target " - "of a branch."; - } - } - } else if (block->is_type(kBlockTypeContinue)) { - // 1. Find referencing loop and confirm that it is reachable. - std::vector continue_headers = - function->GetContinueHeaders(block); - if (continue_headers.empty()) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable continue-target must be referenced " - "by a loop instruction."; - } - - std::vector reachable_headers(continue_headers.size()); - auto iter = - std::copy_if(continue_headers.begin(), continue_headers.end(), - reachable_headers.begin(), - [](BasicBlock* header) { return header->reachable(); }); - reachable_headers.resize(std::distance(reachable_headers.begin(), iter)); - - if (reachable_headers.empty()) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable continue-target must be referenced " - "by a reachable loop instruction."; - } - - // 2. Check that the only instructions are OpLabel and OpBranch. - auto* label_inst = block->label(); - auto* terminator_inst = block->terminator(); - assert(label_inst != nullptr); - assert(terminator_inst != nullptr); - - if (terminator_inst->opcode() != SpvOpBranch) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable continue-target must terminate with " - "OpBranch."; - } - - auto label_idx = label_inst - &_.ordered_instructions()[0]; - auto terminator_idx = terminator_inst - &_.ordered_instructions()[0]; - if (label_idx + 1 != terminator_idx) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable continue-target must only contain " - "an OpLabel and an OpBranch instruction."; - } - - // 3. Use label instruction to confirm there is no uses by branches. - for (auto use : label_inst->uses()) { - const auto* use_inst = use.first; - if (spvOpcodeIsBranch(use_inst->opcode())) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable continue-target cannot be the " - "target of a branch."; - } - } - - // 4. Confirm that continue-target has a back edge to a reachable loop - // header block. - auto branch_target = terminator_inst->GetOperandAs(0); - for (auto* continue_header : reachable_headers) { - if (branch_target != continue_header->id()) { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, unreachable continue-target must only have a " - "back edge to a single reachable loop instruction."; - } - } - } else { - return _.diag(SPV_ERROR_INVALID_CFG, _.FindDef(block->id())) - << "For WebGPU, all blocks must be reachable, unless they are " - << "degenerate cases of merge-block or continue-target."; - } - } - return SPV_SUCCESS; -} - spv_result_t PerformCfgChecks(ValidationState_t& _) { for (auto& function : _.functions()) { // Check all referenced blocks are defined within a function @@ -1010,13 +897,6 @@ spv_result_t PerformCfgChecks(ValidationState_t& _) { << _.getIdName(idom->id()); } } - - // For WebGPU check that all unreachable blocks are degenerate cases for - // merge-block or continue-target. - if (spvIsWebGPUEnv(_.context()->target_env)) { - spv_result_t result = PerformWebGPUCfgChecks(_, &function); - if (result != SPV_SUCCESS) return result; - } } // If we have structed control flow, check that no block has a control // flow nesting depth larger than the limit. @@ -1110,6 +990,8 @@ spv_result_t CfgPass(ValidationState_t& _, const Instruction* inst) { case SpvOpReturnValue: case SpvOpUnreachable: case SpvOpTerminateInvocation: + case SpvOpIgnoreIntersectionKHR: + case SpvOpTerminateRayKHR: _.current_function().RegisterBlockEnd(std::vector()); if (opcode == SpvOpKill) { _.current_function().RegisterExecutionModelLimitation( @@ -1121,6 +1003,17 @@ spv_result_t CfgPass(ValidationState_t& _, const Instruction* inst) { SpvExecutionModelFragment, "OpTerminateInvocation requires Fragment execution model"); } + if (opcode == SpvOpIgnoreIntersectionKHR) { + _.current_function().RegisterExecutionModelLimitation( + SpvExecutionModelAnyHitKHR, + "OpIgnoreIntersectionKHR requires AnyHit execution model"); + } + if (opcode == SpvOpTerminateRayKHR) { + _.current_function().RegisterExecutionModelLimitation( + SpvExecutionModelAnyHitKHR, + "OpTerminateRayKHR requires AnyHit execution model"); + } + break; default: break; diff --git a/third_party/spirv-tools/source/val/validate_composites.cpp b/third_party/spirv-tools/source/val/validate_composites.cpp index eb8a3244a4..5d6c5e3770 100644 --- a/third_party/spirv-tools/source/val/validate_composites.cpp +++ b/third_party/spirv-tools/source/val/validate_composites.cpp @@ -437,6 +437,10 @@ spv_result_t ValidateCopyObject(ValidationState_t& _, const Instruction* inst) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Expected Result Type and Operand type to be the same"; } + if (_.IsVoidType(result_type)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "OpCopyObject cannot have void result type"; + } return SPV_SUCCESS; } @@ -531,12 +535,10 @@ spv_result_t ValidateVectorShuffle(ValidationState_t& _, } // All Component literals must either be FFFFFFFF or in [0, N - 1]. - // For WebGPU specifically, Component literals cannot be FFFFFFFF. auto vector1ComponentCount = vector1Type->GetOperandAs(2); auto vector2ComponentCount = vector2Type->GetOperandAs(2); auto N = vector1ComponentCount + vector2ComponentCount; auto firstLiteralIndex = 4; - const auto is_webgpu_env = spvIsWebGPUEnv(_.context()->target_env); for (size_t i = firstLiteralIndex; i < inst->operands().size(); ++i) { auto literal = inst->GetOperandAs(i); if (literal != 0xFFFFFFFF && literal >= N) { @@ -544,12 +546,6 @@ spv_result_t ValidateVectorShuffle(ValidationState_t& _, << "Component index " << literal << " is out of bounds for " << "combined (Vector1 + Vector2) size of " << N << "."; } - - if (is_webgpu_env && literal == 0xFFFFFFFF) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "Component literal at operand " << i - firstLiteralIndex - << " cannot be 0xFFFFFFFF in WebGPU execution environment."; - } } if (_.HasCapability(SpvCapabilityShader) && diff --git a/third_party/spirv-tools/source/val/validate_conversion.cpp b/third_party/spirv-tools/source/val/validate_conversion.cpp index 0060d0b7b5..b4e39cfe45 100644 --- a/third_party/spirv-tools/source/val/validate_conversion.cpp +++ b/third_party/spirv-tools/source/val/validate_conversion.cpp @@ -14,12 +14,12 @@ // Validates correctness of conversion instructions. -#include "source/val/validate.h" - #include "source/diagnostic.h" #include "source/opcode.h" #include "source/spirv_constant.h" +#include "source/spirv_target_env.h" #include "source/val/instruction.h" +#include "source/val/validate.h" #include "source/val/validation_state.h" namespace spvtools { @@ -263,16 +263,25 @@ spv_result_t ConversionPass(ValidationState_t& _, const Instruction* inst) { << "Logical addressing not supported: " << spvOpcodeString(opcode); - if (_.addressing_model() == - SpvAddressingModelPhysicalStorageBuffer64EXT) { + if (_.addressing_model() == SpvAddressingModelPhysicalStorageBuffer64) { uint32_t input_storage_class = 0; uint32_t input_data_type = 0; _.GetPointerTypeInfo(input_type, &input_data_type, &input_storage_class); - if (input_storage_class != SpvStorageClassPhysicalStorageBufferEXT) + if (input_storage_class != SpvStorageClassPhysicalStorageBuffer) return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Pointer storage class must be PhysicalStorageBufferEXT: " + << "Pointer storage class must be PhysicalStorageBuffer: " << spvOpcodeString(opcode); + + if (spvIsVulkanEnv(_.context()->target_env)) { + if (_.GetBitWidth(result_type) != 64) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4710) + << "PhysicalStorageBuffer64 addressing mode requires the " + "result integer type to have a 64-bit width for Vulkan " + "environment."; + } + } } break; } @@ -314,16 +323,25 @@ spv_result_t ConversionPass(ValidationState_t& _, const Instruction* inst) { << "Logical addressing not supported: " << spvOpcodeString(opcode); - if (_.addressing_model() == - SpvAddressingModelPhysicalStorageBuffer64EXT) { + if (_.addressing_model() == SpvAddressingModelPhysicalStorageBuffer64) { uint32_t result_storage_class = 0; uint32_t result_data_type = 0; _.GetPointerTypeInfo(result_type, &result_data_type, &result_storage_class); - if (result_storage_class != SpvStorageClassPhysicalStorageBufferEXT) + if (result_storage_class != SpvStorageClassPhysicalStorageBuffer) return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Pointer storage class must be PhysicalStorageBufferEXT: " + << "Pointer storage class must be PhysicalStorageBuffer: " << spvOpcodeString(opcode); + + if (spvIsVulkanEnv(_.context()->target_env)) { + if (_.GetBitWidth(input_type) != 64) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4710) + << "PhysicalStorageBuffer64 addressing mode requires the " + "input integer to have a 64-bit width for Vulkan " + "environment."; + } + } } break; } diff --git a/third_party/spirv-tools/source/val/validate_decorations.cpp b/third_party/spirv-tools/source/val/validate_decorations.cpp index d3812766ed..f076b04c76 100644 --- a/third_party/spirv-tools/source/val/validate_decorations.cpp +++ b/third_party/spirv-tools/source/val/validate_decorations.cpp @@ -379,6 +379,7 @@ bool IsAlignedTo(uint32_t offset, uint32_t alignment) { // or row major-ness. spv_result_t checkLayout(uint32_t struct_id, const char* storage_class_str, const char* decoration_str, bool blockRules, + bool scalar_block_layout, uint32_t incoming_offset, MemberConstraints& constraints, ValidationState_t& vstate) { @@ -392,7 +393,6 @@ spv_result_t checkLayout(uint32_t struct_id, const char* storage_class_str, // For example, relaxed layout is implied by Vulkan 1.1. But scalar layout // is more permissive than relaxed layout. const bool relaxed_block_layout = vstate.IsRelaxedBlockLayout(); - const bool scalar_block_layout = vstate.options()->scalar_block_layout; auto fail = [&vstate, struct_id, storage_class_str, decoration_str, blockRules, relaxed_block_layout, @@ -501,6 +501,7 @@ spv_result_t checkLayout(uint32_t struct_id, const char* storage_class_str, if (SpvOpTypeStruct == opcode && SPV_SUCCESS != (recursive_status = checkLayout( id, storage_class_str, decoration_str, blockRules, + scalar_block_layout, offset, constraints, vstate))) return recursive_status; // Check matrix stride. @@ -553,7 +554,8 @@ spv_result_t checkLayout(uint32_t struct_id, const char* storage_class_str, if (SpvOpTypeStruct == element_inst->opcode() && SPV_SUCCESS != (recursive_status = checkLayout( typeId, storage_class_str, decoration_str, - blockRules, next_offset, constraints, vstate))) + blockRules, scalar_block_layout, + next_offset, constraints, vstate))) return recursive_status; // If offsets accumulate up to a 16-byte multiple stop checking since // it will just repeat. @@ -698,6 +700,9 @@ spv_result_t CheckDecorationsOfEntryPoints(ValidationState_t& vstate) { const auto& descs = vstate.entry_point_descriptions(entry_point); int num_builtin_inputs = 0; int num_builtin_outputs = 0; + int num_workgroup_variables = 0; + int num_workgroup_variables_with_block = 0; + int num_workgroup_variables_with_aliased = 0; for (const auto& desc : descs) { std::unordered_set seen_vars; for (auto interface : desc.interfaces) { @@ -754,6 +759,16 @@ spv_result_t CheckDecorationsOfEntryPoints(ValidationState_t& vstate) { if (auto error = CheckBuiltInVariable(interface, vstate)) return error; } + + if (storage_class == SpvStorageClassWorkgroup) { + ++num_workgroup_variables; + if (type_instr && SpvOpTypeStruct == type_instr->opcode()) { + if (hasDecoration(type_id, SpvDecorationBlock, vstate)) + ++num_workgroup_variables_with_block; + if (hasDecoration(var_instr->id(), SpvDecorationAliased, vstate)) + ++num_workgroup_variables_with_aliased; + } + } } if (num_builtin_inputs > 1 || num_builtin_outputs > 1) { return vstate.diag(SPV_ERROR_INVALID_BINARY, @@ -777,6 +792,30 @@ spv_result_t CheckDecorationsOfEntryPoints(ValidationState_t& vstate) { << " because it is targeted by an OpEntryPoint instruction."; } } + + if (vstate.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayoutKHR) && + num_workgroup_variables > 0 && + num_workgroup_variables_with_block > 0) { + if (num_workgroup_variables != num_workgroup_variables_with_block) { + return vstate.diag(SPV_ERROR_INVALID_BINARY, vstate.FindDef(entry_point)) + << "When declaring WorkgroupMemoryExplicitLayoutKHR, " + "either all or none of the Workgroup Storage Class variables " + "in the entry point interface must point to struct types " + "decorated with Block. Entry point id " + << entry_point << " does not meet this requirement."; + } + if (num_workgroup_variables_with_block > 1 && + num_workgroup_variables_with_block != + num_workgroup_variables_with_aliased) { + return vstate.diag(SPV_ERROR_INVALID_BINARY, vstate.FindDef(entry_point)) + << "When declaring WorkgroupMemoryExplicitLayoutKHR, " + "if more than one Workgroup Storage Class variable in " + "the entry point interface point to a type decorated " + "with Block, all of them must be decorated with Aliased. " + "Entry point id " + << entry_point << " does not meet this requirement."; + } + } } } return SPV_SUCCESS; @@ -942,14 +981,16 @@ spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) { const bool phys_storage_buffer = storageClass == SpvStorageClassPhysicalStorageBufferEXT; - if (uniform || push_constant || storage_buffer || phys_storage_buffer) { + const bool workgroup = storageClass == SpvStorageClassWorkgroup; + if (uniform || push_constant || storage_buffer || phys_storage_buffer || + workgroup) { const auto ptrInst = vstate.FindDef(words[1]); assert(SpvOpTypePointer == ptrInst->opcode()); auto id = ptrInst->words()[3]; auto id_inst = vstate.FindDef(id); // Jump through one level of arraying. - if (id_inst->opcode() == SpvOpTypeArray || - id_inst->opcode() == SpvOpTypeRuntimeArray) { + if (!workgroup && (id_inst->opcode() == SpvOpTypeArray || + id_inst->opcode() == SpvOpTypeRuntimeArray)) { id = id_inst->GetOperandAs(1u); id_inst = vstate.FindDef(id); } @@ -961,7 +1002,9 @@ spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) { // Prepare for messages const char* sc_str = uniform ? "Uniform" - : (push_constant ? "PushConstant" : "StorageBuffer"); + : (push_constant ? "PushConstant" + : (workgroup ? "Workgroup" + : "StorageBuffer")); if (spvIsVulkanEnv(vstate.context()->target_env)) { const bool block = hasDecoration(id, SpvDecorationBlock, vstate); @@ -1029,8 +1072,9 @@ spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) { const bool bufferDeco = SpvDecorationBufferBlock == dec.dec_type(); const bool blockRules = uniform && blockDeco; const bool bufferRules = - (uniform && bufferDeco) || (push_constant && blockDeco) || - ((storage_buffer || phys_storage_buffer) && blockDeco); + (uniform && bufferDeco) || + ((push_constant || storage_buffer || + phys_storage_buffer || workgroup) && blockDeco); if (uniform && blockDeco) { vstate.RegisterPointerToUniformBlock(ptrInst->id()); vstate.RegisterStructForUniformBlock(id); @@ -1044,6 +1088,10 @@ spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) { if (blockRules || bufferRules) { const char* deco_str = blockDeco ? "Block" : "BufferBlock"; spv_result_t recursive_status = SPV_SUCCESS; + const bool scalar_block_layout = workgroup ? + vstate.options()->workgroup_scalar_block_layout : + vstate.options()->scalar_block_layout; + if (isMissingOffsetInStruct(id, vstate)) { return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id)) << "Structure id " << id << " decorated as " << deco_str @@ -1072,12 +1120,14 @@ spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) { "decorations."; } else if (blockRules && (SPV_SUCCESS != (recursive_status = checkLayout( - id, sc_str, deco_str, true, 0, + id, sc_str, deco_str, true, + scalar_block_layout, 0, constraints, vstate)))) { return recursive_status; } else if (bufferRules && (SPV_SUCCESS != (recursive_status = checkLayout( - id, sc_str, deco_str, false, 0, + id, sc_str, deco_str, false, + scalar_block_layout, 0, constraints, vstate)))) { return recursive_status; } @@ -1260,7 +1310,8 @@ spv_result_t CheckVulkanMemoryModelDeprecatedDecorations( // decorations. Otherwise emits a diagnostic and returns something other than // SPV_SUCCESS. spv_result_t CheckFPRoundingModeForShaders(ValidationState_t& vstate, - const Instruction& inst) { + const Instruction& inst, + const Decoration& decoration) { // Validates width-only conversion instruction for floating-point object // i.e., OpFConvert if (inst.opcode() != SpvOpFConvert) { @@ -1270,6 +1321,15 @@ spv_result_t CheckFPRoundingModeForShaders(ValidationState_t& vstate, "object."; } + if (spvIsVulkanEnv(vstate.context()->target_env)) { + const auto mode = decoration.params()[0]; + if ((mode != SpvFPRoundingModeRTE) && (mode != SpvFPRoundingModeRTZ)) { + return vstate.diag(SPV_ERROR_INVALID_ID, &inst) + << vstate.VkErrorID(4675) + << "In Vulkan, the FPRoundingMode mode must only by RTE or RTZ."; + } + } + // Validates Object operand of an OpStore for (const auto& use : inst.uses()) { const auto store = use.first; @@ -1559,7 +1619,7 @@ spv_result_t CheckLocationDecoration(ValidationState_t& vstate, { \ spv_result_t e##LINE = (X); \ if (e##LINE != SPV_SUCCESS) return e##LINE; \ - } + } static_assert(true, "require extra semicolon") #define PASS_OR_BAIL(X) PASS_OR_BAIL_AT_LINE(X, __LINE__) // Check rules for decorations where we start from the decoration rather @@ -1588,7 +1648,8 @@ spv_result_t CheckDecorationsFromDecoration(ValidationState_t& vstate) { break; case SpvDecorationFPRoundingMode: if (is_shader) - PASS_OR_BAIL(CheckFPRoundingModeForShaders(vstate, *inst)); + PASS_OR_BAIL( + CheckFPRoundingModeForShaders(vstate, *inst, decoration)); break; case SpvDecorationNonWritable: PASS_OR_BAIL(CheckNonWritableDecoration(vstate, *inst, decoration)); diff --git a/third_party/spirv-tools/source/val/validate_extensions.cpp b/third_party/spirv-tools/source/val/validate_extensions.cpp index 17b0446013..b5b98783e3 100644 --- a/third_party/spirv-tools/source/val/validate_extensions.cpp +++ b/third_party/spirv-tools/source/val/validate_extensions.cpp @@ -27,6 +27,7 @@ #include "source/latest_version_glsl_std_450_header.h" #include "source/latest_version_opencl_std_header.h" #include "source/opcode.h" +#include "source/spirv_constant.h" #include "source/spirv_target_env.h" #include "source/val/instruction.h" #include "source/val/validate.h" @@ -686,14 +687,13 @@ bool IsDebugVariableWithIntScalarType(ValidationState_t& _, } // anonymous namespace spv_result_t ValidateExtension(ValidationState_t& _, const Instruction* inst) { - if (spvIsWebGPUEnv(_.context()->target_env)) { + if (_.version() < SPV_SPIRV_VERSION_WORD(1, 4)) { std::string extension = GetExtensionString(&(inst->c_inst())); - - if (extension != ExtensionToString(kSPV_KHR_vulkan_memory_model)) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU, the only valid parameter to OpExtension is " - << "\"" << ExtensionToString(kSPV_KHR_vulkan_memory_model) - << "\"."; + if (extension == + ExtensionToString(kSPV_KHR_workgroup_memory_explicit_layout)) { + return _.diag(SPV_ERROR_WRONG_VERSION, inst) + << "SPV_KHR_workgroup_memory_explicit_layout extension " + "requires SPIR-V version 1.4 or later."; } } @@ -703,16 +703,6 @@ spv_result_t ValidateExtension(ValidationState_t& _, const Instruction* inst) { spv_result_t ValidateExtInstImport(ValidationState_t& _, const Instruction* inst) { const auto name_id = 1; - if (spvIsWebGPUEnv(_.context()->target_env)) { - const std::string name(reinterpret_cast( - inst->words().data() + inst->operands()[name_id].offset)); - if (name != "GLSL.std.450") { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU, the only valid parameter to OpExtInstImport is " - "\"GLSL.std.450\"."; - } - } - if (!_.HasExtension(kSPV_KHR_non_semantic_info)) { const std::string name(reinterpret_cast( inst->words().data() + inst->operands()[name_id].offset)); @@ -1382,7 +1372,16 @@ spv_result_t ValidateExtInst(ValidationState_t& _, const Instruction* inst) { << "or vector type"; } - const uint32_t interpolant_type = _.GetOperandTypeId(inst, 4); + // If HLSL legalization and first operand is an OpLoad, use load + // pointer as the interpolant lvalue. Else use interpolate first + // operand. + uint32_t interp_id = inst->GetOperandAs(4); + auto* interp_inst = _.FindDef(interp_id); + uint32_t interpolant_type = (_.options()->before_hlsl_legalization && + interp_inst->opcode() == SpvOpLoad) + ? _.GetOperandTypeId(interp_inst, 2) + : _.GetOperandTypeId(inst, 4); + uint32_t interpolant_storage_class = 0; uint32_t interpolant_data_type = 0; if (!_.GetPointerTypeInfo(interpolant_type, &interpolant_data_type, @@ -3113,6 +3112,7 @@ spv_result_t ValidateExtInst(ValidationState_t& _, const Instruction* inst) { case OpenCLDebugInfo100DebugMacroDef: case OpenCLDebugInfo100DebugMacroUndef: case OpenCLDebugInfo100DebugImportedEntity: + case OpenCLDebugInfo100DebugModuleINTEL: break; case OpenCLDebugInfo100InstructionsMax: assert(0); diff --git a/third_party/spirv-tools/source/val/validate_id.cpp b/third_party/spirv-tools/source/val/validate_id.cpp index e1a775a852..2bab203493 100644 --- a/third_party/spirv-tools/source/val/validate_id.cpp +++ b/third_party/spirv-tools/source/val/validate_id.cpp @@ -201,7 +201,7 @@ spv_result_t IdPass(ValidationState_t& _, Instruction* inst) { ret = SPV_SUCCESS; } } else if (can_have_forward_declared_ids(i)) { - if (inst->opcode() == SpvOpTypeStruct && + if (spvOpcodeGeneratesType(inst->opcode()) && !_.IsForwardPointer(operand_word)) { ret = _.diag(SPV_ERROR_INVALID_ID, inst) << "Operand " << _.getIdName(operand_word) diff --git a/third_party/spirv-tools/source/val/validate_image.cpp b/third_party/spirv-tools/source/val/validate_image.cpp index 299a3efca9..e5968d06e7 100644 --- a/third_party/spirv-tools/source/val/validate_image.cpp +++ b/third_party/spirv-tools/source/val/validate_image.cpp @@ -16,8 +16,6 @@ // Validates correctness of image instructions. -#include "source/val/validate.h" - #include #include "source/diagnostic.h" @@ -25,6 +23,7 @@ #include "source/spirv_target_env.h" #include "source/util/bitutils.h" #include "source/val/instruction.h" +#include "source/val/validate.h" #include "source/val/validate_scopes.h" #include "source/val/validation_state.h" @@ -234,9 +233,10 @@ uint32_t GetMinCoordSize(SpvOp opcode, const ImageTypeInfo& info) { } // Checks ImageOperand bitfield and respective operands. +// word_index is the index of the first word after the image-operand mask word. spv_result_t ValidateImageOperands(ValidationState_t& _, const Instruction* inst, - const ImageTypeInfo& info, uint32_t mask, + const ImageTypeInfo& info, uint32_t word_index) { static const bool kAllImageOperandsHandled = CheckAllImageOperandsHandled(); (void)kAllImageOperandsHandled; @@ -244,28 +244,48 @@ spv_result_t ValidateImageOperands(ValidationState_t& _, const SpvOp opcode = inst->opcode(); const size_t num_words = inst->words().size(); - // NonPrivate, Volatile, SignExtend, ZeroExtend take no operand words. - const uint32_t mask_bits_having_operands = - mask & ~uint32_t(SpvImageOperandsNonPrivateTexelKHRMask | - SpvImageOperandsVolatileTexelKHRMask | - SpvImageOperandsSignExtendMask | - SpvImageOperandsZeroExtendMask); - size_t expected_num_image_operand_words = - spvtools::utils::CountSetBits(mask_bits_having_operands); - if (mask & SpvImageOperandsGradMask) { - // Grad uses two words. - ++expected_num_image_operand_words; - } + const bool have_explicit_mask = (word_index - 1 < num_words); + const uint32_t mask = have_explicit_mask ? inst->word(word_index - 1) : 0u; - if (expected_num_image_operand_words != num_words - word_index) { + if (have_explicit_mask) { + // NonPrivate, Volatile, SignExtend, ZeroExtend take no operand words. + const uint32_t mask_bits_having_operands = + mask & ~uint32_t(SpvImageOperandsNonPrivateTexelKHRMask | + SpvImageOperandsVolatileTexelKHRMask | + SpvImageOperandsSignExtendMask | + SpvImageOperandsZeroExtendMask); + size_t expected_num_image_operand_words = + spvtools::utils::CountSetBits(mask_bits_having_operands); + if (mask & SpvImageOperandsGradMask) { + // Grad uses two words. + ++expected_num_image_operand_words; + } + + if (expected_num_image_operand_words != num_words - word_index) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Number of image operand ids doesn't correspond to the bit " + "mask"; + } + } else if (num_words != word_index - 1) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Number of image operand ids doesn't correspond to the bit mask"; } + if (info.multisampled & (0 == (mask & SpvImageOperandsSampleMask))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Image Operand Sample is required for operation on " + "multi-sampled image"; + } + + // After this point, only set bits in the image operands mask can cause + // the module to be invalid. + if (mask == 0) return SPV_SUCCESS; + if (spvtools::utils::CountSetBits( mask & (SpvImageOperandsOffsetMask | SpvImageOperandsConstOffsetMask | SpvImageOperandsConstOffsetsMask)) > 1) { return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4662) << "Image Operands Offset, ConstOffset, ConstOffsets cannot be used " << "together"; } @@ -296,10 +316,7 @@ spv_result_t ValidateImageOperands(ValidationState_t& _, "or Cube"; } - if (info.multisampled != 0) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Image Operand Bias requires 'MS' parameter to be 0"; - } + // Multisampled is already checked. } if (mask & SpvImageOperandsLodMask) { @@ -338,10 +355,7 @@ spv_result_t ValidateImageOperands(ValidationState_t& _, "or Cube"; } - if (info.multisampled != 0) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Image Operand Lod requires 'MS' parameter to be 0"; - } + // Multisampled is already checked. } if (mask & SpvImageOperandsGradMask) { @@ -374,10 +388,7 @@ spv_result_t ValidateImageOperands(ValidationState_t& _, << " components, but given " << dy_size; } - if (info.multisampled != 0) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Image Operand Grad requires 'MS' parameter to be 0"; - } + // Multisampled is already checked. } if (mask & SpvImageOperandsConstOffsetMask) { @@ -430,6 +441,18 @@ spv_result_t ValidateImageOperands(ValidationState_t& _, << "Expected Image Operand Offset to have " << plane_size << " components, but given " << offset_size; } + + if (!_.options()->before_hlsl_legalization && + spvIsVulkanEnv(_.context()->target_env)) { + if (opcode != SpvOpImageGather && opcode != SpvOpImageDrefGather && + opcode != SpvOpImageSparseGather && + opcode != SpvOpImageSparseDrefGather) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4663) + << "Image Operand Offset can only be used with " + "OpImage*Gather operations"; + } + } } if (mask & SpvImageOperandsConstOffsetsMask) { @@ -613,12 +636,12 @@ spv_result_t ValidateImageCommon(ValidationState_t& _, const Instruction* inst, if (info.multisampled != 0) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Image Image 'MS' parameter to be 0"; + << "Expected Image 'MS' parameter to be 0"; } if (info.arrayed != 0) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Image Image 'arrayed' parameter to be 0"; + << "Expected Image 'arrayed' parameter to be 0"; } } @@ -736,17 +759,28 @@ spv_result_t ValidateTypeImage(ValidationState_t& _, const Instruction* inst) { << "Corrupt image type definition"; } - if (spvIsVulkanEnv(_.context()->target_env)) { + if (_.IsIntScalarType(info.sampled_type) && + (64 == _.GetBitWidth(info.sampled_type)) && + !_.HasCapability(SpvCapabilityInt64ImageEXT)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Capability Int64ImageEXT is required when using Sampled Type of " + "64-bit int"; + } + + const auto target_env = _.context()->target_env; + if (spvIsVulkanEnv(target_env)) { if ((!_.IsFloatScalarType(info.sampled_type) && !_.IsIntScalarType(info.sampled_type)) || - (32 != _.GetBitWidth(info.sampled_type) && - (64 != _.GetBitWidth(info.sampled_type) || - !_.HasCapability(SpvCapabilityInt64ImageEXT)))) { + ((32 != _.GetBitWidth(info.sampled_type)) && + (64 != _.GetBitWidth(info.sampled_type))) || + ((64 == _.GetBitWidth(info.sampled_type)) && + _.IsFloatScalarType(info.sampled_type))) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Expected Sampled Type to be a 32-bit int or float " - "scalar type for Vulkan environment"; + << _.VkErrorID(4656) + << "Expected Sampled Type to be a 32-bit int, 64-bit int or " + "32-bit float scalar type for Vulkan environment"; } - } else if (spvIsOpenCLEnv(_.context()->target_env)) { + } else if (spvIsOpenCLEnv(target_env)) { if (!_.IsVoidType(info.sampled_type)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Sampled Type must be OpTypeVoid in the OpenCL environment."; @@ -774,7 +808,7 @@ spv_result_t ValidateTypeImage(ValidationState_t& _, const Instruction* inst) { << "Invalid Arrayed " << info.arrayed << " (must be 0 or 1)"; } - if (spvIsOpenCLEnv(_.context()->target_env)) { + if (spvIsOpenCLEnv(target_env)) { if ((info.arrayed == 1) && (info.dim != SpvDim1D) && (info.dim != SpvDim2D)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) @@ -788,10 +822,10 @@ spv_result_t ValidateTypeImage(ValidationState_t& _, const Instruction* inst) { << "Invalid MS " << info.multisampled << " (must be 0 or 1)"; } - if (spvIsOpenCLEnv(_.context()->target_env)) { + if (spvIsOpenCLEnv(target_env)) { if (info.multisampled != 0) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "MS must be 0 in the OpenCL environement."; + << "MS must be 0 in the OpenCL environment."; } } @@ -800,6 +834,14 @@ spv_result_t ValidateTypeImage(ValidationState_t& _, const Instruction* inst) { << "Invalid Sampled " << info.sampled << " (must be 0, 1 or 2)"; } + if (spvIsVulkanEnv(target_env)) { + if (info.sampled == 0) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4657) + << "Sampled must be 1 or 2 in the Vulkan environment."; + } + } + if (spvIsOpenCLEnv(_.context()->target_env)) { if (info.sampled != 0) { return _.diag(SPV_ERROR_INVALID_DATA, inst) @@ -829,6 +871,15 @@ spv_result_t ValidateTypeImage(ValidationState_t& _, const Instruction* inst) { } } + if (info.multisampled && (info.sampled == 2) && + (info.dim != SpvDimSubpassData)) { + if (!_.HasCapability(SpvCapabilityStorageImageMultisample)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Capability StorageImageMultisample is required when using " + "multisampled storage image"; + } + } + return SPV_SUCCESS; } @@ -839,6 +890,21 @@ spv_result_t ValidateTypeSampledImage(ValidationState_t& _, return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Expected Image to be of type OpTypeImage"; } + + ImageTypeInfo info; + if (!GetImageTypeInfo(_, image_type, &info)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Corrupt image type definition"; + } + // OpenCL requires Sampled=0, checked elsewhere. + // Vulkan uses the Sampled=1 case. + if ((info.sampled != 0) && (info.sampled != 1)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4657) + << "Sampled image type requires an image type with \"Sampled\" " + "operand set to 0 or 1"; + } + return SPV_SUCCESS; } @@ -1066,6 +1132,20 @@ spv_result_t ValidateImageTexelPointer(ValidationState_t& _, "the value 0"; } } + + if (spvIsVulkanEnv(_.context()->target_env)) { + if ((info.format != SpvImageFormatR64i) && + (info.format != SpvImageFormatR64ui) && + (info.format != SpvImageFormatR32f) && + (info.format != SpvImageFormatR32i) && + (info.format != SpvImageFormatR32ui)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4658) + << "Expected the Image Format in Image to be R64i, R64ui, R32f, " + "R32i, or R32ui for Vulkan environment"; + } + } + return SPV_SUCCESS; } @@ -1103,6 +1183,14 @@ spv_result_t ValidateImageLod(ValidationState_t& _, const Instruction* inst) { if (spv_result_t result = ValidateImageCommon(_, inst, info)) return result; + if (info.multisampled) { + // When using image operands, the Sample image operand is required if and + // only if the image is multisampled (MS=1). The Sample image operand is + // only allowed for fetch, read, and write. + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Sampling operation is invalid for multisample image"; + } + if (_.GetIdOpcode(info.sampled_type) != SpvOpTypeVoid) { const uint32_t texel_component_type = _.GetComponentType(actual_result_type); @@ -1137,16 +1225,11 @@ spv_result_t ValidateImageLod(ValidationState_t& _, const Instruction* inst) { << " components, but given only " << actual_coord_size; } - if (inst->words().size() <= 5) { - assert(IsImplicitLod(opcode)); - return SPV_SUCCESS; - } + const uint32_t mask = inst->words().size() <= 5 ? 0 : inst->word(5); - const uint32_t mask = inst->word(5); - - if (spvIsOpenCLEnv(_.context()->target_env)) { - if (opcode == SpvOpImageSampleExplicitLod) { - if (mask & SpvImageOperandsConstOffsetMask) { + if (mask & SpvImageOperandsConstOffsetMask) { + if (spvIsOpenCLEnv(_.context()->target_env)) { + if (opcode == SpvOpImageSampleExplicitLod) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "ConstOffset image operand not allowed " << "in the OpenCL environment."; @@ -1155,7 +1238,7 @@ spv_result_t ValidateImageLod(ValidationState_t& _, const Instruction* inst) { } if (spv_result_t result = - ValidateImageOperands(_, inst, info, mask, /* word_index = */ 6)) + ValidateImageOperands(_, inst, info, /* word_index = */ 6)) return result; return SPV_SUCCESS; @@ -1190,6 +1273,14 @@ spv_result_t ValidateImageDrefLod(ValidationState_t& _, if (spv_result_t result = ValidateImageCommon(_, inst, info)) return result; + if (info.multisampled) { + // When using image operands, the Sample image operand is required if and + // only if the image is multisampled (MS=1). The Sample image operand is + // only allowed for fetch, read, and write. + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Dref sampling operation is invalid for multisample image"; + } + if (actual_result_type != info.sampled_type) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Expected Image 'Sampled Type' to be the same as " @@ -1216,14 +1307,8 @@ spv_result_t ValidateImageDrefLod(ValidationState_t& _, << "Expected Dref to be of 32-bit float type"; } - if (inst->words().size() <= 6) { - assert(IsImplicitLod(opcode)); - return SPV_SUCCESS; - } - - const uint32_t mask = inst->word(6); if (spv_result_t result = - ValidateImageOperands(_, inst, info, mask, /* word_index = */ 7)) + ValidateImageOperands(_, inst, info, /* word_index = */ 7)) return result; return SPV_SUCCESS; @@ -1294,11 +1379,8 @@ spv_result_t ValidateImageFetch(ValidationState_t& _, const Instruction* inst) { << " components, but given only " << actual_coord_size; } - if (inst->words().size() <= 5) return SPV_SUCCESS; - - const uint32_t mask = inst->word(5); if (spv_result_t result = - ValidateImageOperands(_, inst, info, mask, /* word_index = */ 6)) + ValidateImageOperands(_, inst, info, /* word_index = */ 6)) return result; return SPV_SUCCESS; @@ -1336,6 +1418,14 @@ spv_result_t ValidateImageGather(ValidationState_t& _, << "Corrupt image type definition"; } + if (info.multisampled) { + // When using image operands, the Sample image operand is required if and + // only if the image is multisampled (MS=1). The Sample image operand is + // only allowed for fetch, read, and write. + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Gather operation is invalid for multisample image"; + } + if (opcode == SpvOpImageDrefGather || opcode == SpvOpImageSparseDrefGather || _.GetIdOpcode(info.sampled_type) != SpvOpTypeVoid) { const uint32_t result_component_type = @@ -1368,12 +1458,21 @@ spv_result_t ValidateImageGather(ValidationState_t& _, } if (opcode == SpvOpImageGather || opcode == SpvOpImageSparseGather) { - const uint32_t component_index_type = _.GetOperandTypeId(inst, 4); + const uint32_t component = inst->GetOperandAs(4); + const uint32_t component_index_type = _.GetTypeId(component); if (!_.IsIntScalarType(component_index_type) || _.GetBitWidth(component_index_type) != 32) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Expected Component to be 32-bit int scalar"; } + if (spvIsVulkanEnv(_.context()->target_env)) { + if (!spvOpcodeIsConstant(_.GetIdOpcode(component))) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4664) + << "Expected Component Operand to be a const object for Vulkan " + "environment"; + } + } } else { assert(opcode == SpvOpImageDrefGather || opcode == SpvOpImageSparseDrefGather); @@ -1384,11 +1483,8 @@ spv_result_t ValidateImageGather(ValidationState_t& _, } } - if (inst->words().size() <= 6) return SPV_SUCCESS; - - const uint32_t mask = inst->word(6); if (spv_result_t result = - ValidateImageOperands(_, inst, info, mask, /* word_index = */ 7)) + ValidateImageOperands(_, inst, info, /* word_index = */ 7)) return result; return SPV_SUCCESS; @@ -1408,14 +1504,16 @@ spv_result_t ValidateImageRead(ValidationState_t& _, const Instruction* inst) { << " to be int or float scalar or vector type"; } -#if 0 - // TODO(atgoo@github.com) Disabled until the spec is clarified. - if (_.GetDimension(actual_result_type) != 4) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Expected " << GetActualResultTypeStr(opcode) - << " to have 4 components"; - } -#endif + const auto target_env = _.context()->target_env; + // Vulkan requires the result to be a 4-element int or float + // vector. + if (spvIsVulkanEnv(target_env)) { + if (_.GetDimension(actual_result_type) != 4) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4780) << "Expected " + << GetActualResultTypeStr(opcode) << " to have 4 components"; + } + } // Check OpenCL below, after we get the image info. const uint32_t image_type = _.GetOperandTypeId(inst, 2); if (_.GetIdOpcode(image_type) != SpvOpTypeImage) { @@ -1429,6 +1527,29 @@ spv_result_t ValidateImageRead(ValidationState_t& _, const Instruction* inst) { << "Corrupt image type definition"; } + if (spvIsOpenCLEnv(target_env)) { + // In OpenCL, a read from a depth image returns a scalar float. In other + // cases, the result is always a 4-element vector. + // https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Env.html#_data_format_for_reading_and_writing_images + // https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_C.html#image-read-and-write-functions + // The builtins for reading depth images are: + // float read_imagef(aQual image2d_depth_t image, int2 coord) + // float read_imagef(aQual image2d_array_depth_t image, int4 coord) + if (info.depth) { + if (!_.IsFloatScalarType(actual_result_type)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Expected " << GetActualResultTypeStr(opcode) + << " from a depth image read to result in a scalar float value"; + } + } else { + if (_.GetDimension(actual_result_type) != 4) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << "Expected " << GetActualResultTypeStr(opcode) + << " to have 4 components"; + } + } + } + if (info.dim == SpvDimSubpassData) { if (opcode == SpvOpImageSparseRead) { return _.diag(SPV_ERROR_INVALID_DATA, inst) @@ -1477,12 +1598,10 @@ spv_result_t ValidateImageRead(ValidationState_t& _, const Instruction* inst) { } } - if (inst->words().size() <= 5) return SPV_SUCCESS; + const uint32_t mask = inst->words().size() <= 5 ? 0 : inst->word(5); - const uint32_t mask = inst->word(5); - - if (spvIsOpenCLEnv(_.context()->target_env)) { - if (mask & SpvImageOperandsConstOffsetMask) { + if (mask & SpvImageOperandsConstOffsetMask) { + if (spvIsOpenCLEnv(_.context()->target_env)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "ConstOffset image operand not allowed " << "in the OpenCL environment."; @@ -1490,7 +1609,7 @@ spv_result_t ValidateImageRead(ValidationState_t& _, const Instruction* inst) { } if (spv_result_t result = - ValidateImageOperands(_, inst, info, mask, /* word_index = */ 6)) + ValidateImageOperands(_, inst, info, /* word_index = */ 6)) return result; return SPV_SUCCESS; @@ -1566,9 +1685,7 @@ spv_result_t ValidateImageWrite(ValidationState_t& _, const Instruction* inst) { } } - if (inst->words().size() <= 4) { - return SPV_SUCCESS; - } else { + if (inst->words().size() > 4) { if (spvIsOpenCLEnv(_.context()->target_env)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Optional Image Operands are not allowed in the OpenCL " @@ -1576,9 +1693,8 @@ spv_result_t ValidateImageWrite(ValidationState_t& _, const Instruction* inst) { } } - const uint32_t mask = inst->word(4); if (spv_result_t result = - ValidateImageOperands(_, inst, info, mask, /* word_index = */ 5)) + ValidateImageOperands(_, inst, info, /* word_index = */ 5)) return result; return SPV_SUCCESS; @@ -1649,6 +1765,16 @@ spv_result_t ValidateImageQuerySizeLod(ValidationState_t& _, return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Image 'MS' must be 0"; } + const auto target_env = _.context()->target_env; + if (spvIsVulkanEnv(target_env)) { + if (info.sampled != 1) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4659) + << "OpImageQuerySizeLod must only consume an \"Image\" operand " + "whose type has its \"Sampled\" operand set to 1"; + } + } + uint32_t result_num_components = _.GetDimension(result_type); if (result_num_components != expected_num_components) { return _.diag(SPV_ERROR_INVALID_DATA, inst) @@ -1823,6 +1949,13 @@ spv_result_t ValidateImageQueryLod(ValidationState_t& _, << "Expected Coordinate to have at least " << min_coord_size << " components, but given only " << actual_coord_size; } + + // The operad is a sampled image. + // The sampled image type is already checked to be parameterized by an image + // type with Sampled=0 or Sampled=1. Vulkan bans Sampled=0, and so we have + // Sampled=1. So the validator already enforces Vulkan VUID 4659: + // OpImageQuerySizeLod must only consume an “Image” operand whose type has + // its "Sampled" operand set to 1 return SPV_SUCCESS; } @@ -1859,6 +1992,15 @@ spv_result_t ValidateImageQueryLevelsOrSamples(ValidationState_t& _, return _.diag(SPV_ERROR_INVALID_DATA, inst) << "Image 'Dim' must be 1D, 2D, 3D or Cube"; } + const auto target_env = _.context()->target_env; + if (spvIsVulkanEnv(target_env)) { + if (info.sampled != 1) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4659) + << "OpImageQueryLevels must only consume an \"Image\" operand " + "whose type has its \"Sampled\" operand set to 1"; + } + } } else { assert(opcode == SpvOpImageQuerySamples); if (info.dim != SpvDim2D) { diff --git a/third_party/spirv-tools/source/val/validate_logicals.cpp b/third_party/spirv-tools/source/val/validate_logicals.cpp index 5886dbf504..bb35f558ec 100644 --- a/third_party/spirv-tools/source/val/validate_logicals.cpp +++ b/third_party/spirv-tools/source/val/validate_logicals.cpp @@ -188,7 +188,7 @@ spv_result_t LogicalsPass(ValidationState_t& _, const Instruction* inst) { case SpvOpTypeStruct: { if (!composites) return fail(); break; - }; + } default: return fail(); diff --git a/third_party/spirv-tools/source/val/validate_memory.cpp b/third_party/spirv-tools/source/val/validate_memory.cpp index 1e1a38dd22..a4bc0faba8 100644 --- a/third_party/spirv-tools/source/val/validate_memory.cpp +++ b/third_party/spirv-tools/source/val/validate_memory.cpp @@ -407,6 +407,10 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { << "' is not a pointer type."; } + const auto type_index = 2; + const auto value_id = result_type->GetOperandAs(type_index); + auto value_type = _.FindDef(value_id); + const auto initializer_index = 3; const auto storage_class_index = 2; if (initializer_index < inst->operands().size()) { @@ -423,7 +427,7 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { << "OpVariable Initializer '" << _.getIdName(initializer_id) << "' is not a constant or module-scope variable."; } - if (initializer->type_id() != result_type->GetOperandAs(2u)) { + if (initializer->type_id() != value_id) { return _.diag(SPV_ERROR_INVALID_ID, inst) << "Initializer type must match the type pointed to by the Result " "Type"; @@ -440,9 +444,6 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { storage_class != SpvStorageClassHitAttributeNV && storage_class != SpvStorageClassCallableDataNV && storage_class != SpvStorageClassIncomingCallableDataNV) { - const auto storage_index = 2; - const auto storage_id = result_type->GetOperandAs(storage_index); - const auto storage = _.FindDef(storage_id); bool storage_input_or_output = storage_class == SpvStorageClassInput || storage_class == SpvStorageClassOutput; bool builtin = false; @@ -455,7 +456,7 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { } } if (!(storage_input_or_output && builtin) && - ContainsInvalidBool(_, storage, storage_input_or_output)) { + ContainsInvalidBool(_, value_type, storage_input_or_output)) { return _.diag(SPV_ERROR_INVALID_ID, inst) << "If OpTypeBool is stored in conjunction with OpVariable, it " << "can only be used with non-externally visible shader Storage " @@ -465,6 +466,7 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { if (!_.IsValidStorageClass(storage_class)) { return _.diag(SPV_ERROR_INVALID_BINARY, inst) + << _.VkErrorID(4643) << "Invalid storage class for target environment"; } @@ -535,19 +537,14 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { if (!IsAllowedTypeOrArrayOfSame( _, pointee, {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage, - SpvOpTypeAccelerationStructureNV, - SpvOpTypeAccelerationStructureKHR, - SpvOpTypeRayQueryProvisionalKHR})) { + SpvOpTypeAccelerationStructureKHR})) { return _.diag(SPV_ERROR_INVALID_ID, inst) - << "UniformConstant OpVariable '" << _.getIdName(inst->id()) - << "' has illegal type.\n" - << "From Vulkan spec, section 14.5.2:\n" + << _.VkErrorID(4655) << "UniformConstant OpVariable '" + << _.getIdName(inst->id()) << "' has illegal type.\n" << "Variables identified with the UniformConstant storage class " << "are used only as handles to refer to opaque resources. Such " << "variables must be typed as OpTypeImage, OpTypeSampler, " - << "OpTypeSampledImage, OpTypeAccelerationStructureNV, " - "OpTypeAccelerationStructureKHR, " - "OpTypeRayQueryProvisionalKHR, " + << "OpTypeSampledImage, OpTypeAccelerationStructureKHR, " << "or an array of one of these types."; } } @@ -577,40 +574,59 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { "of this type"; } } + + // Check for invalid use of Invariant + if (storage_class != SpvStorageClassInput && + storage_class != SpvStorageClassOutput) { + if (_.HasDecoration(inst->id(), SpvDecorationInvariant)) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << _.VkErrorID(4677) + << "Variable decorated with Invariant must only be identified " + "with the Input or Output storage class in Vulkan " + "environment."; + } + // Need to check if only the members in a struct are decorated + if (value_type && value_type->opcode() == SpvOpTypeStruct) { + if (_.HasDecoration(value_id, SpvDecorationInvariant)) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << _.VkErrorID(4677) + << "Variable struct member decorated with Invariant must only " + "be identified with the Input or Output storage class in " + "Vulkan environment."; + } + } + } } - // WebGPU & Vulkan Appendix A: Check that if contains initializer, then + // Vulkan Appendix A: Check that if contains initializer, then // storage class is Output, Private, or Function. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput && storage_class != SpvStorageClassPrivate && storage_class != SpvStorageClassFunction) { - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpVariable, '" << _.getIdName(inst->id()) - << "', has a disallowed initializer & storage class " - << "combination.\n" - << "From " << spvLogStringForEnv(_.context()->target_env) - << " spec:\n" - << "Variable declarations that include initializers must have " - << "one of the following storage classes: Output, Private, or " - << "Function"; + if (spvIsVulkanEnv(_.context()->target_env)) { + if (storage_class == SpvStorageClassWorkgroup) { + auto init_id = inst->GetOperandAs(3); + auto init = _.FindDef(init_id); + if (init->opcode() != SpvOpConstantNull) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Variable initializers in Workgroup storage class are " + "limited to OpConstantNull"; + } + } else { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << _.VkErrorID(4651) << "OpVariable, '" + << _.getIdName(inst->id()) + << "', has a disallowed initializer & storage class " + << "combination.\n" + << "From " << spvLogStringForEnv(_.context()->target_env) + << " spec:\n" + << "Variable declarations that include initializers must have " + << "one of the following storage classes: Output, Private, " + << "Function or Workgroup"; + } } } - // WebGPU: All variables with storage class Output, Private, or Function MUST - // have an initializer. - if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 && - (storage_class == SpvStorageClassOutput || - storage_class == SpvStorageClassPrivate || - storage_class == SpvStorageClassFunction)) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpVariable, '" << _.getIdName(inst->id()) - << "', must have an initializer.\n" - << "From WebGPU execution environment spec:\n" - << "All variables in the following storage classes must have an " - << "initializer: Output, Private, or Function"; - } - if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) { return _.diag(SPV_ERROR_INVALID_ID, inst) << "PhysicalStorageBufferEXT must not be used with OpVariable."; @@ -644,9 +660,6 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { } // Vulkan specific validation rules for OpTypeRuntimeArray - const auto type_index = 2; - const auto value_id = result_type->GetOperandAs(type_index); - auto value_type = _.FindDef(value_id); if (spvIsVulkanEnv(_.context()->target_env)) { // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct, // so should never appear as a bare variable. @@ -703,41 +716,6 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { } } - // WebGPU specific validation rules for OpTypeRuntimeArray - if (spvIsWebGPUEnv(_.context()->target_env)) { - // OpTypeRuntimeArray should only ever be in an OpTypeStruct, - // so should never appear as a bare variable. - if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpVariable, '" << _.getIdName(inst->id()) - << "', is attempting to create memory for an illegal type, " - << "OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray can only " - << "appear as the final member of an OpTypeStruct, thus cannot " - << "be instantiated via OpVariable"; - } - - // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it - // must have the storage class StorageBuffer and be decorated - // with Block. - if (value_type && value_type->opcode() == SpvOpTypeStruct) { - if (DoesStructContainRTA(_, value_type)) { - if (storage_class == SpvStorageClassStorageBuffer) { - if (!_.HasDecoration(value_id, SpvDecorationBlock)) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "For WebGPU, an OpTypeStruct variable containing an " - << "OpTypeRuntimeArray must be decorated with Block if it " - << "has storage class StorageBuffer."; - } - } else { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "For WebGPU, OpTypeStruct variables containing " - << "OpTypeRuntimeArray must have storage class of " - << "StorageBuffer"; - } - } - } - } - // Cooperative matrix types can only be allocated in Function or Private if ((storage_class != SpvStorageClassFunction && storage_class != SpvStorageClassPrivate) && @@ -798,6 +776,11 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { storage_class_ok = false; } break; + case SpvStorageClassWorkgroup: + if (!_.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR)) { + storage_class_ok = false; + } + break; default: return _.diag(SPV_ERROR_INVALID_ID, inst) << "Cannot allocate a variable containing a 16-bit type in " @@ -849,6 +832,11 @@ spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) { storage_class_ok = false; } break; + case SpvStorageClassWorkgroup: + if (!_.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR)) { + storage_class_ok = false; + } + break; default: return _.diag(SPV_ERROR_INVALID_ID, inst) << "Cannot allocate a variable containing a 8-bit type in " diff --git a/third_party/spirv-tools/source/val/validate_memory_semantics.cpp b/third_party/spirv-tools/source/val/validate_memory_semantics.cpp index 4c582f09f4..d9189313af 100644 --- a/third_party/spirv-tools/source/val/validate_memory_semantics.cpp +++ b/third_party/spirv-tools/source/val/validate_memory_semantics.cpp @@ -25,7 +25,8 @@ namespace val { spv_result_t ValidateMemorySemantics(ValidationState_t& _, const Instruction* inst, - uint32_t operand_index) { + uint32_t operand_index, + uint32_t memory_scope) { const SpvOp opcode = inst->opcode(); const auto id = inst->GetOperandAs(operand_index); bool is_int32 = false, is_const_int32 = false; @@ -56,55 +57,6 @@ spv_result_t ValidateMemorySemantics(ValidationState_t& _, return SPV_SUCCESS; } - if (spvIsWebGPUEnv(_.context()->target_env)) { - uint32_t valid_bits; - switch (inst->opcode()) { - case SpvOpControlBarrier: - if (!(value & SpvMemorySemanticsAcquireReleaseMask)) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU, AcquireRelease must be set for Memory " - "Semantics of OpControlBarrier."; - } - - if (!(value & SpvMemorySemanticsWorkgroupMemoryMask)) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU, WorkgroupMemory must be set for Memory " - "Semantics of OpControlBarrier."; - } - - valid_bits = SpvMemorySemanticsAcquireReleaseMask | - SpvMemorySemanticsWorkgroupMemoryMask; - if (value & ~valid_bits) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU only WorkgroupMemory and AcquireRelease may be " - "set for Memory Semantics of OpControlBarrier."; - } - break; - case SpvOpMemoryBarrier: - if (!(value & SpvMemorySemanticsImageMemoryMask)) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU, ImageMemory must be set for Memory Semantics " - "of OpMemoryBarrier."; - } - valid_bits = SpvMemorySemanticsImageMemoryMask; - if (value & ~valid_bits) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU only ImageMemory may be set for Memory " - "Semantics of OpMemoryBarrier."; - } - break; - default: - if (spvOpcodeIsAtomicOp(inst->opcode())) { - if (value != 0) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "For WebGPU Memory no bits may be set for Memory " - "Semantics of OpAtomic* instructions."; - } - } - break; - } - } - const size_t num_memory_order_set_bits = spvtools::utils::CountSetBits( value & (SpvMemorySemanticsAcquireMask | SpvMemorySemanticsReleaseMask | SpvMemorySemanticsAcquireReleaseMask | @@ -221,17 +173,29 @@ spv_result_t ValidateMemorySemantics(ValidationState_t& _, if (opcode == SpvOpMemoryBarrier && !num_memory_order_set_bits) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) + << _.VkErrorID(4732) << spvOpcodeString(opcode) << ": Vulkan specification requires Memory Semantics to have " "one " "of the following bits set: Acquire, Release, " "AcquireRelease " "or SequentiallyConsistent"; + } else if (opcode != SpvOpMemoryBarrier && num_memory_order_set_bits) { + // should leave only atomics and control barriers for Vulkan env + bool memory_is_int32 = false, memory_is_const_int32 = false; + uint32_t memory_value = 0; + std::tie(memory_is_int32, memory_is_const_int32, memory_value) = + _.EvalInt32IfConst(memory_scope); + if (memory_is_int32 && memory_value == SpvScopeInvocation) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4641) << spvOpcodeString(opcode) + << ": Vulkan specification requires Memory Semantics to be None " + "if used with Invocation Memory Scope"; + } } if (opcode == SpvOpMemoryBarrier && !includes_storage_class) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) + << _.VkErrorID(4733) << spvOpcodeString(opcode) << ": expected Memory Semantics to include a Vulkan-supported " "storage class"; } @@ -272,6 +236,7 @@ spv_result_t ValidateMemorySemantics(ValidationState_t& _, value & SpvMemorySemanticsAcquireReleaseMask || value & SpvMemorySemanticsSequentiallyConsistentMask)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4731) << "Vulkan spec disallows OpAtomicLoad with Memory Semantics " "Release, AcquireRelease and SequentiallyConsistent"; } @@ -281,6 +246,7 @@ spv_result_t ValidateMemorySemantics(ValidationState_t& _, value & SpvMemorySemanticsAcquireReleaseMask || value & SpvMemorySemanticsSequentiallyConsistentMask)) { return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4730) << "Vulkan spec disallows OpAtomicStore with Memory Semantics " "Acquire, AcquireRelease and SequentiallyConsistent"; } diff --git a/third_party/spirv-tools/source/val/validate_memory_semantics.h b/third_party/spirv-tools/source/val/validate_memory_semantics.h index 72a3e10048..9e6f93a367 100644 --- a/third_party/spirv-tools/source/val/validate_memory_semantics.h +++ b/third_party/spirv-tools/source/val/validate_memory_semantics.h @@ -22,7 +22,8 @@ namespace val { spv_result_t ValidateMemorySemantics(ValidationState_t& _, const Instruction* inst, - uint32_t operand_index); + uint32_t operand_index, + uint32_t memory_scope); } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/source/val/validate_misc.cpp b/third_party/spirv-tools/source/val/validate_misc.cpp index f0deedfad6..3bc15ca04b 100644 --- a/third_party/spirv-tools/source/val/validate_misc.cpp +++ b/third_party/spirv-tools/source/val/validate_misc.cpp @@ -26,6 +26,10 @@ namespace val { namespace { spv_result_t ValidateUndef(ValidationState_t& _, const Instruction* inst) { + if (_.IsVoidType(inst->type_id())) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Cannot create undefined values with void type"; + } if (_.HasCapability(SpvCapabilityShader) && _.ContainsLimitedUseIntOrFloatType(inst->type_id()) && !_.IsPointerType(inst->type_id())) { @@ -33,10 +37,6 @@ spv_result_t ValidateUndef(ValidationState_t& _, const Instruction* inst) { << "Cannot create undefined values with 8- or 16-bit types"; } - if (spvIsWebGPUEnv(_.context()->target_env)) { - return _.diag(SPV_ERROR_INVALID_BINARY, inst) << "OpUndef is disallowed"; - } - return SPV_SUCCESS; } @@ -52,7 +52,7 @@ spv_result_t ValidateShaderClock(ValidationState_t& _, std::tie(is_int32, is_const_int32, value) = _.EvalInt32IfConst(scope); if (is_const_int32 && value != SpvScopeSubgroup && value != SpvScopeDevice) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Scope must be Subgroup or Device"; + << _.VkErrorID(4652) << "Scope must be Subgroup or Device"; } // Result Type must be a 64 - bit unsigned integer type or @@ -72,6 +72,37 @@ spv_result_t ValidateShaderClock(ValidationState_t& _, return SPV_SUCCESS; } +spv_result_t ValidateAssumeTrue(ValidationState_t& _, const Instruction* inst) { + const auto operand_type_id = _.GetOperandTypeId(inst, 0); + if (!operand_type_id || !_.IsBoolScalarType(operand_type_id)) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Value operand of OpAssumeTrueKHR must be a boolean scalar"; + } + return SPV_SUCCESS; +} + +spv_result_t ValidateExpect(ValidationState_t& _, const Instruction* inst) { + const auto result_type = inst->type_id(); + if (!_.IsBoolScalarOrVectorType(result_type) && + !_.IsIntScalarOrVectorType(result_type)) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Result of OpExpectKHR must be a scalar or vector of integer " + "type or boolean type"; + } + + if (_.GetOperandTypeId(inst, 2) != result_type) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Type of Value operand of OpExpectKHR does not match the result " + "type "; + } + if (_.GetOperandTypeId(inst, 3) != result_type) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << "Type of ExpectedValue operand of OpExpectKHR does not match the " + "result type "; + } + return SPV_SUCCESS; +} + } // namespace spv_result_t MiscPass(ValidationState_t& _, const Instruction* inst) { @@ -152,6 +183,16 @@ spv_result_t MiscPass(ValidationState_t& _, const Instruction* inst) { return error; } break; + case SpvOpAssumeTrueKHR: + if (auto error = ValidateAssumeTrue(_, inst)) { + return error; + } + break; + case SpvOpExpectKHR: + if (auto error = ValidateExpect(_, inst)) { + return error; + } + break; default: break; } diff --git a/third_party/spirv-tools/source/val/validate_mode_setting.cpp b/third_party/spirv-tools/source/val/validate_mode_setting.cpp index a7f8d33958..79f82d8d76 100644 --- a/third_party/spirv-tools/source/val/validate_mode_setting.cpp +++ b/third_party/spirv-tools/source/val/validate_mode_setting.cpp @@ -42,7 +42,8 @@ spv_result_t ValidateEntryPoint(ValidationState_t& _, const Instruction* inst) { const auto entry_point_type = _.FindDef(entry_point_type_id); if (!entry_point_type || 3 != entry_point_type->words().size()) { return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpEntryPoint Entry Point '" << _.getIdName(entry_point_id) + << _.VkErrorID(4633) << "OpEntryPoint Entry Point '" + << _.getIdName(entry_point_id) << "'s function parameter count is not zero."; } } @@ -50,7 +51,8 @@ spv_result_t ValidateEntryPoint(ValidationState_t& _, const Instruction* inst) { auto return_type = _.FindDef(entry_point->type_id()); if (!return_type || SpvOpTypeVoid != return_type->opcode()) { return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpEntryPoint Entry Point '" << _.getIdName(entry_point_id) + << _.VkErrorID(4633) << "OpEntryPoint Entry Point '" + << _.getIdName(entry_point_id) << "'s function return type is not void."; } @@ -226,6 +228,7 @@ spv_result_t ValidateEntryPoint(ValidationState_t& _, const Instruction* inst) { } if (!ok) { return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4683) << "In the Vulkan environment, GLCompute execution model " "entry points require either the LocalSize execution " "mode or an object decorated with WorkgroupSize must be " @@ -457,31 +460,18 @@ spv_result_t ValidateExecutionMode(ValidationState_t& _, if (spvIsVulkanEnv(_.context()->target_env)) { if (mode == SpvExecutionModeOriginLowerLeft) { return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4653) << "In the Vulkan environment, the OriginLowerLeft execution mode " "must not be used."; } if (mode == SpvExecutionModePixelCenterInteger) { return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4654) << "In the Vulkan environment, the PixelCenterInteger execution " "mode must not be used."; } } - if (spvIsWebGPUEnv(_.context()->target_env)) { - if (mode != SpvExecutionModeOriginUpperLeft && - mode != SpvExecutionModeDepthReplacing && - mode != SpvExecutionModeDepthGreater && - mode != SpvExecutionModeDepthLess && - mode != SpvExecutionModeDepthUnchanged && - mode != SpvExecutionModeLocalSize && - mode != SpvExecutionModeLocalSizeHint) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Execution mode must be one of OriginUpperLeft, " - "DepthReplacing, DepthGreater, DepthLess, DepthUnchanged, " - "LocalSize, or LocalSizeHint for WebGPU environment."; - } - } - return SPV_SUCCESS; } @@ -496,13 +486,6 @@ spv_result_t ValidateMemoryModel(ValidationState_t& _, "the VulkanKHR memory model is used."; } - if (spvIsWebGPUEnv(_.context()->target_env)) { - if (_.addressing_model() != SpvAddressingModelLogical) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << "Addressing model must be Logical for WebGPU environment."; - } - } - if (spvIsOpenCLEnv(_.context()->target_env)) { if ((_.addressing_model() != SpvAddressingModelPhysical32) && (_.addressing_model() != SpvAddressingModelPhysical64)) { @@ -516,6 +499,15 @@ spv_result_t ValidateMemoryModel(ValidationState_t& _, } } + if (spvIsVulkanEnv(_.context()->target_env)) { + if ((_.addressing_model() != SpvAddressingModelLogical) && + (_.addressing_model() != SpvAddressingModelPhysicalStorageBuffer64)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4635) + << "Addressing model must be Logical or PhysicalStorageBuffer64 " + << "in the Vulkan environment."; + } + } return SPV_SUCCESS; } diff --git a/third_party/spirv-tools/source/val/validate_non_uniform.cpp b/third_party/spirv-tools/source/val/validate_non_uniform.cpp index 8dcf9743f5..2b6eb8b5bf 100644 --- a/third_party/spirv-tools/source/val/validate_non_uniform.cpp +++ b/third_party/spirv-tools/source/val/validate_non_uniform.cpp @@ -47,6 +47,19 @@ spv_result_t ValidateGroupNonUniformBallotBitCount(ValidationState_t& _, "vector of four components " "of integer type scalar"; } + + const auto group = inst->GetOperandAs(3); + if (spvIsVulkanEnv(_.context()->target_env)) { + if ((group != SpvGroupOperationReduce) && + (group != SpvGroupOperationInclusiveScan) && + (group != SpvGroupOperationExclusiveScan)) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4685) + << "In Vulkan: The OpGroupNonUniformBallotBitCount group " + "operation must be only: Reduce, InclusiveScan, or " + "ExclusiveScan."; + } + } return SPV_SUCCESS; } diff --git a/third_party/spirv-tools/source/val/validate_scopes.cpp b/third_party/spirv-tools/source/val/validate_scopes.cpp index a6fb26dad0..29ba583173 100644 --- a/third_party/spirv-tools/source/val/validate_scopes.cpp +++ b/third_party/spirv-tools/source/val/validate_scopes.cpp @@ -99,27 +99,36 @@ spv_result_t ValidateExecutionScope(ValidationState_t& _, if (spvOpcodeIsNonUniformGroupOperation(opcode) && value != SpvScopeSubgroup) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) + << _.VkErrorID(4642) << spvOpcodeString(opcode) << ": in Vulkan environment Execution scope is limited to " << "Subgroup"; } } - // If OpControlBarrier is used in fragment, vertex, tessellation evaluation, - // or geometry stages, the execution Scope must be Subgroup. + // OpControlBarrier must only use Subgroup execution scope for a subset of + // execution models. if (opcode == SpvOpControlBarrier && value != SpvScopeSubgroup) { + std::string errorVUID = _.VkErrorID(4682); _.function(inst->function()->id()) - ->RegisterExecutionModelLimitation([](SpvExecutionModel model, - std::string* message) { + ->RegisterExecutionModelLimitation([errorVUID]( + SpvExecutionModel model, + std::string* message) { if (model == SpvExecutionModelFragment || model == SpvExecutionModelVertex || model == SpvExecutionModelGeometry || - model == SpvExecutionModelTessellationEvaluation) { + model == SpvExecutionModelTessellationEvaluation || + model == SpvExecutionModelRayGenerationKHR || + model == SpvExecutionModelIntersectionKHR || + model == SpvExecutionModelAnyHitKHR || + model == SpvExecutionModelClosestHitKHR || + model == SpvExecutionModelMissKHR) { if (message) { *message = - "in Vulkan evironment, OpControlBarrier execution scope " - "must be Subgroup for Fragment, Vertex, Geometry and " - "TessellationEvaluation execution models"; + errorVUID + + "in Vulkan environment, OpControlBarrier execution scope " + "must be Subgroup for Fragment, Vertex, Geometry, " + "TessellationEvaluation, RayGeneration, Intersection, " + "AnyHit, ClosestHit, and Miss execution models"; } return false; } @@ -127,38 +136,37 @@ spv_result_t ValidateExecutionScope(ValidationState_t& _, }); } - // Vulkan generic rules - // Scope for execution must be limited to Workgroup or Subgroup - if (value != SpvScopeWorkgroup && value != SpvScopeSubgroup) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": in Vulkan environment Execution Scope is limited to " - << "Workgroup and Subgroup"; - } - } - - // WebGPU Specific rules - if (spvIsWebGPUEnv(_.context()->target_env)) { - if (value != SpvScopeWorkgroup) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": in WebGPU environment Execution Scope is limited to " - << "Workgroup"; - } else { + // Only subset of execution models support Workgroup. + if (value == SpvScopeWorkgroup) { + std::string errorVUID = _.VkErrorID(4637); _.function(inst->function()->id()) ->RegisterExecutionModelLimitation( - [](SpvExecutionModel model, std::string* message) { - if (model != SpvExecutionModelGLCompute) { + [errorVUID](SpvExecutionModel model, std::string* message) { + if (model != SpvExecutionModelTaskNV && + model != SpvExecutionModelMeshNV && + model != SpvExecutionModelTessellationControl && + model != SpvExecutionModelGLCompute) { if (message) { *message = - ": in WebGPU environment, Workgroup Execution Scope is " - "limited to GLCompute execution model"; + errorVUID + + "in Vulkan environment, Workgroup execution scope is " + "only for TaskNV, MeshNV, TessellationControl, and " + "GLCompute execution models"; } return false; } return true; }); } + + // Vulkan generic rules + // Scope for execution must be limited to Workgroup or Subgroup + if (value != SpvScopeWorkgroup && value != SpvScopeSubgroup) { + return _.diag(SPV_ERROR_INVALID_DATA, inst) + << _.VkErrorID(4636) << spvOpcodeString(opcode) + << ": in Vulkan environment Execution Scope is limited to " + << "Workgroup and Subgroup"; + } } // TODO(atgoo@github.com) Add checks for OpenCL and OpenGL environments. @@ -214,7 +222,7 @@ spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, if (spvIsVulkanEnv(_.context()->target_env)) { if (value == SpvScopeCrossDevice) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) + << _.VkErrorID(4638) << spvOpcodeString(opcode) << ": in Vulkan environment, Memory Scope cannot be CrossDevice"; } // Vulkan 1.0 specifc rules @@ -222,7 +230,7 @@ spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, value != SpvScopeDevice && value != SpvScopeWorkgroup && value != SpvScopeInvocation) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) + << _.VkErrorID(4638) << spvOpcodeString(opcode) << ": in Vulkan 1.0 environment Memory Scope is limited to " << "Device, Workgroup and Invocation"; } @@ -233,15 +241,16 @@ spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, value != SpvScopeSubgroup && value != SpvScopeInvocation && value != SpvScopeShaderCallKHR) { return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) + << _.VkErrorID(4638) << spvOpcodeString(opcode) << ": in Vulkan 1.1 and 1.2 environment Memory Scope is limited " << "to Device, Workgroup, Invocation, and ShaderCall"; } if (value == SpvScopeShaderCallKHR) { + std::string errorVUID = _.VkErrorID(4640); _.function(inst->function()->id()) ->RegisterExecutionModelLimitation( - [](SpvExecutionModel model, std::string* message) { + [errorVUID](SpvExecutionModel model, std::string* message) { if (model != SpvExecutionModelRayGenerationKHR && model != SpvExecutionModelIntersectionKHR && model != SpvExecutionModelAnyHitKHR && @@ -250,6 +259,7 @@ spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, model != SpvExecutionModelCallableKHR) { if (message) { *message = + errorVUID + "ShaderCallKHR Memory Scope requires a ray tracing " "execution model"; } @@ -258,56 +268,19 @@ spv_result_t ValidateMemoryScope(ValidationState_t& _, const Instruction* inst, return true; }); } - } - - // WebGPU specific rules - if (spvIsWebGPUEnv(_.context()->target_env)) { - switch (inst->opcode()) { - case SpvOpControlBarrier: - if (value != SpvScopeWorkgroup) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": in WebGPU environment Memory Scope is limited to " - << "Workgroup for OpControlBarrier"; - } - break; - case SpvOpMemoryBarrier: - if (value != SpvScopeWorkgroup) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": in WebGPU environment Memory Scope is limited to " - << "Workgroup for OpMemoryBarrier"; - } - break; - default: - if (spvOpcodeIsAtomicOp(inst->opcode())) { - if (value != SpvScopeQueueFamilyKHR) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": in WebGPU environment Memory Scope is limited to " - << "QueueFamilyKHR for OpAtomic* operations"; - } - } - - if (value != SpvScopeWorkgroup && value != SpvScopeInvocation && - value != SpvScopeQueueFamilyKHR) { - return _.diag(SPV_ERROR_INVALID_DATA, inst) - << spvOpcodeString(opcode) - << ": in WebGPU environment Memory Scope is limited to " - << "Workgroup, Invocation, and QueueFamilyKHR"; - } - break; - } if (value == SpvScopeWorkgroup) { + std::string errorVUID = _.VkErrorID(4639); _.function(inst->function()->id()) ->RegisterExecutionModelLimitation( - [](SpvExecutionModel model, std::string* message) { - if (model != SpvExecutionModelGLCompute) { + [errorVUID](SpvExecutionModel model, std::string* message) { + if (model != SpvExecutionModelGLCompute && + model != SpvExecutionModelTaskNV && + model != SpvExecutionModelMeshNV) { if (message) { - *message = - ": in WebGPU environment, Workgroup Memory Scope is " - "limited to GLCompute execution model"; + *message = errorVUID + + "Workgroup Memory Scope is limited to MeshNV, " + "TaskNV, and GLCompute execution model"; } return false; } diff --git a/third_party/spirv-tools/source/val/validate_type.cpp b/third_party/spirv-tools/source/val/validate_type.cpp index 5924c69fa4..612fc5c2ce 100644 --- a/third_party/spirv-tools/source/val/validate_type.cpp +++ b/third_party/spirv-tools/source/val/validate_type.cpp @@ -40,21 +40,6 @@ int64_t ConstantLiteralAsInt64(uint32_t width, return static_cast(uint64_t(lo_word) | uint64_t(hi_word) << 32); } -// Returns, as an uint64_t, the literal value from an OpConstant or the -// default value of an OpSpecConstant, assuming it is an integral type. -// For signed integers, relies the rule that literal value is sign extended -// to fill out to word granularity. Assumes that the constant value -// has -int64_t ConstantLiteralAsUint64(uint32_t width, - const std::vector& const_words) { - const uint32_t lo_word = const_words[3]; - if (width <= 32) return lo_word; - assert(width <= 64); - assert(const_words.size() > 4); - const uint32_t hi_word = const_words[4]; // Must exist, per spec. - return (uint64_t(lo_word) | uint64_t(hi_word) << 32); -} - // Validates that type declarations are unique, unless multiple declarations // of the same data type are allowed by the specification. // (see section 2.8 Types and Variables) @@ -240,7 +225,7 @@ spv_result_t ValidateTypeArray(ValidationState_t& _, const Instruction* inst) { << "' is a void type."; } - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env) && + if (spvIsVulkanEnv(_.context()->target_env) && element_type->opcode() == SpvOpTypeRuntimeArray) { return _.diag(SPV_ERROR_INVALID_ID, inst) << "OpTypeArray Element Type '" << _.getIdName(element_type_id) @@ -279,18 +264,6 @@ spv_result_t ValidateTypeArray(ValidationState_t& _, const Instruction* inst) { << "OpTypeArray Length '" << _.getIdName(length_id) << "' default value must be at least 1: found " << ivalue; } - if (spvIsWebGPUEnv(_.context()->target_env)) { - // WebGPU has maximum integer width of 32 bits, and max array size - // is one more than the max signed integer representation. - const uint64_t max_permitted = (uint64_t(1) << 31); - const uint64_t uvalue = ConstantLiteralAsUint64(width, length->words()); - if (uvalue > max_permitted) { - return _.diag(SPV_ERROR_INVALID_ID, inst) - << "OpTypeArray Length '" << _.getIdName(length_id) - << "' size exceeds max value " << max_permitted - << " permitted by WebGPU: got " << uvalue; - } - } } break; case SpvOpConstantNull: return _.diag(SPV_ERROR_INVALID_ID, inst) @@ -322,7 +295,7 @@ spv_result_t ValidateTypeRuntimeArray(ValidationState_t& _, << _.getIdName(element_id) << "' is a void type."; } - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env) && + if (spvIsVulkanEnv(_.context()->target_env) && element_type->opcode() == SpvOpTypeRuntimeArray) { return _.diag(SPV_ERROR_INVALID_ID, inst) << "OpTypeRuntimeArray Element Type '" @@ -394,7 +367,7 @@ spv_result_t ValidateTypeStruct(ValidationState_t& _, const Instruction* inst) { << "."; } - if (spvIsVulkanOrWebGPUEnv(_.context()->target_env) && + if (spvIsVulkanEnv(_.context()->target_env) && member_type->opcode() == SpvOpTypeRuntimeArray) { const bool is_last_member = member_type_index == inst->operands().size() - 1; @@ -454,7 +427,8 @@ spv_result_t ValidateTypeStruct(ValidationState_t& _, const Instruction* inst) { if (spvIsVulkanEnv(_.context()->target_env) && !_.options()->before_hlsl_legalization && ContainsOpaqueType(_, inst)) { return _.diag(SPV_ERROR_INVALID_ID, inst) - << "In " << spvLogStringForEnv(_.context()->target_env) + << _.VkErrorID(4667) << "In " + << spvLogStringForEnv(_.context()->target_env) << ", OpTypeStruct must not contain an opaque type."; } @@ -489,6 +463,7 @@ spv_result_t ValidateTypePointer(ValidationState_t& _, if (!_.IsValidStorageClass(storage_class)) { return _.diag(SPV_ERROR_INVALID_BINARY, inst) + << _.VkErrorID(4643) << "Invalid storage class for target environment"; } @@ -555,8 +530,8 @@ spv_result_t ValidateTypeForwardPointer(ValidationState_t& _, << "Pointer type in OpTypeForwardPointer is not a pointer type."; } - if (inst->GetOperandAs(1) != - pointer_type_inst->GetOperandAs(1)) { + const auto storage_class = inst->GetOperandAs(1); + if (storage_class != pointer_type_inst->GetOperandAs(1)) { return _.diag(SPV_ERROR_INVALID_ID, inst) << "Storage class in OpTypeForwardPointer does not match the " << "pointer definition."; @@ -569,6 +544,15 @@ spv_result_t ValidateTypeForwardPointer(ValidationState_t& _, << "Forward pointers must point to a structure"; } + if (spvIsVulkanEnv(_.context()->target_env)) { + if (storage_class != SpvStorageClassPhysicalStorageBuffer) { + return _.diag(SPV_ERROR_INVALID_ID, inst) + << _.VkErrorID(4711) + << "In Vulkan, OpTypeForwardPointer must have " + << "a storage class of PhysicalStorageBuffer."; + } + } + return SPV_SUCCESS; } diff --git a/third_party/spirv-tools/source/val/validation_state.cpp b/third_party/spirv-tools/source/val/validation_state.cpp index cb69dda309..52821636bf 100644 --- a/third_party/spirv-tools/source/val/validation_state.cpp +++ b/third_party/spirv-tools/source/val/validation_state.cpp @@ -359,6 +359,7 @@ void ValidationState_t::RegisterCapability(SpvCapability cap) { case SpvCapabilityStorageBuffer8BitAccess: case SpvCapabilityUniformAndStorageBuffer8BitAccess: case SpvCapabilityStoragePushConstant8: + case SpvCapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR: features_.declare_int8_type = true; break; case SpvCapabilityInt16: @@ -372,6 +373,7 @@ void ValidationState_t::RegisterCapability(SpvCapability cap) { case SpvCapabilityStorageUniform16: case SpvCapabilityStoragePushConstant16: case SpvCapabilityStorageInputOutput16: + case SpvCapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR: features_.declare_int16_type = true; features_.declare_float16_type = true; features_.free_fp_rounding_mode = true; @@ -518,17 +520,39 @@ void ValidationState_t::RegisterDebugInstruction(const Instruction* inst) { void ValidationState_t::RegisterInstruction(Instruction* inst) { if (inst->id()) all_definitions_.insert(std::make_pair(inst->id(), inst)); - // If the instruction is using an OpTypeSampledImage as an operand, it should - // be recorded. The validator will ensure that all usages of an - // OpTypeSampledImage and its definition are in the same basic block. + // Some validation checks are easier by getting all the consumers for (uint16_t i = 0; i < inst->operands().size(); ++i) { const spv_parsed_operand_t& operand = inst->operand(i); - if (SPV_OPERAND_TYPE_ID == operand.type) { + if ((SPV_OPERAND_TYPE_ID == operand.type) || + (SPV_OPERAND_TYPE_TYPE_ID == operand.type)) { const uint32_t operand_word = inst->word(operand.offset); Instruction* operand_inst = FindDef(operand_word); - if (operand_inst && SpvOpSampledImage == operand_inst->opcode()) { + if (!operand_inst) { + continue; + } + + // If the instruction is using an OpTypeSampledImage as an operand, it + // should be recorded. The validator will ensure that all usages of an + // OpTypeSampledImage and its definition are in the same basic block. + if ((SPV_OPERAND_TYPE_ID == operand.type) && + (SpvOpSampledImage == operand_inst->opcode())) { RegisterSampledImageConsumer(operand_word, inst); } + + // In order to track storage classes (not Function) used per execution + // model we can't use RegisterExecutionModelLimitation on instructions + // like OpTypePointer which are going to be in the pre-function section. + // Instead just need to register storage class usage for consumers in a + // function block. + if (inst->function()) { + if (operand_inst->opcode() == SpvOpTypePointer) { + RegisterStorageClassConsumer( + operand_inst->GetOperandAs(1), inst); + } else if (operand_inst->opcode() == SpvOpVariable) { + RegisterStorageClassConsumer( + operand_inst->GetOperandAs(2), inst); + } + } } } } @@ -548,6 +572,57 @@ void ValidationState_t::RegisterSampledImageConsumer(uint32_t sampled_image_id, sampled_image_consumers_[sampled_image_id].push_back(consumer); } +void ValidationState_t::RegisterStorageClassConsumer( + SpvStorageClass storage_class, Instruction* consumer) { + if (spvIsVulkanEnv(context()->target_env)) { + if (storage_class == SpvStorageClassOutput) { + std::string errorVUID = VkErrorID(4644); + function(consumer->function()->id()) + ->RegisterExecutionModelLimitation([errorVUID]( + SpvExecutionModel model, std::string* message) { + if (model == SpvExecutionModelGLCompute || + model == SpvExecutionModelRayGenerationKHR || + model == SpvExecutionModelIntersectionKHR || + model == SpvExecutionModelAnyHitKHR || + model == SpvExecutionModelClosestHitKHR || + model == SpvExecutionModelMissKHR || + model == SpvExecutionModelCallableKHR) { + if (message) { + *message = + errorVUID + + "in Vulkan evironment, Output Storage Class must not be " + "used in GLCompute, RayGenerationKHR, IntersectionKHR, " + "AnyHitKHR, ClosestHitKHR, MissKHR, or CallableKHR " + "execution models"; + } + return false; + } + return true; + }); + } + + if (storage_class == SpvStorageClassWorkgroup) { + std::string errorVUID = VkErrorID(4645); + function(consumer->function()->id()) + ->RegisterExecutionModelLimitation([errorVUID]( + SpvExecutionModel model, std::string* message) { + if (model != SpvExecutionModelGLCompute && + model != SpvExecutionModelTaskNV && + model != SpvExecutionModelMeshNV) { + if (message) { + *message = + errorVUID + + "in Vulkan evironment, Workgroup Storage Class is limited " + "to MeshNV, TaskNV, and GLCompute execution model"; + } + return false; + } + return true; + }); + } + } +} + uint32_t ValidationState_t::getIdBound() const { return id_bound_; } void ValidationState_t::setIdBound(const uint32_t bound) { id_bound_ = bound; } @@ -1240,23 +1315,6 @@ bool ValidationState_t::ContainsLimitedUseIntOrFloatType(uint32_t id) const { bool ValidationState_t::IsValidStorageClass( SpvStorageClass storage_class) const { - if (spvIsWebGPUEnv(context()->target_env)) { - switch (storage_class) { - case SpvStorageClassUniformConstant: - case SpvStorageClassUniform: - case SpvStorageClassStorageBuffer: - case SpvStorageClassInput: - case SpvStorageClassOutput: - case SpvStorageClassImage: - case SpvStorageClassWorkgroup: - case SpvStorageClassPrivate: - case SpvStorageClassFunction: - return true; - default: - return false; - } - } - if (spvIsVulkanEnv(context()->target_env)) { switch (storage_class) { case SpvStorageClassUniformConstant: @@ -1270,12 +1328,12 @@ bool ValidationState_t::IsValidStorageClass( case SpvStorageClassFunction: case SpvStorageClassPushConstant: case SpvStorageClassPhysicalStorageBuffer: - case SpvStorageClassRayPayloadNV: - case SpvStorageClassIncomingRayPayloadNV: - case SpvStorageClassHitAttributeNV: - case SpvStorageClassCallableDataNV: - case SpvStorageClassIncomingCallableDataNV: - case SpvStorageClassShaderRecordBufferNV: + case SpvStorageClassRayPayloadKHR: + case SpvStorageClassIncomingRayPayloadKHR: + case SpvStorageClassHitAttributeKHR: + case SpvStorageClassCallableDataKHR: + case SpvStorageClassIncomingCallableDataKHR: + case SpvStorageClassShaderRecordBufferKHR: return true; default: return false; @@ -1315,10 +1373,22 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-BaseVertex-BaseVertex-04186); case 4187: return VUID_WRAP(VUID-ClipDistance-ClipDistance-04187); + case 4188: + return VUID_WRAP(VUID-ClipDistance-ClipDistance-04188); + case 4189: + return VUID_WRAP(VUID-ClipDistance-ClipDistance-04189); + case 4190: + return VUID_WRAP(VUID-ClipDistance-ClipDistance-04190); case 4191: return VUID_WRAP(VUID-ClipDistance-ClipDistance-04191); case 4196: return VUID_WRAP(VUID-CullDistance-CullDistance-04196); + case 4197: + return VUID_WRAP(VUID-CullDistance-CullDistance-04197); + case 4198: + return VUID_WRAP(VUID-CullDistance-CullDistance-04198); + case 4199: + return VUID_WRAP(VUID-CullDistance-CullDistance-04199); case 4200: return VUID_WRAP(VUID-CullDistance-CullDistance-04200); case 4205: @@ -1345,12 +1415,36 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-FragDepth-FragDepth-04215); case 4216: return VUID_WRAP(VUID-FragDepth-FragDepth-04216); + case 4217: + return VUID_WRAP(VUID-FragInvocationCountEXT-FragInvocationCountEXT-04217); + case 4218: + return VUID_WRAP(VUID-FragInvocationCountEXT-FragInvocationCountEXT-04218); + case 4219: + return VUID_WRAP(VUID-FragInvocationCountEXT-FragInvocationCountEXT-04219); + case 4220: + return VUID_WRAP(VUID-FragSizeEXT-FragSizeEXT-04220); + case 4221: + return VUID_WRAP(VUID-FragSizeEXT-FragSizeEXT-04221); + case 4222: + return VUID_WRAP(VUID-FragSizeEXT-FragSizeEXT-04222); + case 4223: + return VUID_WRAP(VUID-FragStencilRefEXT-FragStencilRefEXT-04223); + case 4224: + return VUID_WRAP(VUID-FragStencilRefEXT-FragStencilRefEXT-04224); + case 4225: + return VUID_WRAP(VUID-FragStencilRefEXT-FragStencilRefEXT-04225); case 4229: return VUID_WRAP(VUID-FrontFacing-FrontFacing-04229); case 4230: return VUID_WRAP(VUID-FrontFacing-FrontFacing-04230); case 4231: return VUID_WRAP(VUID-FrontFacing-FrontFacing-04231); + case 4232: + return VUID_WRAP(VUID-FullyCoveredEXT-FullyCoveredEXT-04232); + case 4233: + return VUID_WRAP(VUID-FullyCoveredEXT-FullyCoveredEXT-04233); + case 4234: + return VUID_WRAP(VUID-FullyCoveredEXT-FullyCoveredEXT-04234); case 4236: return VUID_WRAP(VUID-GlobalInvocationId-GlobalInvocationId-04236); case 4237: @@ -1363,6 +1457,36 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-HelperInvocation-HelperInvocation-04240); case 4241: return VUID_WRAP(VUID-HelperInvocation-HelperInvocation-04241); + case 4242: + return VUID_WRAP(VUID-HitKindKHR-HitKindKHR-04242); + case 4243: + return VUID_WRAP(VUID-HitKindKHR-HitKindKHR-04243); + case 4244: + return VUID_WRAP(VUID-HitKindKHR-HitKindKHR-04244); + case 4245: + return VUID_WRAP(VUID-HitTNV-HitTNV-04245); + case 4246: + return VUID_WRAP(VUID-HitTNV-HitTNV-04246); + case 4247: + return VUID_WRAP(VUID-HitTNV-HitTNV-04247); + case 4248: + return VUID_WRAP(VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04248); + case 4249: + return VUID_WRAP(VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04249); + case 4250: + return VUID_WRAP(VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04250); + case 4251: + return VUID_WRAP(VUID-InstanceCustomIndexKHR-InstanceCustomIndexKHR-04251); + case 4252: + return VUID_WRAP(VUID-InstanceCustomIndexKHR-InstanceCustomIndexKHR-04252); + case 4253: + return VUID_WRAP(VUID-InstanceCustomIndexKHR-InstanceCustomIndexKHR-04253); + case 4254: + return VUID_WRAP(VUID-InstanceId-InstanceId-04254); + case 4255: + return VUID_WRAP(VUID-InstanceId-InstanceId-04255); + case 4256: + return VUID_WRAP(VUID-InstanceId-InstanceId-04256); case 4257: return VUID_WRAP(VUID-InvocationId-InvocationId-04257); case 4258: @@ -1375,8 +1499,22 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-InstanceIndex-InstanceIndex-04264); case 4265: return VUID_WRAP(VUID-InstanceIndex-InstanceIndex-04265); + case 4266: + return VUID_WRAP(VUID-LaunchIdKHR-LaunchIdKHR-04266); + case 4267: + return VUID_WRAP(VUID-LaunchIdKHR-LaunchIdKHR-04267); + case 4268: + return VUID_WRAP(VUID-LaunchIdKHR-LaunchIdKHR-04268); + case 4269: + return VUID_WRAP(VUID-LaunchSizeKHR-LaunchSizeKHR-04269); + case 4270: + return VUID_WRAP(VUID-LaunchSizeKHR-LaunchSizeKHR-04270); + case 4271: + return VUID_WRAP(VUID-LaunchSizeKHR-LaunchSizeKHR-04271); case 4272: return VUID_WRAP(VUID-Layer-Layer-04272); + case 4273: + return VUID_WRAP(VUID-Layer-Layer-04273); case 4274: return VUID_WRAP(VUID-Layer-Layer-04274); case 4275: @@ -1389,12 +1527,36 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-LocalInvocationId-LocalInvocationId-04282); case 4283: return VUID_WRAP(VUID-LocalInvocationId-LocalInvocationId-04283); + case 4293: + return VUID_WRAP(VUID-NumSubgroups-NumSubgroups-04293); + case 4294: + return VUID_WRAP(VUID-NumSubgroups-NumSubgroups-04294); + case 4295: + return VUID_WRAP(VUID-NumSubgroups-NumSubgroups-04295); case 4296: return VUID_WRAP(VUID-NumWorkgroups-NumWorkgroups-04296); case 4297: return VUID_WRAP(VUID-NumWorkgroups-NumWorkgroups-04297); case 4298: return VUID_WRAP(VUID-NumWorkgroups-NumWorkgroups-04298); + case 4299: + return VUID_WRAP(VUID-ObjectRayDirectionKHR-ObjectRayDirectionKHR-04299); + case 4300: + return VUID_WRAP(VUID-ObjectRayDirectionKHR-ObjectRayDirectionKHR-04300); + case 4301: + return VUID_WRAP(VUID-ObjectRayDirectionKHR-ObjectRayDirectionKHR-04301); + case 4302: + return VUID_WRAP(VUID-ObjectRayOriginKHR-ObjectRayOriginKHR-04302); + case 4303: + return VUID_WRAP(VUID-ObjectRayOriginKHR-ObjectRayOriginKHR-04303); + case 4304: + return VUID_WRAP(VUID-ObjectRayOriginKHR-ObjectRayOriginKHR-04304); + case 4305: + return VUID_WRAP(VUID-ObjectToWorldKHR-ObjectToWorldKHR-04305); + case 4306: + return VUID_WRAP(VUID-ObjectToWorldKHR-ObjectToWorldKHR-04306); + case 4307: + return VUID_WRAP(VUID-ObjectToWorldKHR-ObjectToWorldKHR-04307); case 4308: return VUID_WRAP(VUID-PatchVertices-PatchVertices-04308); case 4309: @@ -1417,6 +1579,8 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-PointSize-PointSize-04317); case 4318: return VUID_WRAP(VUID-Position-Position-04318); + case 4319: + return VUID_WRAP(VUID-Position-Position-04319); case 4320: return VUID_WRAP(VUID-Position-Position-04320); case 4321: @@ -1427,6 +1591,24 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-PrimitiveId-PrimitiveId-04334); case 4337: return VUID_WRAP(VUID-PrimitiveId-PrimitiveId-04337); + case 4345: + return VUID_WRAP(VUID-RayGeometryIndexKHR-RayGeometryIndexKHR-04345); + case 4346: + return VUID_WRAP(VUID-RayGeometryIndexKHR-RayGeometryIndexKHR-04346); + case 4347: + return VUID_WRAP(VUID-RayGeometryIndexKHR-RayGeometryIndexKHR-04347); + case 4348: + return VUID_WRAP(VUID-RayTmaxKHR-RayTmaxKHR-04348); + case 4349: + return VUID_WRAP(VUID-RayTmaxKHR-RayTmaxKHR-04349); + case 4350: + return VUID_WRAP(VUID-RayTmaxKHR-RayTmaxKHR-04350); + case 4351: + return VUID_WRAP(VUID-RayTminKHR-RayTminKHR-04351); + case 4352: + return VUID_WRAP(VUID-RayTminKHR-RayTminKHR-04352); + case 4353: + return VUID_WRAP(VUID-RayTminKHR-RayTminKHR-04353); case 4354: return VUID_WRAP(VUID-SampleId-SampleId-04354); case 4355: @@ -1445,6 +1627,40 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-SamplePosition-SamplePosition-04361); case 4362: return VUID_WRAP(VUID-SamplePosition-SamplePosition-04362); + case 4367: + return VUID_WRAP(VUID-SubgroupId-SubgroupId-04367); + case 4368: + return VUID_WRAP(VUID-SubgroupId-SubgroupId-04368); + case 4369: + return VUID_WRAP(VUID-SubgroupId-SubgroupId-04369); + case 4370: + return VUID_WRAP(VUID-SubgroupEqMask-SubgroupEqMask-04370); + case 4371: + return VUID_WRAP(VUID-SubgroupEqMask-SubgroupEqMask-04371); + case 4372: + return VUID_WRAP(VUID-SubgroupGeMask-SubgroupGeMask-04372); + case 4373: + return VUID_WRAP(VUID-SubgroupGeMask-SubgroupGeMask-04373); + case 4374: + return VUID_WRAP(VUID-SubgroupGtMask-SubgroupGtMask-04374); + case 4375: + return VUID_WRAP(VUID-SubgroupGtMask-SubgroupGtMask-04375); + case 4376: + return VUID_WRAP(VUID-SubgroupLeMask-SubgroupLeMask-04376); + case 4377: + return VUID_WRAP(VUID-SubgroupLeMask-SubgroupLeMask-04377); + case 4378: + return VUID_WRAP(VUID-SubgroupLtMask-SubgroupLtMask-04378); + case 4379: + return VUID_WRAP(VUID-SubgroupLtMask-SubgroupLtMask-04379); + case 4380: + return VUID_WRAP(VUID-SubgroupLocalInvocationId-SubgroupLocalInvocationId-04380); + case 4381: + return VUID_WRAP(VUID-SubgroupLocalInvocationId-SubgroupLocalInvocationId-04381); + case 4382: + return VUID_WRAP(VUID-SubgroupSize-SubgroupSize-04382); + case 4383: + return VUID_WRAP(VUID-SubgroupSize-SubgroupSize-04383); case 4387: return VUID_WRAP(VUID-TessCoord-TessCoord-04387); case 4388: @@ -1453,10 +1669,18 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-TessCoord-TessCoord-04389); case 4390: return VUID_WRAP(VUID-TessLevelOuter-TessLevelOuter-04390); + case 4391: + return VUID_WRAP(VUID-TessLevelOuter-TessLevelOuter-04391); + case 4392: + return VUID_WRAP(VUID-TessLevelOuter-TessLevelOuter-04392); case 4393: return VUID_WRAP(VUID-TessLevelOuter-TessLevelOuter-04393); case 4394: return VUID_WRAP(VUID-TessLevelInner-TessLevelInner-04394); + case 4395: + return VUID_WRAP(VUID-TessLevelInner-TessLevelInner-04395); + case 4396: + return VUID_WRAP(VUID-TessLevelInner-TessLevelInner-04396); case 4397: return VUID_WRAP(VUID-TessLevelInner-TessLevelInner-04397); case 4398: @@ -1473,6 +1697,8 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-ViewIndex-ViewIndex-04403); case 4404: return VUID_WRAP(VUID-ViewportIndex-ViewportIndex-04404); + case 4405: + return VUID_WRAP(VUID-ViewportIndex-ViewportIndex-04405); case 4406: return VUID_WRAP(VUID-ViewportIndex-ViewportIndex-04406); case 4407: @@ -1491,6 +1717,24 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-WorkgroupSize-WorkgroupSize-04426); case 4427: return VUID_WRAP(VUID-WorkgroupSize-WorkgroupSize-04427); + case 4428: + return VUID_WRAP(VUID-WorldRayDirectionKHR-WorldRayDirectionKHR-04428); + case 4429: + return VUID_WRAP(VUID-WorldRayDirectionKHR-WorldRayDirectionKHR-04429); + case 4430: + return VUID_WRAP(VUID-WorldRayDirectionKHR-WorldRayDirectionKHR-04430); + case 4431: + return VUID_WRAP(VUID-WorldRayOriginKHR-WorldRayOriginKHR-04431); + case 4432: + return VUID_WRAP(VUID-WorldRayOriginKHR-WorldRayOriginKHR-04432); + case 4433: + return VUID_WRAP(VUID-WorldRayOriginKHR-WorldRayOriginKHR-04433); + case 4434: + return VUID_WRAP(VUID-WorldToObjectKHR-WorldToObjectKHR-04434); + case 4435: + return VUID_WRAP(VUID-WorldToObjectKHR-WorldToObjectKHR-04435); + case 4436: + return VUID_WRAP(VUID-WorldToObjectKHR-WorldToObjectKHR-04436); case 4484: return VUID_WRAP(VUID-PrimitiveShadingRateKHR-PrimitiveShadingRateKHR-04484); case 4485: @@ -1503,9 +1747,89 @@ std::string ValidationState_t::VkErrorID(uint32_t id, return VUID_WRAP(VUID-ShadingRateKHR-ShadingRateKHR-04491); case 4492: return VUID_WRAP(VUID-ShadingRateKHR-ShadingRateKHR-04492); + case 4633: + return VUID_WRAP(VUID-StandaloneSpirv-None-04633); + case 4634: + return VUID_WRAP(VUID-StandaloneSpirv-None-04634); + case 4635: + return VUID_WRAP(VUID-StandaloneSpirv-None-04635); + case 4636: + return VUID_WRAP(VUID-StandaloneSpirv-None-04636); + case 4637: + return VUID_WRAP(VUID-StandaloneSpirv-None-04637); + case 4638: + return VUID_WRAP(VUID-StandaloneSpirv-None-04638); + case 4639: + return VUID_WRAP(VUID-StandaloneSpirv-None-04639); + case 4640: + return VUID_WRAP(VUID-StandaloneSpirv-None-04640); + case 4641: + return VUID_WRAP(VUID-StandaloneSpirv-None-04641); + case 4642: + return VUID_WRAP(VUID-StandaloneSpirv-None-04642); + case 4643: + return VUID_WRAP(VUID-StandaloneSpirv-None-04643); + case 4644: + return VUID_WRAP(VUID-StandaloneSpirv-None-04644); + case 4645: + return VUID_WRAP(VUID-StandaloneSpirv-None-04645); + case 4651: + return VUID_WRAP(VUID-StandaloneSpirv-OpVariable-04651); + case 4652: + return VUID_WRAP(VUID-StandaloneSpirv-OpReadClockKHR-04652); + case 4653: + return VUID_WRAP(VUID-StandaloneSpirv-OriginLowerLeft-04653); + case 4654: + return VUID_WRAP(VUID-StandaloneSpirv-PixelCenterInteger-04654); + case 4655: + return VUID_WRAP(VUID-StandaloneSpirv-UniformConstant-04655); + case 4656: + return VUID_WRAP(VUID-StandaloneSpirv-OpTypeImage-04656); + case 4657: + return VUID_WRAP(VUID-StandaloneSpirv-OpTypeImage-04657); + case 4658: + return VUID_WRAP(VUID-StandaloneSpirv-OpImageTexelPointer-04658); + case 4659: + return VUID_WRAP(VUID-StandaloneSpirv-OpImageQuerySizeLod-04659); + case 4662: + return VUID_WRAP(VUID-StandaloneSpirv-Offset-04662); + case 4663: + return VUID_WRAP(VUID-StandaloneSpirv-Offset-04663); + case 4664: + return VUID_WRAP(VUID-StandaloneSpirv-OpImageGather-04664); + case 4667: + return VUID_WRAP(VUID-StandaloneSpirv-None-04667); + case 4669: + return VUID_WRAP(VUID-StandaloneSpirv-GLSLShared-04669); + case 4675: + return VUID_WRAP(VUID-StandaloneSpirv-FPRoundingMode-04675); + case 4677: + return VUID_WRAP(VUID-StandaloneSpirv-Invariant-04677); + case 4682: + return VUID_WRAP(VUID-StandaloneSpirv-OpControlBarrier-04682); + case 4683: + return VUID_WRAP(VUID-StandaloneSpirv-LocalSize-04683); + case 4685: + return VUID_WRAP(VUID-StandaloneSpirv-OpGroupNonUniformBallotBitCount-04685); + case 4686: + return VUID_WRAP(VUID-StandaloneSpirv-None-04686); + case 4710: + return VUID_WRAP(VUID-StandaloneSpirv-PhysicalStorageBuffer64-04710); + case 4711: + return VUID_WRAP(VUID-StandaloneSpirv-OpTypeForwardPointer-04711); + case 4730: + return VUID_WRAP(VUID-StandaloneSpirv-OpAtomicStore-04730); + case 4731: + return VUID_WRAP(VUID-StandaloneSpirv-OpAtomicLoad-04731); + case 4732: + return VUID_WRAP(VUID-StandaloneSpirv-OpMemoryBarrier-04732); + case 4733: + return VUID_WRAP(VUID-StandaloneSpirv-OpMemoryBarrier-04733); + case 4780: + return VUID_WRAP(VUID-StandaloneSpirv-Result-04780); default: return ""; // unknown id - }; + } // clang-format on } diff --git a/third_party/spirv-tools/source/val/validation_state.h b/third_party/spirv-tools/source/val/validation_state.h index aeb1ca861f..57634bf4a0 100644 --- a/third_party/spirv-tools/source/val/validation_state.h +++ b/third_party/spirv-tools/source/val/validation_state.h @@ -103,6 +103,10 @@ class ValidationState_t { // Members need not be listed in offset order bool scalar_block_layout = false; + // Use scalar block layout (as defined above) for Workgroup block + // variables. See VK_KHR_workgroup_memory_explicit_layout. + bool workgroup_scalar_block_layout = false; + // SPIR-V 1.4 allows us to select between any two composite values // of the same type. bool select_between_composites = false; @@ -461,6 +465,10 @@ class ValidationState_t { void RegisterSampledImageConsumer(uint32_t sampled_image_id, Instruction* consumer); + // Record a function's storage class consumer instruction + void RegisterStorageClassConsumer(SpvStorageClass storage_class, + Instruction* consumer); + /// Returns the set of Global Variables. std::unordered_set& global_vars() { return global_vars_; } diff --git a/third_party/spirv-tools/test/binary_parse_test.cpp b/third_party/spirv-tools/test/binary_parse_test.cpp index 93e87bddad..9a13f22ca5 100644 --- a/third_party/spirv-tools/test/binary_parse_test.cpp +++ b/third_party/spirv-tools/test/binary_parse_test.cpp @@ -198,7 +198,7 @@ ParsedInstruction MakeParsedInt32TypeInstruction(uint32_t result_id) { class BinaryParseTest : public spvtest::TextToBinaryTestBase<::testing::Test> { protected: - ~BinaryParseTest() { spvDiagnosticDestroy(diagnostic_); } + ~BinaryParseTest() override { spvDiagnosticDestroy(diagnostic_); } void Parse(const SpirvVector& words, spv_result_t expected_result, bool flip_words = false) { diff --git a/third_party/spirv-tools/test/binary_to_text_test.cpp b/third_party/spirv-tools/test/binary_to_text_test.cpp index e8a02fd59b..9cad9661d1 100644 --- a/third_party/spirv-tools/test/binary_to_text_test.cpp +++ b/third_party/spirv-tools/test/binary_to_text_test.cpp @@ -36,12 +36,12 @@ class BinaryToText : public ::testing::Test { public: BinaryToText() : context(spvContextCreate(SPV_ENV_UNIVERSAL_1_0)), binary(nullptr) {} - ~BinaryToText() { + ~BinaryToText() override { spvBinaryDestroy(binary); spvContextDestroy(context); } - virtual void SetUp() { + void SetUp() override { const char* textStr = R"( OpSource OpenCL_C 12 OpMemoryModel Physical64 OpenCL @@ -72,7 +72,7 @@ class BinaryToText : public ::testing::Test { ASSERT_EQ(SPV_SUCCESS, error); } - virtual void TearDown() { + void TearDown() override { spvBinaryDestroy(binary); binary = nullptr; } diff --git a/third_party/spirv-tools/test/enum_string_mapping_test.cpp b/third_party/spirv-tools/test/enum_string_mapping_test.cpp index 9bbd8ca8de..52aa653e63 100644 --- a/third_party/spirv-tools/test/enum_string_mapping_test.cpp +++ b/third_party/spirv-tools/test/enum_string_mapping_test.cpp @@ -181,6 +181,8 @@ INSTANTIATE_TEST_SUITE_P( {SpvCapabilityDeviceGroup, "DeviceGroup"}, {SpvCapabilityAtomicFloat32AddEXT, "AtomicFloat32AddEXT"}, {SpvCapabilityAtomicFloat64AddEXT, "AtomicFloat64AddEXT"}, + {SpvCapabilityAtomicFloat32MinMaxEXT, "AtomicFloat32MinMaxEXT"}, + {SpvCapabilityAtomicFloat64MinMaxEXT, "AtomicFloat64MinMaxEXT"}, {SpvCapabilityMultiView, "MultiView"}, {SpvCapabilityInt64ImageEXT, "Int64ImageEXT"}, {SpvCapabilitySampleMaskOverrideCoverageNV, diff --git a/third_party/spirv-tools/test/fuzz/CMakeLists.txt b/third_party/spirv-tools/test/fuzz/CMakeLists.txt index 2e93293c52..8acebde6e7 100644 --- a/third_party/spirv-tools/test/fuzz/CMakeLists.txt +++ b/third_party/spirv-tools/test/fuzz/CMakeLists.txt @@ -17,6 +17,7 @@ if (${SPIRV_BUILD_FUZZER}) set(SOURCES fuzz_test_util.h + available_instructions_test.cpp call_graph_test.cpp comparator_deep_blocks_first_test.cpp data_synonym_transformation_test.cpp @@ -30,6 +31,7 @@ if (${SPIRV_BUILD_FUZZER}) fuzzer_pass_construct_composites_test.cpp fuzzer_pass_donate_modules_test.cpp fuzzer_pass_outline_functions_test.cpp + fuzzerutil_test.cpp instruction_descriptor_test.cpp fuzzer_pass_test.cpp replayer_test.cpp @@ -113,6 +115,8 @@ if (${SPIRV_BUILD_FUZZER}) transformation_store_test.cpp transformation_swap_commutable_operands_test.cpp transformation_swap_conditional_branch_operands_test.cpp + transformation_swap_function_variables_test.cpp + transformation_swap_two_functions_test.cpp transformation_toggle_access_chain_instruction_test.cpp transformation_record_synonymous_constants_test.cpp transformation_vector_shuffle_test.cpp diff --git a/third_party/spirv-tools/test/fuzz/available_instructions_test.cpp b/third_party/spirv-tools/test/fuzz/available_instructions_test.cpp new file mode 100644 index 0000000000..dc8a3b5a55 --- /dev/null +++ b/third_party/spirv-tools/test/fuzz/available_instructions_test.cpp @@ -0,0 +1,328 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/available_instructions.h" + +#include "gtest/gtest.h" +#include "source/fuzz/fuzzer_util.h" +#include "test/fuzz/fuzz_test_util.h" + +namespace spvtools { +namespace fuzz { +namespace { + +TEST(AvailableInstructionsTest, BasicTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %8 = OpTypeFloat 32 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %7 %9 + %15 = OpTypeVector %8 2 + %16 = OpTypePointer Private %15 + %17 = OpVariable %16 Private + %18 = OpConstant %8 1 + %19 = OpConstant %8 2 + %20 = OpConstantComposite %15 %18 %19 + %21 = OpTypeVector %8 4 + %22 = OpTypePointer Private %21 + %23 = OpVariable %22 Private + %24 = OpConstant %8 10 + %25 = OpConstant %8 20 + %26 = OpConstant %8 30 + %27 = OpConstant %8 40 + %28 = OpConstantComposite %21 %24 %25 %26 %27 + %31 = OpTypeInt 32 0 + %32 = OpConstant %31 0 + %33 = OpTypePointer Private %8 + %41 = OpTypeBool + %46 = OpConstant %6 1 + %54 = OpConstant %6 10 + %57 = OpConstant %31 3 + %61 = OpConstant %6 0 + %66 = OpConstant %6 3 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %55 = OpVariable %7 Function + %56 = OpVariable %9 Function + %65 = OpVariable %7 Function + %68 = OpVariable %7 Function + OpStore %17 %20 + OpStore %23 %28 + OpStore %55 %54 + %58 = OpAccessChain %33 %23 %57 + %59 = OpLoad %8 %58 + OpStore %56 %59 + %60 = OpFunctionCall %6 %13 %55 %56 + %100 = OpCopyObject %21 %28 + %62 = OpSGreaterThan %41 %60 %61 + OpSelectionMerge %64 None + OpBranchConditional %62 %63 %67 + %63 = OpLabel + OpStore %65 %66 + %101 = OpCopyObject %21 %28 + OpBranch %64 + %67 = OpLabel + OpStore %68 %61 + OpBranch %69 + %69 = OpLabel + OpLoopMerge %71 %72 None + OpBranch %73 + %73 = OpLabel + %74 = OpLoad %6 %68 + %75 = OpSLessThan %41 %74 %54 + OpBranchConditional %75 %70 %71 + %70 = OpLabel + %76 = OpLoad %6 %65 + %77 = OpIAdd %6 %76 %46 + OpStore %65 %77 + OpBranch %72 + %72 = OpLabel + %78 = OpLoad %6 %68 + %79 = OpIAdd %6 %78 %46 + OpStore %68 %79 + OpBranch %69 + %71 = OpLabel + %102 = OpCopyObject %21 %28 + OpBranch %64 + %64 = OpLabel + OpReturn + OpFunctionEnd + %13 = OpFunction %6 None %10 + %11 = OpFunctionParameter %7 + %12 = OpFunctionParameter %9 + %14 = OpLabel + %29 = OpVariable %7 Function + %30 = OpLoad %6 %11 + %34 = OpAccessChain %33 %17 %32 + %35 = OpLoad %8 %34 + %36 = OpConvertFToS %6 %35 + %37 = OpIAdd %6 %30 %36 + OpStore %29 %37 + %38 = OpLoad %6 %11 + %39 = OpLoad %8 %12 + %40 = OpConvertFToS %6 %39 + %42 = OpSLessThan %41 %38 %40 + %103 = OpCopyObject %21 %28 + OpSelectionMerge %44 None + OpBranchConditional %42 %43 %48 + %43 = OpLabel + %45 = OpLoad %6 %29 + %47 = OpIAdd %6 %45 %46 + OpStore %29 %47 + OpBranch %44 + %48 = OpLabel + %49 = OpLoad %6 %29 + %50 = OpISub %6 %49 %46 + OpStore %29 %50 + OpBranch %44 + %44 = OpLabel + %51 = OpLoad %6 %29 + OpReturnValue %51 + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::Instruction* i1 = context->get_def_use_mgr()->GetDef(55); + opt::Instruction* i2 = context->get_def_use_mgr()->GetDef(101); + opt::Instruction* i3 = &*context->cfg()->block(67)->begin(); + opt::Instruction* i4 = context->get_def_use_mgr()->GetDef(74); + opt::Instruction* i5 = context->get_def_use_mgr()->GetDef(102); + opt::Instruction* i6 = context->get_def_use_mgr()->GetDef(30); + opt::Instruction* i7 = context->get_def_use_mgr()->GetDef(47); + opt::Instruction* i8 = context->get_def_use_mgr()->GetDef(50); + opt::Instruction* i9 = context->get_def_use_mgr()->GetDef(51); + + { + AvailableInstructions no_instructions( + context.get(), + [](opt::IRContext*, opt::Instruction*) -> bool { return false; }); + for (auto i : {i1, i2, i3, i4, i5, i6, i7, i8, i9}) { + auto available = no_instructions.GetAvailableBeforeInstruction(i); + ASSERT_EQ(0, available.size()); + ASSERT_TRUE(available.empty()); + } + } + { + AvailableInstructions all_instructions( + context.get(), + [](opt::IRContext*, opt::Instruction*) -> bool { return true; }); + { + auto available = all_instructions.GetAvailableBeforeInstruction(i1); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(30, available.size()); + ASSERT_EQ(SpvOpTypeVoid, available[0]->opcode()); + ASSERT_EQ(SpvOpVariable, available[15]->opcode()); + } + { + auto available = all_instructions.GetAvailableBeforeInstruction(i2); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(46, available.size()); + ASSERT_EQ(SpvOpTypeVoid, available[0]->opcode()); + ASSERT_EQ(SpvOpTypePointer, available[3]->opcode()); + ASSERT_EQ(SpvOpVariable, available[15]->opcode()); + ASSERT_EQ(SpvOpFunctionCall, available[40]->opcode()); + ASSERT_EQ(SpvOpStore, available[45]->opcode()); + } + { + auto available = all_instructions.GetAvailableBeforeInstruction(i3); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(45, available.size()); + ASSERT_EQ(SpvOpTypeVoid, available[0]->opcode()); + ASSERT_EQ(SpvOpTypePointer, available[3]->opcode()); + ASSERT_EQ(SpvOpVariable, available[15]->opcode()); + ASSERT_EQ(SpvOpFunctionCall, available[40]->opcode()); + ASSERT_EQ(SpvOpBranchConditional, available[44]->opcode()); + } + { + auto available = all_instructions.GetAvailableBeforeInstruction(i6); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(33, available.size()); + ASSERT_EQ(SpvOpTypeVoid, available[0]->opcode()); + ASSERT_EQ(SpvOpTypeFloat, available[4]->opcode()); + ASSERT_EQ(SpvOpTypePointer, available[8]->opcode()); + ASSERT_EQ(SpvOpConstantComposite, available[12]->opcode()); + ASSERT_EQ(SpvOpConstant, available[16]->opcode()); + ASSERT_EQ(SpvOpFunctionParameter, available[30]->opcode()); + ASSERT_EQ(SpvOpFunctionParameter, available[31]->opcode()); + ASSERT_EQ(SpvOpVariable, available[32]->opcode()); + } + } + { + AvailableInstructions vector_instructions( + context.get(), + [](opt::IRContext* ir_context, opt::Instruction* inst) -> bool { + return inst->type_id() != 0 && ir_context->get_type_mgr() + ->GetType(inst->type_id()) + ->AsVector() != nullptr; + }); + { + auto available = vector_instructions.GetAvailableBeforeInstruction(i4); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(3, available.size()); + ASSERT_EQ(SpvOpConstantComposite, available[0]->opcode()); + ASSERT_EQ(SpvOpConstantComposite, available[1]->opcode()); + ASSERT_EQ(SpvOpCopyObject, available[2]->opcode()); + } + { + auto available = vector_instructions.GetAvailableBeforeInstruction(i5); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(3, available.size()); + ASSERT_EQ(SpvOpConstantComposite, available[0]->opcode()); + ASSERT_EQ(SpvOpConstantComposite, available[1]->opcode()); + ASSERT_EQ(SpvOpCopyObject, available[2]->opcode()); + } + { + auto available = vector_instructions.GetAvailableBeforeInstruction(i6); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(2, available.size()); + ASSERT_EQ(SpvOpConstantComposite, available[0]->opcode()); + ASSERT_EQ(SpvOpConstantComposite, available[1]->opcode()); + } + } + { + AvailableInstructions integer_add_instructions( + context.get(), [](opt::IRContext*, opt::Instruction* inst) -> bool { + return inst->opcode() == SpvOpIAdd; + }); + { + auto available = + integer_add_instructions.GetAvailableBeforeInstruction(i7); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(1, available.size()); + ASSERT_EQ(SpvOpIAdd, available[0]->opcode()); + } + { + auto available = + integer_add_instructions.GetAvailableBeforeInstruction(i8); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(1, available.size()); + ASSERT_EQ(SpvOpIAdd, available[0]->opcode()); + } + { + auto available = + integer_add_instructions.GetAvailableBeforeInstruction(i9); + ASSERT_FALSE(available.empty()); + ASSERT_EQ(1, available.size()); + ASSERT_EQ(SpvOpIAdd, available[0]->opcode()); + } + } +} + +TEST(AvailableInstructionsTest, UnreachableBlock) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %4 "main" + OpName %8 "x" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpConstant %6 2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + OpStore %8 %9 + %12 = OpLoad %6 %8 + OpReturn + %10 = OpLabel + %11 = OpLoad %6 %8 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + AvailableInstructions all_instructions( + context.get(), + [](opt::IRContext*, opt::Instruction*) -> bool { return true; }); + ASSERT_EQ(7, all_instructions + .GetAvailableBeforeInstruction( + context->get_def_use_mgr()->GetDef(12)) + .size()); + +#ifndef NDEBUG + ASSERT_DEATH(all_instructions.GetAvailableBeforeInstruction( + context->get_def_use_mgr()->GetDef(11)), + "Availability can only be queried for reachable instructions."); +#endif +} + +} // namespace +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/fuzz_test_util.cpp b/third_party/spirv-tools/test/fuzz/fuzz_test_util.cpp index 28d3f892bb..bf0a4ff5dc 100644 --- a/third_party/spirv-tools/test/fuzz/fuzz_test_util.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzz_test_util.cpp @@ -160,13 +160,19 @@ void ApplyAndCheckFreshIds( const Transformation& transformation, opt::IRContext* ir_context, TransformationContext* transformation_context, const std::unordered_set& issued_overflow_ids) { + // To ensure that we cover all ToMessage and message-based constructor methods + // in our tests, we turn this into a message and back into a transformation, + // and use the reconstructed transformation in the rest of the function. + auto message = transformation.ToMessage(); + auto reconstructed_transformation = Transformation::FromMessage(message); + opt::analysis::DefUseManager::IdToDefMap before_transformation = ir_context->get_def_use_mgr()->id_to_defs(); - transformation.Apply(ir_context, transformation_context); + reconstructed_transformation->Apply(ir_context, transformation_context); opt::analysis::DefUseManager::IdToDefMap after_transformation = ir_context->get_def_use_mgr()->id_to_defs(); std::unordered_set fresh_ids_for_transformation = - transformation.GetFreshIds(); + reconstructed_transformation->GetFreshIds(); for (auto& entry : after_transformation) { uint32_t id = entry.first; bool introduced_by_transformation_message = diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_pass_add_opphi_synonyms_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_pass_add_opphi_synonyms_test.cpp index f7a09964cf..734f47afd8 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_pass_add_opphi_synonyms_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_pass_add_opphi_synonyms_test.cpp @@ -128,8 +128,8 @@ TEST(FuzzerPassAddOpPhiSynonymsTest, HelperFunctions) { kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassAddOpPhiSynonyms fuzzer_pass(context.get(), &transformation_context, diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_pass_construct_composites_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_pass_construct_composites_test.cpp index d49d1d6866..a02176b215 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_pass_construct_composites_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_pass_construct_composites_test.cpp @@ -77,7 +77,8 @@ TEST(FuzzerPassConstructCompositesTest, IsomorphicStructs) { const auto env = SPV_ENV_UNIVERSAL_1_3; const auto consumer = nullptr; - auto prng = MakeUnique(0); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); for (uint32_t i = 0; i < 10; i++) { const auto context = @@ -87,7 +88,6 @@ TEST(FuzzerPassConstructCompositesTest, IsomorphicStructs) { context.get(), validator_options, kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - FuzzerContext fuzzer_context(prng.get(), 100); protobufs::TransformationSequence transformation_sequence; FuzzerPassConstructComposites fuzzer_pass( @@ -158,7 +158,8 @@ TEST(FuzzerPassConstructCompositesTest, IsomorphicArrays) { const auto env = SPV_ENV_UNIVERSAL_1_3; const auto consumer = nullptr; - auto prng = MakeUnique(0); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); for (uint32_t i = 0; i < 10; i++) { const auto context = @@ -168,7 +169,6 @@ TEST(FuzzerPassConstructCompositesTest, IsomorphicArrays) { context.get(), validator_options, kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - FuzzerContext fuzzer_context(prng.get(), 100); protobufs::TransformationSequence transformation_sequence; FuzzerPassConstructComposites fuzzer_pass( diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_pass_donate_modules_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_pass_donate_modules_test.cpp index 1a7cd4ab5e..f11885d4e6 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_pass_donate_modules_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_pass_donate_modules_test.cpp @@ -204,8 +204,8 @@ TEST(FuzzerPassDonateModulesTest, BasicDonation) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -285,8 +285,8 @@ TEST(FuzzerPassDonateModulesTest, DonationWithUniforms) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -416,8 +416,8 @@ TEST(FuzzerPassDonateModulesTest, DonationWithInputAndOutputVariables) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -511,8 +511,8 @@ TEST(FuzzerPassDonateModulesTest, DonateFunctionTypeWithDifferentPointers) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -581,8 +581,8 @@ TEST(FuzzerPassDonateModulesTest, DonateOpConstantNull) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -709,8 +709,8 @@ TEST(FuzzerPassDonateModulesTest, DonateCodeThatUsesImages) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -805,8 +805,8 @@ TEST(FuzzerPassDonateModulesTest, DonateCodeThatUsesSampler) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -937,8 +937,8 @@ TEST(FuzzerPassDonateModulesTest, DonateCodeThatUsesImageStructField) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1073,8 +1073,8 @@ TEST(FuzzerPassDonateModulesTest, DonateCodeThatUsesImageFunctionParameter) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1155,8 +1155,8 @@ TEST(FuzzerPassDonateModulesTest, DonateShaderWithImageStorageClass) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1242,8 +1242,8 @@ TEST(FuzzerPassDonateModulesTest, DonateComputeShaderWithRuntimeArray) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1346,8 +1346,8 @@ TEST(FuzzerPassDonateModulesTest, DonateComputeShaderWithRuntimeArrayLivesafe) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1418,8 +1418,8 @@ TEST(FuzzerPassDonateModulesTest, DonateComputeShaderWithWorkgroupVariables) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1528,8 +1528,8 @@ TEST(FuzzerPassDonateModulesTest, DonateComputeShaderWithAtomics) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1712,8 +1712,8 @@ TEST(FuzzerPassDonateModulesTest, Miscellaneous1) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator rng(0); - FuzzerContext fuzzer_context(&rng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1784,8 +1784,8 @@ TEST(FuzzerPassDonateModulesTest, OpSpecConstantInstructions) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -1941,8 +1941,8 @@ TEST(FuzzerPassDonateModulesTest, DonationSupportsOpTypeRuntimeArray) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator rng(0); - FuzzerContext fuzzer_context(&rng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -2014,8 +2014,8 @@ TEST(FuzzerPassDonateModulesTest, HandlesCapabilities) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator rng(0); - FuzzerContext fuzzer_context(&rng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), @@ -2247,8 +2247,8 @@ TEST(FuzzerPassDonateModulesTest, HandlesOpPhisInMergeBlock) { TransformationContext transformation_context( MakeUnique(recipient_context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassDonateModules fuzzer_pass(recipient_context.get(), diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_pass_outline_functions_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_pass_outline_functions_test.cpp index 576962c306..0d2c5bf745 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_pass_outline_functions_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_pass_outline_functions_test.cpp @@ -124,8 +124,8 @@ TEST(FuzzerPassOutlineFunctionsTest, EntryIsAlreadySuitable) { kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassOutlineFunctions fuzzer_pass(context.get(), &transformation_context, @@ -167,8 +167,8 @@ TEST(FuzzerPassOutlineFunctionsTest, EntryHasOpVariable) { kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassOutlineFunctions fuzzer_pass(context.get(), &transformation_context, @@ -291,8 +291,8 @@ TEST(FuzzerPassOutlineFunctionsTest, EntryBlockIsHeader) { kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassOutlineFunctions fuzzer_pass(context.get(), &transformation_context, @@ -458,8 +458,8 @@ TEST(FuzzerPassOutlineFunctionsTest, ExitBlock) { kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformation_sequence; FuzzerPassOutlineFunctions fuzzer_pass(context.get(), &transformation_context, diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_pass_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_pass_test.cpp index 283aa114c2..b035de7444 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_pass_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_pass_test.cpp @@ -87,8 +87,8 @@ TEST(FuzzerPassTest, ForEachInstructionWithInstructionDescriptor) { ASSERT_TRUE(dominator_analysis->IsReachable(5)); ASSERT_FALSE(dominator_analysis->IsReachable(8)); - PseudoRandomGenerator prng(0); - FuzzerContext fuzzer_context(&prng, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); protobufs::TransformationSequence transformations; FuzzerPassMock fuzzer_pass_mock(context.get(), &transformation_context, &fuzzer_context, &transformations); diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_replayer_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_replayer_test.cpp index dc905741b7..6dc7ffb11c 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_replayer_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_replayer_test.cpp @@ -12,12 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "source/fuzz/fuzzer.h" -#include "source/fuzz/replayer.h" - #include "gtest/gtest.h" +#include "source/fuzz/fuzzer.h" #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/pseudo_random_generator.h" +#include "source/fuzz/replayer.h" #include "source/fuzz/uniform_buffer_element_descriptor.h" #include "test/fuzz/fuzz_test_util.h" @@ -1642,37 +1641,53 @@ void RunFuzzerAndReplayer(const std::string& shader, }); } - std::vector strategies{ - Fuzzer::RepeatedPassStrategy::kSimple, - Fuzzer::RepeatedPassStrategy::kLoopedWithRecommendations, - Fuzzer::RepeatedPassStrategy::kRandomWithRecommendations}; + std::vector strategies{ + RepeatedPassStrategy::kSimple, + RepeatedPassStrategy::kLoopedWithRecommendations, + RepeatedPassStrategy::kRandomWithRecommendations}; uint32_t strategy_index = 0; for (uint32_t seed = initial_seed; seed < initial_seed + num_runs; seed++) { spvtools::ValidatorOptions validator_options; + + std::unique_ptr ir_context; + ASSERT_TRUE(fuzzerutil::BuildIRContext(env, kConsoleMessageConsumer, + binary_in, validator_options, + &ir_context)); + + auto fuzzer_context = MakeUnique( + MakeUnique(seed), + FuzzerContext::GetMinFreshId(ir_context.get()), false); + + auto transformation_context = MakeUnique( + MakeUnique(ir_context.get()), validator_options); + transformation_context->GetFactManager()->AddInitialFacts( + kConsoleMessageConsumer, initial_facts); + // Every 4th time we run the fuzzer, enable all fuzzer passes. bool enable_all_passes = (seed % 4) == 0; - auto fuzzer_result = - Fuzzer(env, kConsoleMessageConsumer, binary_in, initial_facts, - donor_suppliers, MakeUnique(seed), - enable_all_passes, strategies[strategy_index], true, - validator_options) - .Run(); + Fuzzer fuzzer(std::move(ir_context), std::move(transformation_context), + std::move(fuzzer_context), kConsoleMessageConsumer, + donor_suppliers, enable_all_passes, + strategies[strategy_index], true, validator_options); + auto fuzzer_result = fuzzer.Run(0); // Cycle the repeated pass strategy so that we try a different one next time // we run the fuzzer. strategy_index = (strategy_index + 1) % static_cast(strategies.size()); - ASSERT_EQ(Fuzzer::FuzzerResultStatus::kComplete, fuzzer_result.status); - ASSERT_TRUE(t.Validate(fuzzer_result.transformed_binary)); + ASSERT_NE(Fuzzer::Status::kFuzzerPassLedToInvalidModule, + fuzzer_result.status); + std::vector transformed_binary; + fuzzer.GetIRContext()->module()->ToBinary(&transformed_binary, true); + ASSERT_TRUE(t.Validate(transformed_binary)); auto replayer_result = - Replayer( - env, kConsoleMessageConsumer, binary_in, initial_facts, - fuzzer_result.applied_transformations, - static_cast( - fuzzer_result.applied_transformations.transformation_size()), - false, validator_options) + Replayer(env, kConsoleMessageConsumer, binary_in, initial_facts, + fuzzer.GetTransformationSequence(), + static_cast( + fuzzer.GetTransformationSequence().transformation_size()), + false, validator_options) .Run(); ASSERT_EQ(Replayer::ReplayerResultStatus::kComplete, replayer_result.status); @@ -1682,12 +1697,12 @@ void RunFuzzerAndReplayer(const std::string& shader, // replay should be identical to that which resulted from fuzzing. std::string fuzzer_transformations_string; std::string replayer_transformations_string; - fuzzer_result.applied_transformations.SerializeToString( + fuzzer.GetTransformationSequence().SerializeToString( &fuzzer_transformations_string); replayer_result.applied_transformations.SerializeToString( &replayer_transformations_string); ASSERT_EQ(fuzzer_transformations_string, replayer_transformations_string); - ASSERT_TRUE(IsEqual(env, fuzzer_result.transformed_binary, + ASSERT_TRUE(IsEqual(env, transformed_binary, replayer_result.transformed_module.get())); } } diff --git a/third_party/spirv-tools/test/fuzz/fuzzer_shrinker_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzer_shrinker_test.cpp index 6d9dad358e..e792116980 100644 --- a/third_party/spirv-tools/test/fuzz/fuzzer_shrinker_test.cpp +++ b/third_party/spirv-tools/test/fuzz/fuzzer_shrinker_test.cpp @@ -12,15 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "source/fuzz/fuzzer.h" -#include "source/fuzz/shrinker.h" - #include #include #include "gtest/gtest.h" +#include "source/fuzz/fuzzer.h" #include "source/fuzz/fuzzer_util.h" #include "source/fuzz/pseudo_random_generator.h" +#include "source/fuzz/shrinker.h" #include "source/fuzz/uniform_buffer_element_descriptor.h" #include "test/fuzz/fuzz_test_util.h" @@ -1044,24 +1043,38 @@ void RunFuzzerAndShrinker(const std::string& shader, // Depending on the seed, decide whether to enable all passes and which // repeated pass manager to use. bool enable_all_passes = (seed % 4) == 0; - Fuzzer::RepeatedPassStrategy repeated_pass_strategy; + RepeatedPassStrategy repeated_pass_strategy; if ((seed % 3) == 0) { - repeated_pass_strategy = Fuzzer::RepeatedPassStrategy::kSimple; + repeated_pass_strategy = RepeatedPassStrategy::kSimple; } else if ((seed % 3) == 1) { - repeated_pass_strategy = - Fuzzer::RepeatedPassStrategy::kLoopedWithRecommendations; + repeated_pass_strategy = RepeatedPassStrategy::kLoopedWithRecommendations; } else { - repeated_pass_strategy = - Fuzzer::RepeatedPassStrategy::kRandomWithRecommendations; + repeated_pass_strategy = RepeatedPassStrategy::kRandomWithRecommendations; } - auto fuzzer_result = - Fuzzer(env, kConsoleMessageConsumer, binary_in, initial_facts, - donor_suppliers, MakeUnique(seed), - enable_all_passes, repeated_pass_strategy, true, validator_options) - .Run(); - ASSERT_EQ(Fuzzer::FuzzerResultStatus::kComplete, fuzzer_result.status); - ASSERT_TRUE(t.Validate(fuzzer_result.transformed_binary)); + std::unique_ptr ir_context; + ASSERT_TRUE(fuzzerutil::BuildIRContext( + env, kConsoleMessageConsumer, binary_in, validator_options, &ir_context)); + + auto fuzzer_context = MakeUnique( + MakeUnique(seed), + FuzzerContext::GetMinFreshId(ir_context.get()), false); + + auto transformation_context = MakeUnique( + MakeUnique(ir_context.get()), validator_options); + transformation_context->GetFactManager()->AddInitialFacts( + kConsoleMessageConsumer, initial_facts); + + Fuzzer fuzzer(std::move(ir_context), std::move(transformation_context), + std::move(fuzzer_context), kConsoleMessageConsumer, + donor_suppliers, enable_all_passes, repeated_pass_strategy, + true, validator_options); + auto fuzzer_result = fuzzer.Run(0); + ASSERT_NE(Fuzzer::Status::kFuzzerPassLedToInvalidModule, + fuzzer_result.status); + std::vector transformed_binary; + fuzzer.GetIRContext()->module()->ToBinary(&transformed_binary, true); + ASSERT_TRUE(t.Validate(transformed_binary)); const uint32_t kReasonableStepLimit = 50; const uint32_t kSmallStepLimit = 20; @@ -1069,30 +1082,30 @@ void RunFuzzerAndShrinker(const std::string& shader, // With the AlwaysInteresting test, we should quickly shrink to the original // binary with no transformations remaining. RunAndCheckShrinker(env, binary_in, initial_facts, - fuzzer_result.applied_transformations, + fuzzer.GetTransformationSequence(), AlwaysInteresting().AsFunction(), binary_in, 0, kReasonableStepLimit, validator_options); // With the OnlyInterestingFirstTime test, no shrinking should be achieved. RunAndCheckShrinker( - env, binary_in, initial_facts, fuzzer_result.applied_transformations, - OnlyInterestingFirstTime().AsFunction(), fuzzer_result.transformed_binary, + env, binary_in, initial_facts, fuzzer.GetTransformationSequence(), + OnlyInterestingFirstTime().AsFunction(), transformed_binary, static_cast( - fuzzer_result.applied_transformations.transformation_size()), + fuzzer.GetTransformationSequence().transformation_size()), kReasonableStepLimit, validator_options); // The PingPong test is unpredictable; passing an empty expected binary // means that we don't check anything beyond that shrinking completes // successfully. RunAndCheckShrinker( - env, binary_in, initial_facts, fuzzer_result.applied_transformations, + env, binary_in, initial_facts, fuzzer.GetTransformationSequence(), PingPong().AsFunction(), {}, 0, kSmallStepLimit, validator_options); // The InterestingThenRandom test is unpredictable; passing an empty // expected binary means that we do not check anything about shrinking // results. RunAndCheckShrinker( - env, binary_in, initial_facts, fuzzer_result.applied_transformations, + env, binary_in, initial_facts, fuzzer.GetTransformationSequence(), InterestingThenRandom(PseudoRandomGenerator(seed)).AsFunction(), {}, 0, kSmallStepLimit, validator_options); } diff --git a/third_party/spirv-tools/test/fuzz/fuzzerutil_test.cpp b/third_party/spirv-tools/test/fuzz/fuzzerutil_test.cpp new file mode 100644 index 0000000000..7ff9b4d8d7 --- /dev/null +++ b/third_party/spirv-tools/test/fuzz/fuzzerutil_test.cpp @@ -0,0 +1,1568 @@ +// Copyright (c) 2021 Shiyu Liu +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "gtest/gtest.h" +#include "source/fuzz/fuzzer_util.h" +#include "test/fuzz/fuzz_test_util.h" + +namespace spvtools { +namespace fuzz { +namespace { + +TEST(FuzzerUtilMaybeFindBlockTest, BasicTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %8 RelaxedPrecision + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpConstant %6 1 + %10 = OpConstant %6 2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + OpBranch %11 + %11 = OpLabel + OpStore %8 %9 + OpBranch %12 + %12 = OpLabel + OpStore %8 %10 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + // Only blocks with id 11 and 12 can be found. + // Should return nullptr when id is not a label or id was not found. + uint32_t block_id1 = 11; + uint32_t block_id2 = 12; + uint32_t block_id3 = 13; + uint32_t block_id4 = 8; + + opt::IRContext* ir_context = context.get(); + // Block with id 11 should be found. + ASSERT_TRUE(fuzzerutil::MaybeFindBlock(ir_context, block_id1) != nullptr); + // Block with id 12 should be found. + ASSERT_TRUE(fuzzerutil::MaybeFindBlock(ir_context, block_id2) != nullptr); + // Block with id 13 cannot be found. + ASSERT_FALSE(fuzzerutil::MaybeFindBlock(ir_context, block_id3) != nullptr); + // Block with id 8 exisits but don't not of type OpLabel. + ASSERT_FALSE(fuzzerutil::MaybeFindBlock(ir_context, block_id4) != nullptr); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetBoolConstantTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %36 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %20 "cf1" + OpName %22 "cf2" + OpName %26 "i1" + OpName %28 "i2" + OpName %30 "ci1" + OpName %32 "ci2" + OpName %36 "value" + OpDecorate %26 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %36 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %21 = OpConstant %14 2 + %23 = OpConstant %14 3.29999995 + %24 = OpTypeInt 32 1 + %25 = OpTypePointer Function %24 + %27 = OpConstant %24 1 + %29 = OpConstant %24 100 + %31 = OpConstant %24 123 + %33 = OpConstant %24 1111 + %35 = OpTypePointer Input %14 + %36 = OpVariable %35 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %20 = OpVariable %15 Function + %22 = OpVariable %15 Function + %26 = OpVariable %25 Function + %28 = OpVariable %25 Function + %30 = OpVariable %25 Function + %32 = OpVariable %25 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %20 %21 + OpStore %22 %23 + OpStore %26 %27 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + opt::IRContext* ir_context = context.get(); + // A bool constant with value false exists and the id is 11. + ASSERT_EQ(11, fuzzerutil::MaybeGetBoolConstant( + ir_context, transformation_context, false, false)); + // A bool constant with value true exists and the id is 9. + ASSERT_EQ(9, fuzzerutil::MaybeGetBoolConstant( + ir_context, transformation_context, true, false)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetBoolTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + // A bool type with result id of 34 exists. + ASSERT_TRUE(fuzzerutil::MaybeGetBoolType(ir_context)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetCompositeConstantTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %54 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %22 "zc" + OpName %24 "i1" + OpName %28 "i2" + OpName %30 "i3" + OpName %32 "i4" + OpName %37 "f_arr" + OpName %47 "i_arr" + OpName %54 "value" + OpDecorate %22 RelaxedPrecision + OpDecorate %24 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %47 RelaxedPrecision + OpDecorate %54 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %20 = OpTypeInt 32 1 + %21 = OpTypePointer Function %20 + %23 = OpConstant %20 0 + %25 = OpConstant %20 1 + %26 = OpTypeInt 32 0 + %27 = OpTypePointer Function %26 + %29 = OpConstant %26 100 + %31 = OpConstant %20 -1 + %33 = OpConstant %20 -99 + %34 = OpConstant %26 5 + %35 = OpTypeArray %14 %34 + %36 = OpTypePointer Function %35 + %38 = OpConstant %14 5.5 + %39 = OpConstant %14 4.4000001 + %40 = OpConstant %14 3.29999995 + %41 = OpConstant %14 2.20000005 + %42 = OpConstant %14 1.10000002 + %43 = OpConstantComposite %35 %38 %39 %40 %41 %42 + %44 = OpConstant %26 3 + %45 = OpTypeArray %20 %44 + %46 = OpTypePointer Function %45 + %48 = OpConstant %20 3 + %49 = OpConstant %20 7 + %50 = OpConstant %20 9 + %51 = OpConstantComposite %45 %48 %49 %50 + %53 = OpTypePointer Input %14 + %54 = OpVariable %53 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %22 = OpVariable %21 Function + %24 = OpVariable %21 Function + %28 = OpVariable %27 Function + %30 = OpVariable %21 Function + %32 = OpVariable %21 Function + %37 = OpVariable %36 Function + %47 = OpVariable %46 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %22 %23 + OpStore %24 %25 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpStore %37 %43 + OpStore %47 %51 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + opt::IRContext* ir_context = context.get(); + + // %43 = OpConstantComposite %35 %38 %39 %40 %41 %42 + // %51 = OpConstantComposite %45 %48 %49 %50 + // This should pass as a float array with 5 elements exist and its id is 43. + ASSERT_EQ(43, fuzzerutil::MaybeGetCompositeConstant( + ir_context, transformation_context, {38, 39, 40, 41, 42}, + 35, false)); + // This should pass as an int array with 3 elements exist and its id is 51. + ASSERT_EQ(51, + fuzzerutil::MaybeGetCompositeConstant( + ir_context, transformation_context, {48, 49, 50}, 45, false)); + // An int array with 2 elements does not exist. + ASSERT_EQ(0, fuzzerutil::MaybeGetCompositeConstant( + ir_context, transformation_context, {48, 49}, 45, false)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetFloatConstantTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %36 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %20 "cf1" + OpName %22 "cf2" + OpName %26 "i1" + OpName %28 "i2" + OpName %30 "ci1" + OpName %32 "ci2" + OpName %36 "value" + OpDecorate %26 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %36 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %21 = OpConstant %14 2 + %23 = OpConstant %14 3.29999995 + %24 = OpTypeInt 32 1 + %25 = OpTypePointer Function %24 + %27 = OpConstant %24 1 + %29 = OpConstant %24 100 + %31 = OpConstant %24 123 + %33 = OpConstant %24 1111 + %35 = OpTypePointer Input %14 + %36 = OpVariable %35 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %20 = OpVariable %15 Function + %22 = OpVariable %15 Function + %26 = OpVariable %25 Function + %28 = OpVariable %25 Function + %30 = OpVariable %25 Function + %32 = OpVariable %25 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %20 %21 + OpStore %22 %23 + OpStore %26 %27 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + opt::IRContext* ir_context = context.get(); + + uint32_t word1 = fuzzerutil::FloatToWord(2); + uint32_t word2 = fuzzerutil::FloatToWord(1.23f); + + // A 32 bit float constant of value 2 exists and its id is 21. + ASSERT_EQ(21, fuzzerutil::MaybeGetFloatConstant( + ir_context, transformation_context, + std::vector{word1}, 32, false)); + // A 32 bit float constant of value 1.23 exists and its id is 17. + ASSERT_EQ(17, fuzzerutil::MaybeGetFloatConstant( + ir_context, transformation_context, + std::vector{word2}, 32, false)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetFloatTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + // A float type with width = 32 and result id of 7 exists. + ASSERT_EQ(7, fuzzerutil::MaybeGetFloatType(ir_context, 32)); + + // A float int type with width = 32 exists, but the id should be 7. + ASSERT_NE(5, fuzzerutil::MaybeGetFloatType(ir_context, 32)); + + // A float type with width 30 does not exist. + ASSERT_EQ(0, fuzzerutil::MaybeGetFloatType(ir_context, 30)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetIntegerConstantFromValueAndTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %36 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %22 "zc" + OpName %24 "i1" + OpName %28 "i2" + OpName %30 "i3" + OpName %32 "i4" + OpName %36 "value" + OpDecorate %22 RelaxedPrecision + OpDecorate %24 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %36 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %20 = OpTypeInt 32 1 + %21 = OpTypePointer Function %20 + %23 = OpConstant %20 0 + %25 = OpConstant %20 1 + %26 = OpTypeInt 32 0 + %27 = OpTypePointer Function %26 + %29 = OpConstant %26 100 + %31 = OpConstant %20 -1 + %33 = OpConstant %20 -99 + %35 = OpTypePointer Input %14 + %36 = OpVariable %35 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %22 = OpVariable %21 Function + %24 = OpVariable %21 Function + %28 = OpVariable %27 Function + %30 = OpVariable %21 Function + %32 = OpVariable %21 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %22 %23 + OpStore %24 %25 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + + // A 32 bit signed int constant (with int type id 20) with value 1 exists and + // the id is 25. + ASSERT_EQ(25, fuzzerutil::MaybeGetIntegerConstantFromValueAndType(ir_context, + 1, 20)); + // A 32 bit unsigned int constant (with int type id 0) with value 100 exists + // and the id is 29. + ASSERT_EQ(29, fuzzerutil::MaybeGetIntegerConstantFromValueAndType(ir_context, + 100, 26)); + // A 32 bit unsigned int constant with value 50 does not exist. + ASSERT_EQ(0, fuzzerutil::MaybeGetIntegerConstantFromValueAndType(ir_context, + 50, 26)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetIntegerConstantTest) { + std::string shader = R"( +OpCapability Shader + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %36 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %22 "zc" + OpName %24 "i1" + OpName %28 "i2" + OpName %30 "i3" + OpName %32 "i4" + OpName %36 "value" + OpDecorate %22 RelaxedPrecision + OpDecorate %24 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %36 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %20 = OpTypeInt 32 1 + %21 = OpTypePointer Function %20 + %23 = OpConstant %20 0 + %25 = OpConstant %20 1 + %26 = OpTypeInt 32 0 + %27 = OpTypePointer Function %26 + %29 = OpConstant %26 100 + %31 = OpConstant %20 -1 + %33 = OpConstant %20 -99 + %35 = OpTypePointer Input %14 + %36 = OpVariable %35 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %22 = OpVariable %21 Function + %24 = OpVariable %21 Function + %28 = OpVariable %27 Function + %30 = OpVariable %21 Function + %32 = OpVariable %21 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %22 %23 + OpStore %24 %25 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + opt::IRContext* ir_context = context.get(); + + // A 32 bit unsigned int constant with value 1 exists and the id is 25. + ASSERT_EQ(25, fuzzerutil::MaybeGetIntegerConstant( + ir_context, transformation_context, + std::vector{1}, 32, true, false)); + // A 32 bit unsigned int constant with value 100 exists and the id is 29. + ASSERT_EQ(29, fuzzerutil::MaybeGetIntegerConstant( + ir_context, transformation_context, + std::vector{100}, 32, false, false)); + // A 32 bit signed int constant with value 99 doesn't not exist and should + // return 0. + ASSERT_EQ(0, fuzzerutil::MaybeGetIntegerConstant( + ir_context, transformation_context, + std::vector{99}, 32, true, false)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetIntegerTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + + // A signed int type with width = 32 and result id of 6 exists. + ASSERT_EQ(6, fuzzerutil::MaybeGetIntegerType(ir_context, 32, true)); + + // A signed int type with width = 32 exists, but the id should be 6. + ASSERT_FALSE(fuzzerutil::MaybeGetIntegerType(ir_context, 32, true) == 5); + + // A int type with width = 32 and result id of 6 exists, but it should be a + // signed int. + ASSERT_EQ(0, fuzzerutil::MaybeGetIntegerType(ir_context, 32, false)); + // A signed int type with width 30 does not exist. + ASSERT_EQ(0, fuzzerutil::MaybeGetIntegerType(ir_context, 30, true)); + // An unsigned int type with width 22 does not exist. + ASSERT_EQ(0, fuzzerutil::MaybeGetIntegerType(ir_context, 22, false)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetPointerTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + auto private_storage_class = SpvStorageClassPrivate; + auto function_storage_class = SpvStorageClassFunction; + auto input_storage_class = SpvStorageClassInput; + + // A valid pointer must have the correct |pointee_type_id| and |storageClass|. + // A function type pointer with id = 9 and pointee type id 8 should be found. + ASSERT_EQ(9, fuzzerutil::MaybeGetPointerType(ir_context, 8, + function_storage_class)); + // A function type pointer with id = 15 and pointee type id 6 should be found. + ASSERT_EQ(15, fuzzerutil::MaybeGetPointerType(ir_context, 6, + function_storage_class)); + // A function type pointer with id = 25 and pointee type id 7 should be found. + ASSERT_EQ(25, fuzzerutil::MaybeGetPointerType(ir_context, 7, + function_storage_class)); + + // A private type pointer with id=51 and pointee type id 6 should be found. + ASSERT_EQ(51, fuzzerutil::MaybeGetPointerType(ir_context, 6, + private_storage_class)); + // A function pointer with id=50 and pointee type id 7 should be found. + ASSERT_EQ(50, fuzzerutil::MaybeGetPointerType(ir_context, 7, + private_storage_class)); + + // A input type pointer with id=91 and pointee type id 90 should be found. + ASSERT_EQ( + 91, fuzzerutil::MaybeGetPointerType(ir_context, 90, input_storage_class)); + + // A pointer with id=91 and pointee type 90 exisits, but the type should be + // input. + ASSERT_EQ(0, fuzzerutil::MaybeGetPointerType(ir_context, 90, + function_storage_class)); + // A input type pointer with id=91 exists but the pointee id should be 90. + ASSERT_EQ( + 0, fuzzerutil::MaybeGetPointerType(ir_context, 89, input_storage_class)); + // A input type pointer with pointee id 90 exists but result id of the pointer + // should be 91. + ASSERT_NE( + 58, fuzzerutil::MaybeGetPointerType(ir_context, 90, input_storage_class)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetScalarConstantTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %56 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %22 "zc" + OpName %24 "i1" + OpName %28 "i2" + OpName %30 "i" + OpName %32 "i3" + OpName %34 "i4" + OpName %39 "f_arr" + OpName %49 "i_arr" + OpName %56 "value" + OpDecorate %22 RelaxedPrecision + OpDecorate %24 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %34 RelaxedPrecision + OpDecorate %49 RelaxedPrecision + OpDecorate %56 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %20 = OpTypeInt 32 1 + %21 = OpTypePointer Function %20 + %23 = OpConstant %20 0 + %25 = OpConstant %20 1 + %26 = OpTypeInt 32 0 + %27 = OpTypePointer Function %26 + %29 = OpConstant %26 100 + %31 = OpConstant %26 0 + %33 = OpConstant %20 -1 + %35 = OpConstant %20 -99 + %36 = OpConstant %26 5 + %37 = OpTypeArray %14 %36 + %38 = OpTypePointer Function %37 + %40 = OpConstant %14 5.5 + %41 = OpConstant %14 4.4000001 + %42 = OpConstant %14 3.29999995 + %43 = OpConstant %14 2.20000005 + %44 = OpConstant %14 1.10000002 + %45 = OpConstantComposite %37 %40 %41 %42 %43 %44 + %46 = OpConstant %26 3 + %47 = OpTypeArray %20 %46 + %48 = OpTypePointer Function %47 + %50 = OpConstant %20 3 + %51 = OpConstant %20 7 + %52 = OpConstant %20 9 + %53 = OpConstantComposite %47 %50 %51 %52 + %55 = OpTypePointer Input %14 + %56 = OpVariable %55 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %22 = OpVariable %21 Function + %24 = OpVariable %21 Function + %28 = OpVariable %27 Function + %30 = OpVariable %27 Function + %32 = OpVariable %21 Function + %34 = OpVariable %21 Function + %39 = OpVariable %38 Function + %49 = OpVariable %48 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %22 %23 + OpStore %24 %25 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpStore %34 %35 + OpStore %39 %45 + OpStore %49 %53 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + opt::IRContext* ir_context = context.get(); + + std::vector uint_words1 = fuzzerutil::IntToWords(100, 32, false); + std::vector uint_words2 = fuzzerutil::IntToWords(0, 32, false); + std::vector int_words1 = fuzzerutil::IntToWords(-99, 32, true); + std::vector int_words2 = fuzzerutil::IntToWords(1, 32, true); + uint32_t float_word1 = fuzzerutil::FloatToWord(1.11f); + uint32_t float_word2 = fuzzerutil::FloatToWord(4.4f); + + // A unsigned int of value 100 that has a scalar type id of 26 exists and its + // id is 29. + ASSERT_EQ( + 29, fuzzerutil::MaybeGetScalarConstant(ir_context, transformation_context, + uint_words1, 26, false)); + // A unsigned int of value 0 that has a scalar type id of 26 exists and its id + // is 29. + ASSERT_EQ( + 31, fuzzerutil::MaybeGetScalarConstant(ir_context, transformation_context, + uint_words2, 26, false)); + // A signed int of value -99 that has a scalar type id of 20 exists and its id + // is 35. + ASSERT_EQ(35, fuzzerutil::MaybeGetScalarConstant( + ir_context, transformation_context, int_words1, 20, false)); + // A signed int of value 1 that has a scalar type id of 20 exists and its id + // is 25. + ASSERT_EQ(25, fuzzerutil::MaybeGetScalarConstant( + ir_context, transformation_context, int_words2, 20, false)); + // A float of value 1.11 that has a scalar type id of 14 exists and its id + // is 19. + ASSERT_EQ(19, fuzzerutil::MaybeGetScalarConstant( + ir_context, transformation_context, + std::vector{float_word1}, 14, false)); + // A signed int of value 1 that has a scalar type id of 20 exists and its id + // is 25. + ASSERT_EQ(41, fuzzerutil::MaybeGetScalarConstant( + ir_context, transformation_context, + std::vector{float_word2}, 14, false)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetStructTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + + // 6 and 7 are all valid ids from OpTypeInt and OpTypeFloat + // so the result id of 8 should be found. + ASSERT_EQ(8, fuzzerutil::MaybeGetStructType(ir_context, + std::vector{6, 7})); + + // |component_type_id| of 16 does not exist in the module, so such a struct + // type cannot be found. + ASSERT_EQ(0, fuzzerutil::MaybeGetStructType(ir_context, + std::vector(6, 16))); + + // |component_type_id| of 10 is of OpTypeFunction type and thus the struct + // cannot be found. + ASSERT_EQ(0, fuzzerutil::MaybeGetStructType(ir_context, + std::vector(6, 10))); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetVectorTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + // The vector type with |element_count| 4 and |component_type_id| 7 + // is present and has a result id of 90. + ASSERT_EQ(90, fuzzerutil::MaybeGetVectorType(ir_context, 7, 4)); + + // The vector type with |element_count| 3 and |component_type_id| 7 + // is not present in the module. + ASSERT_EQ(0, fuzzerutil::MaybeGetVectorType(ir_context, 7, 3)); + +#ifndef NDEBUG + // It should abort with |component_type_id| of 100 + // |component_type_id| must be a valid result id of an OpTypeInt, + // OpTypeFloat or OpTypeBool instruction in the module. + ASSERT_DEATH(fuzzerutil::MaybeGetVectorType(ir_context, 100, 4), + "\\|component_type_id\\| is invalid"); + + // It should abort with |element_count| of 5. + // |element_count| must be in the range [2,4]. + ASSERT_DEATH(fuzzerutil::MaybeGetVectorType(ir_context, 7, 5), + "Precondition: component count must be in range \\[2, 4\\]."); +#endif +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetVoidTypeTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %92 %52 %53 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpDecorate %92 BuiltIn FragCoord + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypeFloat 32 + %8 = OpTypeStruct %6 %7 + %9 = OpTypePointer Function %8 + %10 = OpTypeFunction %6 %9 + %14 = OpConstant %6 0 + %15 = OpTypePointer Function %6 + %51 = OpTypePointer Private %6 + %21 = OpConstant %6 2 + %23 = OpConstant %6 1 + %24 = OpConstant %7 1 + %25 = OpTypePointer Function %7 + %50 = OpTypePointer Private %7 + %34 = OpTypeBool + %35 = OpConstantFalse %34 + %60 = OpConstantNull %50 + %61 = OpUndef %51 + %52 = OpVariable %50 Private + %53 = OpVariable %51 Private + %80 = OpConstantComposite %8 %21 %24 + %90 = OpTypeVector %7 4 + %91 = OpTypePointer Input %90 + %92 = OpVariable %91 Input + %93 = OpConstantComposite %90 %24 %24 %24 %24 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %20 = OpVariable %9 Function + %27 = OpVariable %9 Function + %22 = OpAccessChain %15 %20 %14 + %44 = OpCopyObject %9 %20 + %26 = OpAccessChain %25 %20 %23 + %29 = OpFunctionCall %6 %12 %27 + %30 = OpAccessChain %15 %20 %14 + %45 = OpCopyObject %15 %30 + %81 = OpCopyObject %9 %27 + %33 = OpAccessChain %15 %20 %14 + OpSelectionMerge %37 None + OpBranchConditional %35 %36 %37 + %36 = OpLabel + %38 = OpAccessChain %15 %20 %14 + %40 = OpAccessChain %15 %20 %14 + %43 = OpAccessChain %15 %20 %14 + %82 = OpCopyObject %9 %27 + OpBranch %37 + %37 = OpLabel + OpReturn + OpFunctionEnd + %12 = OpFunction %6 None %10 + %11 = OpFunctionParameter %9 + %13 = OpLabel + %46 = OpCopyObject %9 %11 + %16 = OpAccessChain %15 %11 %14 + %95 = OpCopyObject %8 %80 + OpReturnValue %21 + %100 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + opt::IRContext* ir_context = context.get(); + // A void type with a result id of 2 can be found. + ASSERT_EQ(2, fuzzerutil::MaybeGetVoidType(ir_context)); +} + +TEST(FuzzerutilTest, FuzzerUtilMaybeGetZeroConstantTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %56 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %8 "b1" + OpName %10 "b2" + OpName %12 "b3" + OpName %13 "b4" + OpName %16 "f1" + OpName %18 "f2" + OpName %22 "zc" + OpName %24 "i1" + OpName %28 "i2" + OpName %30 "i" + OpName %32 "i3" + OpName %34 "i4" + OpName %39 "f_arr" + OpName %49 "i_arr" + OpName %56 "value" + OpDecorate %22 RelaxedPrecision + OpDecorate %24 RelaxedPrecision + OpDecorate %28 RelaxedPrecision + OpDecorate %30 RelaxedPrecision + OpDecorate %32 RelaxedPrecision + OpDecorate %34 RelaxedPrecision + OpDecorate %49 RelaxedPrecision + OpDecorate %56 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpTypePointer Function %6 + %9 = OpConstantTrue %6 + %11 = OpConstantFalse %6 + %14 = OpTypeFloat 32 + %15 = OpTypePointer Function %14 + %17 = OpConstant %14 1.23000002 + %19 = OpConstant %14 1.11000001 + %20 = OpTypeInt 32 1 + %21 = OpTypePointer Function %20 + %23 = OpConstant %20 0 + %25 = OpConstant %20 1 + %26 = OpTypeInt 32 0 + %27 = OpTypePointer Function %26 + %29 = OpConstant %26 100 + %31 = OpConstant %26 0 + %33 = OpConstant %20 -1 + %35 = OpConstant %20 -99 + %36 = OpConstant %26 5 + %37 = OpTypeArray %14 %36 + %38 = OpTypePointer Function %37 + %40 = OpConstant %14 5.5 + %41 = OpConstant %14 4.4000001 + %42 = OpConstant %14 3.29999995 + %43 = OpConstant %14 2.20000005 + %44 = OpConstant %14 1.10000002 + %45 = OpConstantComposite %37 %40 %41 %42 %43 %44 + %46 = OpConstant %26 3 + %47 = OpTypeArray %20 %46 + %48 = OpTypePointer Function %47 + %50 = OpConstant %20 3 + %51 = OpConstant %20 7 + %52 = OpConstant %20 9 + %53 = OpConstantComposite %47 %50 %51 %52 + %55 = OpTypePointer Input %14 + %56 = OpVariable %55 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %10 = OpVariable %7 Function + %12 = OpVariable %7 Function + %13 = OpVariable %7 Function + %16 = OpVariable %15 Function + %18 = OpVariable %15 Function + %22 = OpVariable %21 Function + %24 = OpVariable %21 Function + %28 = OpVariable %27 Function + %30 = OpVariable %27 Function + %32 = OpVariable %21 Function + %34 = OpVariable %21 Function + %39 = OpVariable %38 Function + %49 = OpVariable %48 Function + OpStore %8 %9 + OpStore %10 %11 + OpStore %12 %9 + OpStore %13 %11 + OpStore %16 %17 + OpStore %18 %19 + OpStore %22 %23 + OpStore %24 %25 + OpStore %28 %29 + OpStore %30 %31 + OpStore %32 %33 + OpStore %34 %35 + OpStore %39 %45 + OpStore %49 %53 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const std::unique_ptr context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + opt::IRContext* ir_context = context.get(); + + // The id of a boolean constant will be returned give boolean type id 6. + uint32_t maybe_bool_id = fuzzerutil::MaybeGetZeroConstant( + ir_context, transformation_context, 6, false); + // The id of a 32 bit float constant will be returned given the float type + // id 14. + uint32_t maybe_float_id = fuzzerutil::MaybeGetZeroConstant( + ir_context, transformation_context, 14, false); + uint32_t maybe_signed_int_id = fuzzerutil::MaybeGetZeroConstant( + ir_context, transformation_context, 20, false); + uint32_t maybe_unsigned_int_id = fuzzerutil::MaybeGetZeroConstant( + ir_context, transformation_context, 26, false); + + // Lists of possible ids for float, signed int, unsigned int and array. + std::vector float_ids{17, 19}; + std::vector signed_int_ids{23, 25, 31, 33}; + + ASSERT_TRUE(maybe_bool_id == 9 || maybe_bool_id == 11); + ASSERT_TRUE(std::find(signed_int_ids.begin(), signed_int_ids.end(), + maybe_signed_int_id) != signed_int_ids.end()); + + // There is a unsigned int typed zero constant and its id is 31. + ASSERT_EQ(31, maybe_unsigned_int_id); + + // There is no zero float constant. + ASSERT_TRUE(std::find(float_ids.begin(), float_ids.end(), maybe_float_id) == + float_ids.end()); +} + +} // namespace +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/shrinker_test.cpp b/third_party/spirv-tools/test/fuzz/shrinker_test.cpp index 42cd182cb8..447ebecd74 100644 --- a/third_party/spirv-tools/test/fuzz/shrinker_test.cpp +++ b/third_party/spirv-tools/test/fuzz/shrinker_test.cpp @@ -163,8 +163,8 @@ TEST(ShrinkerTest, ReduceAddedFunctions) { ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( donor_ir_context.get(), validator_options, kConsoleMessageConsumer)); - PseudoRandomGenerator random_generator(0); - FuzzerContext fuzzer_context(&random_generator, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); TransformationContext transformation_context( MakeUnique(variant_ir_context.get()), validator_options); @@ -341,8 +341,8 @@ TEST(ShrinkerTest, HitStepLimitWhenReducingAddedFunctions) { ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( donor_ir_context.get(), validator_options, kConsoleMessageConsumer)); - PseudoRandomGenerator random_generator(0); - FuzzerContext fuzzer_context(&random_generator, 100); + FuzzerContext fuzzer_context(MakeUnique(0), 100, + false); TransformationContext transformation_context( MakeUnique(variant_ir_context.get()), validator_options); @@ -365,7 +365,6 @@ TEST(ShrinkerTest, HitStepLimitWhenReducingAddedFunctions) { if (inst->opcode() == SpvOpCopyObject) { copy_object_count++; } - }); return copy_object_count >= 8; }; diff --git a/third_party/spirv-tools/test/fuzz/transformation_access_chain_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_access_chain_test.cpp index 5c431279a7..e7919816d9 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_access_chain_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_access_chain_test.cpp @@ -127,6 +127,16 @@ TEST(TransformationAccessChainTest, BasicTest) { transformation_context.GetFactManager()->AddFactValueOfPointeeIsIrrelevant( 54); + // Check the case where the index type is not a 32-bit integer. + TransformationAccessChain invalid_index_example1( + 101, 28, {29}, MakeInstructionDescriptor(42, SpvOpReturn, 0)); + + // Since the index is not a 32-bit integer type but a 32-bit float type, + // ValidIndexComposite should return false and thus the transformation is not + // applicable. + ASSERT_FALSE(invalid_index_example1.IsApplicable(context.get(), + transformation_context)); + // Bad: id is not fresh ASSERT_FALSE(TransformationAccessChain( 43, 43, {80}, MakeInstructionDescriptor(24, SpvOpLoad, 0)) @@ -304,6 +314,20 @@ TEST(TransformationAccessChainTest, BasicTest) { ASSERT_FALSE( transformation_context.GetFactManager()->PointeeValueIsIrrelevant(107)); } + { + // Check the case where the access chain's base pointer has the irrelevant + // pointee fact; the resulting access chain should inherit this fact. + TransformationAccessChain transformation( + 107, 54, {}, MakeInstructionDescriptor(24, SpvOpLoad, 0)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + ASSERT_TRUE( + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(54)); + } std::string after_transformation = R"( OpCapability Shader @@ -383,6 +407,7 @@ TEST(TransformationAccessChainTest, BasicTest) { %23 = OpConvertFToS %10 %22 %100 = OpAccessChain %70 %43 %80 %106 = OpAccessChain %11 %14 + %107 = OpAccessChain %53 %54 %24 = OpLoad %10 %14 %25 = OpIAdd %10 %23 %24 OpReturnValue %25 @@ -391,6 +416,44 @@ TEST(TransformationAccessChainTest, BasicTest) { ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); } +TEST(TransformationAccessChainTest, StructIndexMustBeConstant) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %20 = OpUndef %6 + %7 = OpTypeStruct %6 %6 + %8 = OpTypePointer Function %7 + %10 = OpConstant %6 0 + %11 = OpConstant %6 2 + %12 = OpTypePointer Function %6 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %9 = OpVariable %8 Function + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + // Bad: %9 is a pointer to a struct, but %20 is not a constant. + ASSERT_FALSE(TransformationAccessChain( + 100, 9, {20}, MakeInstructionDescriptor(9, SpvOpReturn, 0)) + .IsApplicable(context.get(), transformation_context)); +} + TEST(TransformationAccessChainTest, IsomorphicStructs) { std::string shader = R"( OpCapability Shader diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_bit_instruction_synonym_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_bit_instruction_synonym_test.cpp index fa8f7bf390..d6b2ce51a3 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_bit_instruction_synonym_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_bit_instruction_synonym_test.cpp @@ -937,6 +937,131 @@ TEST(TransformationAddBitInstructionSynonymTest, NoSynonymWhenBlockIsDead) { MakeDataDescriptor(166, {}), MakeDataDescriptor(39, {}))); } +TEST(TransformationAddBitInstructionSynonymTest, DifferentSingedness) { + std::string reference_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %37 "main" + +; Types + %2 = OpTypeInt 32 0 + %200 = OpTypeInt 32 1 + %3 = OpTypeVoid + %4 = OpTypeFunction %3 + +; Constants + %5 = OpConstant %2 0 + %6 = OpConstant %2 1 + %7 = OpConstant %2 2 + %8 = OpConstant %2 3 + %9 = OpConstant %2 4 + %10 = OpConstant %2 5 + %11 = OpConstant %2 6 + %12 = OpConstant %2 7 + %13 = OpConstant %2 8 + %14 = OpConstant %2 9 + %15 = OpConstant %2 10 + %16 = OpConstant %2 11 + %17 = OpConstant %2 12 + %18 = OpConstant %2 13 + %19 = OpConstant %2 14 + %20 = OpConstant %2 15 + %21 = OpConstant %2 16 + %22 = OpConstant %2 17 + %23 = OpConstant %2 18 + %24 = OpConstant %2 19 + %25 = OpConstant %2 20 + %26 = OpConstant %2 21 + %27 = OpConstant %2 22 + %28 = OpConstant %2 23 + %29 = OpConstant %2 24 + %30 = OpConstant %2 25 + %31 = OpConstant %2 26 + %32 = OpConstant %2 27 + %33 = OpConstant %2 28 + %34 = OpConstant %2 29 + %35 = OpConstant %2 30 + %36 = OpConstant %2 31 + %45 = OpConstant %200 32 + +; main function + %37 = OpFunction %3 None %4 + %38 = OpLabel + %39 = OpNot %200 %5 ; bit instruction + %40 = OpBitwiseOr %200 %6 %45 ; bit instruction + %41 = OpBitwiseAnd %2 %5 %6 ; bit instruction + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_5; + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, reference_shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + // Invalid because the sign of id 200 result is not equal to the sign of id 5 + // operand in OpNot. + auto transformation = TransformationAddBitInstructionSynonym( + 39, {300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, + 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, + 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, + 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, + 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, + 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, + 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, + 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, + 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, + 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427}); + ASSERT_FALSE( + transformation.IsApplicable(context.get(), transformation_context)); + + // Invalid because the sign of two operands not the same and the first operand + // sign not equal the result sign in OpBitwiseOr. + transformation = TransformationAddBitInstructionSynonym( + 40, {300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, + 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, + 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, + 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, + 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, + 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, + 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, + 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, + 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, + 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427}); + ASSERT_FALSE( + transformation.IsApplicable(context.get(), transformation_context)); + + // Successful transformation + { + // Instruction operands are the same and it's equal with the result sign in + // OpBitwiseAnd bitwise operation. + transformation = TransformationAddBitInstructionSynonym( + 41, {46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, + 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, + 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, + 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, + 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, + 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, + 163, 164, 165, 166, 167, 168, 169, 170, 171, 172}); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + } +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_constant_boolean_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_constant_boolean_test.cpp index 3506db6b97..bd8d91c9ed 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_constant_boolean_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_constant_boolean_test.cpp @@ -46,6 +46,7 @@ TEST(TransformationAddConstantBooleanTest, NeitherPresentInitiallyAddBoth) { spvtools::ValidatorOptions validator_options; ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); + TransformationContext transformation_context( MakeUnique(context.get()), validator_options); // True and false can both be added as neither is present. @@ -68,7 +69,14 @@ TEST(TransformationAddConstantBooleanTest, NeitherPresentInitiallyAddBoth) { auto add_false = TransformationAddConstantBoolean(8, false, false); ASSERT_TRUE(add_true.IsApplicable(context.get(), transformation_context)); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(7)); + ASSERT_EQ(nullptr, context->get_constant_mgr()->FindDeclaredConstant(7)); ApplyAndCheckFreshIds(add_true, context.get(), &transformation_context); + ASSERT_EQ(SpvOpConstantTrue, context->get_def_use_mgr()->GetDef(7)->opcode()); + ASSERT_TRUE(context->get_constant_mgr() + ->FindDeclaredConstant(7) + ->AsBoolConstant() + ->value()); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_constant_composite_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_constant_composite_test.cpp index 2c296fbc5b..e5cbeec2d7 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_constant_composite_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_constant_composite_test.cpp @@ -82,10 +82,30 @@ TEST(TransformationAddConstantCompositeTest, BasicTest) { ASSERT_FALSE(TransformationAddConstantComposite(100, 39, {11, 12}, false) .IsApplicable(context.get(), transformation_context)); - TransformationAddConstantComposite transformations[] = { - // %100 = OpConstantComposite %7 %11 %12 - TransformationAddConstantComposite(100, 7, {11, 12}, false), + { + // %100 = OpConstantComposite %7 %11 %12 + TransformationAddConstantComposite transformation(100, 7, {11, 12}, false); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_constant_mgr()->FindDeclaredConstant(100)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpConstantComposite, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_EQ(0.0F, context->get_constant_mgr() + ->FindDeclaredConstant(100) + ->AsVectorConstant() + ->GetComponents()[0] + ->GetFloat()); + ASSERT_EQ(1.0F, context->get_constant_mgr() + ->FindDeclaredConstant(100) + ->AsVectorConstant() + ->GetComponents()[1] + ->GetFloat()); + } + TransformationAddConstantComposite transformations[] = { // %101 = OpConstantComposite %7 %14 %15 TransformationAddConstantComposite(101, 7, {14, 15}, false), diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_constant_null_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_constant_null_test.cpp index ce20a67780..1553e9f97d 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_constant_null_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_constant_null_test.cpp @@ -78,9 +78,23 @@ TEST(TransformationAddConstantNullTest, BasicTest) { ASSERT_FALSE(TransformationAddConstantNull(100, 22).IsApplicable( context.get(), transformation_context)); + { + // %100 = OpConstantNull %6 + TransformationAddConstantNull transformation(100, 6); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_constant_mgr()->FindDeclaredConstant(100)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpConstantNull, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_EQ( + 0.0F, + context->get_constant_mgr()->FindDeclaredConstant(100)->GetFloat()); + } + TransformationAddConstantNull transformations[] = { - // %100 = OpConstantNull %6 - TransformationAddConstantNull(100, 6), // %101 = OpConstantNull %7 TransformationAddConstantNull(101, 7), diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_constant_scalar_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_constant_scalar_test.cpp index a153fb1c3d..00c05416cf 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_constant_scalar_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_constant_scalar_test.cpp @@ -114,6 +114,11 @@ TEST(TransformationAddConstantScalarTest, IsApplicable) { transformation = TransformationAddConstantScalar(19, 5, {0, 1, 2}, false); ASSERT_FALSE( transformation.IsApplicable(context.get(), transformation_context)); + + // Tests |words| having 2 words for a 32-bit float type. + transformation = TransformationAddConstantScalar(19, 4, {0, 1}, false); + ASSERT_FALSE( + transformation.IsApplicable(context.get(), transformation_context)); } TEST(TransformationAddConstantScalarTest, Apply) { @@ -171,7 +176,11 @@ TEST(TransformationAddConstantScalarTest, Apply) { MakeUnique(context.get()), validator_options); // Adds 32-bit unsigned integer (1 logical operand with 1 word). auto transformation = TransformationAddConstantScalar(19, 2, {4}, false); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(19)); + ASSERT_EQ(nullptr, context->get_constant_mgr()->FindDeclaredConstant(19)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpConstant, context->get_def_use_mgr()->GetDef(19)->opcode()); + ASSERT_EQ(4, context->get_constant_mgr()->FindDeclaredConstant(19)->GetU32()); auto* constant_instruction = context->get_def_use_mgr()->GetDef(19); EXPECT_EQ(constant_instruction->NumInOperands(), 1); EXPECT_EQ(constant_instruction->NumInOperandWords(), 1); diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_dead_block_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_dead_block_test.cpp index 687f00c712..3c9e6b43c4 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_dead_block_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_dead_block_test.cpp @@ -142,6 +142,99 @@ TEST(TransformationAddDeadBlockTest, BasicTest) { ASSERT_TRUE(IsEqual(env, variant_shader, context.get())); } +TEST(TransformationAddDeadBlockTest, ApplicableWithFalseCondition) { + std::string reference_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %6 "main" + OpExecutionMode %6 OriginUpperLeft + +; Types + %2 = OpTypeBool + %3 = OpTypeVoid + %4 = OpTypeFunction %3 + +; Constants + %5 = OpConstantFalse %2 + +; main function + %6 = OpFunction %3 None %4 + %7 = OpLabel + OpSelectionMerge %11 None + OpBranchConditional %5 %8 %9 + %8 = OpLabel + OpBranch %10 + %9 = OpLabel + OpBranch %10 + %10 = OpLabel + OpBranch %11 + %11 = OpLabel + OpBranch %13 + %12 = OpLabel + OpBranch %13 + %13 = OpLabel + OpReturn + OpFunctionEnd + )"; + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, reference_shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + auto transformation = TransformationAddDeadBlock(14, 11, false); + + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + + std::string variant_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %6 "main" + OpExecutionMode %6 OriginUpperLeft + +; Types + %2 = OpTypeBool + %3 = OpTypeVoid + %4 = OpTypeFunction %3 + +; Constants + %5 = OpConstantFalse %2 + +; main function + %6 = OpFunction %3 None %4 + %7 = OpLabel + OpSelectionMerge %11 None + OpBranchConditional %5 %8 %9 + %8 = OpLabel + OpBranch %10 + %9 = OpLabel + OpBranch %10 + %10 = OpLabel + OpBranch %11 + %11 = OpLabel + OpSelectionMerge %13 None + OpBranchConditional %5 %14 %13 + %14 = OpLabel + OpBranch %13 + %12 = OpLabel + OpBranch %13 + %13 = OpLabel + OpReturn + OpFunctionEnd + )"; + + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + ASSERT_TRUE(IsEqual(env, variant_shader, context.get())); +} + TEST(TransformationAddDeadBlockTest, TargetBlockMustNotBeSelectionMerge) { std::string shader = R"( OpCapability Shader diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_global_undef_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_global_undef_test.cpp index c3a49e474b..03b915705e 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_global_undef_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_global_undef_test.cpp @@ -63,9 +63,18 @@ TEST(TransformationAddGlobalUndefTest, BasicTest) { ASSERT_FALSE(TransformationAddGlobalUndef(100, 3).IsApplicable( context.get(), transformation_context)); + { + // %100 = OpUndef %6 + TransformationAddGlobalUndef transformation(100, 6); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpUndef, context->get_def_use_mgr()->GetDef(100)->opcode()); + } + TransformationAddGlobalUndef transformations[] = { - // %100 = OpUndef %6 - TransformationAddGlobalUndef(100, 6), // %101 = OpUndef %7 TransformationAddGlobalUndef(101, 7), diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_global_variable_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_global_variable_test.cpp index eb958a7799..9531ade7c4 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_global_variable_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_global_variable_test.cpp @@ -118,11 +118,24 @@ TEST(TransformationAddGlobalVariableTest, BasicTest) { 14, false) .IsApplicable(context.get(), transformation_context)); - TransformationAddGlobalVariable transformations[] = { - // %100 = OpVariable %12 Private - TransformationAddGlobalVariable(100, 12, SpvStorageClassPrivate, 16, - true), + { + // %100 = OpVariable %12 Private + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + TransformationAddGlobalVariable transformation( + 100, 12, SpvStorageClassPrivate, 16, true); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpVariable, context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_EQ( + SpvStorageClassPrivate, + static_cast( + context->get_def_use_mgr()->GetDef(100)->GetSingleWordInOperand( + 0))); + } + TransformationAddGlobalVariable transformations[] = { // %101 = OpVariable %10 Private TransformationAddGlobalVariable(101, 10, SpvStorageClassPrivate, 40, false), @@ -225,12 +238,10 @@ TEST(TransformationAddGlobalVariableTest, TestEntryPointInterfaceEnlargement) { %8 = OpTypeVector %6 2 %9 = OpTypePointer Function %6 %10 = OpTypePointer Private %6 - %20 = OpTypePointer Uniform %6 %11 = OpTypePointer Function %7 %12 = OpTypePointer Private %7 %13 = OpTypePointer Private %8 %14 = OpVariable %10 Private - %15 = OpVariable %20 Uniform %16 = OpConstant %7 1 %17 = OpTypePointer Private %10 %18 = OpTypeBool @@ -246,48 +257,96 @@ TEST(TransformationAddGlobalVariableTest, TestEntryPointInterfaceEnlargement) { OpFunctionEnd )"; - const auto env = SPV_ENV_UNIVERSAL_1_4; - const auto consumer = nullptr; - const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); - spvtools::ValidatorOptions validator_options; - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); - TransformationContext transformation_context( - MakeUnique(context.get()), validator_options); - TransformationAddGlobalVariable transformations[] = { - // %100 = OpVariable %12 Private - TransformationAddGlobalVariable(100, 12, SpvStorageClassPrivate, 16, - true), + for (auto env : {SPV_ENV_UNIVERSAL_1_4, SPV_ENV_UNIVERSAL_1_5, + SPV_ENV_VULKAN_1_1_SPIRV_1_4, SPV_ENV_VULKAN_1_2}) { + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + TransformationAddGlobalVariable transformations[] = { + // %100 = OpVariable %12 Private + TransformationAddGlobalVariable(100, 12, SpvStorageClassPrivate, 16, + true), - // %101 = OpVariable %12 Private %16 - TransformationAddGlobalVariable(101, 12, SpvStorageClassPrivate, 16, - false), + // %101 = OpVariable %12 Private %16 + TransformationAddGlobalVariable(101, 12, SpvStorageClassPrivate, 16, + false), - // %102 = OpVariable %19 Private %21 - TransformationAddGlobalVariable(102, 19, SpvStorageClassPrivate, 21, - true)}; + // %102 = OpVariable %19 Private %21 + TransformationAddGlobalVariable(102, 19, SpvStorageClassPrivate, 21, + true)}; - for (auto& transformation : transformations) { + for (auto& transformation : transformations) { + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } - ASSERT_TRUE( - transformation_context.GetFactManager()->PointeeValueIsIrrelevant(100)); - ASSERT_TRUE( - transformation_context.GetFactManager()->PointeeValueIsIrrelevant(102)); - ASSERT_FALSE( - transformation_context.GetFactManager()->PointeeValueIsIrrelevant(101)); - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(100)); + ASSERT_TRUE( + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(102)); + ASSERT_FALSE( + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(101)); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); - std::string after_transformation = R"( + std::string after_transformation_enlarged_interface = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "m1" %100 %101 %102 + OpEntryPoint Vertex %5 "m2" %100 %101 %102 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeInt 32 1 + %8 = OpTypeVector %6 2 + %9 = OpTypePointer Function %6 + %10 = OpTypePointer Private %6 + %11 = OpTypePointer Function %7 + %12 = OpTypePointer Private %7 + %13 = OpTypePointer Private %8 + %14 = OpVariable %10 Private + %16 = OpConstant %7 1 + %17 = OpTypePointer Private %10 + %18 = OpTypeBool + %19 = OpTypePointer Private %18 + %21 = OpConstantTrue %18 + %100 = OpVariable %12 Private %16 + %101 = OpVariable %12 Private %16 + %102 = OpVariable %19 Private %21 + %4 = OpFunction %2 None %3 + %30 = OpLabel + OpReturn + OpFunctionEnd + %5 = OpFunction %2 None %3 + %31 = OpLabel + OpReturn + OpFunctionEnd + )"; + + ASSERT_TRUE( + IsEqual(env, after_transformation_enlarged_interface, context.get())); + } +} + +TEST(TransformationAddGlobalVariableTest, + TestEntryPointInterfaceNoEnlargement) { + // This checks that when global variables are added to a SPIR-V 1.3- module, + // they are not added to entry points of that module. + std::string shader = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %4 "m1" %100 %101 %102 - OpEntryPoint Vertex %5 "m2" %100 %101 %102 + OpEntryPoint Fragment %4 "m1" + OpEntryPoint Vertex %5 "m2" OpExecutionMode %4 OriginUpperLeft OpSource ESSL 310 %2 = OpTypeVoid @@ -297,20 +356,15 @@ TEST(TransformationAddGlobalVariableTest, TestEntryPointInterfaceEnlargement) { %8 = OpTypeVector %6 2 %9 = OpTypePointer Function %6 %10 = OpTypePointer Private %6 - %20 = OpTypePointer Uniform %6 %11 = OpTypePointer Function %7 %12 = OpTypePointer Private %7 %13 = OpTypePointer Private %8 %14 = OpVariable %10 Private - %15 = OpVariable %20 Uniform %16 = OpConstant %7 1 %17 = OpTypePointer Private %10 %18 = OpTypeBool %19 = OpTypePointer Private %18 %21 = OpConstantTrue %18 - %100 = OpVariable %12 Private %16 - %101 = OpVariable %12 Private %16 - %102 = OpVariable %19 Private %21 %4 = OpFunction %2 None %3 %30 = OpLabel OpReturn @@ -320,7 +374,86 @@ TEST(TransformationAddGlobalVariableTest, TestEntryPointInterfaceEnlargement) { OpReturn OpFunctionEnd )"; - ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); + + for (auto env : + {SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1, SPV_ENV_UNIVERSAL_1_2, + SPV_ENV_UNIVERSAL_1_3, SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1}) { + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + TransformationAddGlobalVariable transformations[] = { + // %100 = OpVariable %12 Private + TransformationAddGlobalVariable(100, 12, SpvStorageClassPrivate, 16, + true), + + // %101 = OpVariable %12 Private %16 + TransformationAddGlobalVariable(101, 12, SpvStorageClassPrivate, 16, + false), + + // %102 = OpVariable %19 Private %21 + TransformationAddGlobalVariable(102, 19, SpvStorageClassPrivate, 21, + true)}; + + for (auto& transformation : transformations) { + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + ASSERT_TRUE( + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(100)); + ASSERT_TRUE( + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(102)); + ASSERT_FALSE( + transformation_context.GetFactManager()->PointeeValueIsIrrelevant(101)); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + + std::string after_transformation_fixed_interface = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "m1" + OpEntryPoint Vertex %5 "m2" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeInt 32 1 + %8 = OpTypeVector %6 2 + %9 = OpTypePointer Function %6 + %10 = OpTypePointer Private %6 + %11 = OpTypePointer Function %7 + %12 = OpTypePointer Private %7 + %13 = OpTypePointer Private %8 + %14 = OpVariable %10 Private + %16 = OpConstant %7 1 + %17 = OpTypePointer Private %10 + %18 = OpTypeBool + %19 = OpTypePointer Private %18 + %21 = OpConstantTrue %18 + %100 = OpVariable %12 Private %16 + %101 = OpVariable %12 Private %16 + %102 = OpVariable %19 Private %21 + %4 = OpFunction %2 None %3 + %30 = OpLabel + OpReturn + OpFunctionEnd + %5 = OpFunction %2 None %3 + %31 = OpLabel + OpReturn + OpFunctionEnd + )"; + + ASSERT_TRUE( + IsEqual(env, after_transformation_fixed_interface, context.get())); + } } TEST(TransformationAddGlobalVariableTest, TestAddingWorkgroupGlobals) { diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_local_variable_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_local_variable_test.cpp index ed57a28b2d..de88573a4a 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_local_variable_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_local_variable_test.cpp @@ -98,10 +98,14 @@ TEST(TransformationAddLocalVariableTest, BasicTest) { // %105 = OpVariable %50 Function %51 { TransformationAddLocalVariable transformation(105, 50, 4, 51, true); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(105)); + ASSERT_EQ(nullptr, context->get_instr_block(105)); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpVariable, context->get_def_use_mgr()->GetDef(105)->opcode()); + ASSERT_EQ(5, context->get_instr_block(105)->id()); } // %104 = OpVariable %41 Function %46 diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_parameter_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_parameter_test.cpp index 7b2a15f7e0..2ae60c9d64 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_parameter_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_parameter_test.cpp @@ -35,6 +35,10 @@ TEST(TransformationAddParameterTest, NonPointerBasicTest) { %7 = OpTypeBool %11 = OpTypeInt 32 1 %16 = OpTypeFloat 32 + %51 = OpConstant %11 2 + %52 = OpTypeArray %16 %51 + %53 = OpConstant %16 7 + %54 = OpConstantComposite %52 %53 %53 %3 = OpTypeFunction %2 %6 = OpTypeFunction %7 %7 %8 = OpConstant %11 23 @@ -140,6 +144,14 @@ TEST(TransformationAddParameterTest, NonPointerBasicTest) { context.get(), validator_options, kConsoleMessageConsumer)); ASSERT_TRUE(transformation_context.GetFactManager()->IdIsIrrelevant(60)); } + { + TransformationAddParameter correct(9, 68, 52, {{{13, 54}}}, 69); + ASSERT_TRUE(correct.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(correct, context.get(), &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + ASSERT_TRUE(transformation_context.GetFactManager()->IdIsIrrelevant(68)); + } { TransformationAddParameter correct(17, 62, 7, {{}}, 63); ASSERT_TRUE(correct.IsApplicable(context.get(), transformation_context)); @@ -177,6 +189,10 @@ TEST(TransformationAddParameterTest, NonPointerBasicTest) { %7 = OpTypeBool %11 = OpTypeInt 32 1 %16 = OpTypeFloat 32 + %51 = OpConstant %11 2 + %52 = OpTypeArray %16 %51 + %53 = OpConstant %16 7 + %54 = OpConstantComposite %52 %53 %53 %3 = OpTypeFunction %2 %8 = OpConstant %11 23 %12 = OpConstantTrue %7 @@ -188,11 +204,11 @@ TEST(TransformationAddParameterTest, NonPointerBasicTest) { %41 = OpTypeStruct %11 %16 %42 = OpConstantComposite %41 %8 %32 %44 = OpTypeFunction %2 %41 %7 - %6 = OpTypeFunction %7 %7 %11 + %6 = OpTypeFunction %7 %7 %11 %52 %65 = OpTypeFunction %2 %31 %4 = OpFunction %2 None %3 %5 = OpLabel - %13 = OpFunctionCall %7 %9 %12 %8 + %13 = OpFunctionCall %7 %9 %12 %8 %54 OpReturn OpFunctionEnd @@ -200,6 +216,7 @@ TEST(TransformationAddParameterTest, NonPointerBasicTest) { %9 = OpFunction %7 None %6 %14 = OpFunctionParameter %7 %60 = OpFunctionParameter %11 + %68 = OpFunctionParameter %52 %10 = OpLabel OpReturnValue %12 OpFunctionEnd diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_synonym_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_synonym_test.cpp index 3803fa3a35..314b0039e9 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_synonym_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_synonym_test.cpp @@ -197,6 +197,7 @@ TEST(TransformationAddSynonymTest, AddZeroSubZeroMulOne) { %37 = OpTypeVector %36 2 %38 = OpConstantTrue %36 %39 = OpConstantComposite %37 %38 %38 + %40 = OpConstant %6 37 %4 = OpFunction %2 None %3 %5 = OpLabel OpReturn @@ -249,6 +250,29 @@ TEST(TransformationAddSynonymTest, AddZeroSubZeroMulOne) { ++fresh_id; } } + { + TransformationAddSynonym transformation( + 40, protobufs::TransformationAddSynonym::BITWISE_OR, fresh_id, + insert_before); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous( + MakeDataDescriptor(40, {}), MakeDataDescriptor(fresh_id, {}))); + ++fresh_id; + } + { + TransformationAddSynonym transformation( + 40, protobufs::TransformationAddSynonym::BITWISE_XOR, fresh_id, + insert_before); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous( + MakeDataDescriptor(40, {}), MakeDataDescriptor(fresh_id, {}))); + } std::string expected_shader = R"( OpCapability Shader @@ -289,6 +313,7 @@ TEST(TransformationAddSynonymTest, AddZeroSubZeroMulOne) { %37 = OpTypeVector %36 2 %38 = OpConstantTrue %36 %39 = OpConstantComposite %37 %38 %38 + %40 = OpConstant %6 37 %4 = OpFunction %2 None %3 %5 = OpLabel %50 = OpIAdd %6 %9 %7 @@ -303,6 +328,8 @@ TEST(TransformationAddSynonymTest, AddZeroSubZeroMulOne) { %59 = OpFMul %14 %17 %16 %60 = OpFMul %18 %23 %20 %61 = OpIMul %24 %29 %26 + %62 = OpBitwiseOr %6 %40 %7 + %63 = OpBitwiseXor %6 %40 %7 OpReturn OpFunctionEnd )"; diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_array_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_array_test.cpp index ab4ed9a188..2ef8200ed4 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_array_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_array_test.cpp @@ -90,19 +90,34 @@ TEST(TransformationAddTypeArrayTest, BasicTest) { ASSERT_FALSE(TransformationAddTypeArray(100, 11, 17) .IsApplicable(context.get(), transformation_context)); - TransformationAddTypeArray transformations[] = { - // %100 = OpTypeArray %10 %16 - TransformationAddTypeArray(100, 10, 16), - - // %101 = OpTypeArray %7 %12 - TransformationAddTypeArray(101, 7, 12)}; - - for (auto& transformation : transformations) { + { + // %100 = OpTypeArray %10 %16 + TransformationAddTypeArray transformation(100, 10, 16); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100)); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpTypeArray, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsArray()); } + + { + // %101 = OpTypeArray %7 %12 + TransformationAddTypeArray transformation(101, 7, 12); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(101)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(101)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpTypeArray, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsArray()); + } + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_boolean_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_boolean_test.cpp index 88d9f5b973..a8e657ba97 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_boolean_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_boolean_test.cpp @@ -52,9 +52,13 @@ TEST(TransformationAddTypeBooleanTest, BasicTest) { context.get(), transformation_context)); auto add_type_bool = TransformationAddTypeBoolean(100); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100)); ASSERT_TRUE( add_type_bool.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(add_type_bool, context.get(), &transformation_context); + ASSERT_EQ(SpvOpTypeBool, context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsBool()); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_float_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_float_test.cpp index 235d61b648..9275bec142 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_float_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_float_test.cpp @@ -61,7 +61,8 @@ TEST(TransformationAddTypeFloatTest, IsApplicable) { ASSERT_FALSE( transformation.IsApplicable(context.get(), transformation_context)); - // Tests existing 16-bit float type. + // The transformation is not applicable because there is already a 16-bit + // float type declared in the module. transformation = TransformationAddTypeFloat(7, 16); ASSERT_FALSE( transformation.IsApplicable(context.get(), transformation_context)); @@ -70,6 +71,19 @@ TEST(TransformationAddTypeFloatTest, IsApplicable) { transformation = TransformationAddTypeFloat(7, 32); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); + + // By default, SPIR-V does not support 64-bit float types. + // Below we add such capability, so the test should now pass. + context.get()->get_feature_mgr()->AddCapability(SpvCapabilityFloat64); + ASSERT_TRUE(TransformationAddTypeFloat(7, 64).IsApplicable( + context.get(), transformation_context)); + +#ifndef NDEBUG + // Should not be able to add float type of width different from 16/32/64 + ASSERT_DEATH(TransformationAddTypeFloat(7, 20).IsApplicable( + context.get(), transformation_context), + "Unexpected float type width"); +#endif } TEST(TransformationAddTypeFloatTest, Apply) { @@ -103,15 +117,27 @@ TEST(TransformationAddTypeFloatTest, Apply) { MakeUnique(context.get()), validator_options); // Adds 16-bit float type. auto transformation = TransformationAddTypeFloat(6, 16); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(6)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(6)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpTypeFloat, context->get_def_use_mgr()->GetDef(6)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(6)->AsFloat()); // Adds 32-bit float type. transformation = TransformationAddTypeFloat(7, 32); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(7)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(7)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpTypeFloat, context->get_def_use_mgr()->GetDef(7)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(7)->AsFloat()); // Adds 64-bit float type. transformation = TransformationAddTypeFloat(8, 64); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(8)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(8)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpTypeFloat, context->get_def_use_mgr()->GetDef(8)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(8)->AsFloat()); std::string variant_shader = R"( OpCapability Shader diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_int_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_int_test.cpp index ee4e79963f..ed8e00a620 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_int_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_int_test.cpp @@ -85,6 +85,29 @@ TEST(TransformationAddTypeIntTest, IsApplicable) { transformation = TransformationAddTypeInt(7, 32, true); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); + + // By default SPIR-V does not support 16-bit integers. + // Below we add such capability, so the test should now be succesful. + context.get()->get_feature_mgr()->AddCapability(SpvCapabilityInt16); + ASSERT_TRUE(TransformationAddTypeInt(7, 16, true) + .IsApplicable(context.get(), transformation_context)); + + // By default SPIR-V does not support 64-bit integers. + // Below we add such capability, so the test should now pass. + context.get()->get_feature_mgr()->AddCapability(SpvCapabilityInt64); + ASSERT_TRUE(TransformationAddTypeInt(7, 64, true) + .IsApplicable(context.get(), transformation_context)); + +#ifndef NDEBUG + // Should not be able to add signed/unsigned integers of width different from + // 16/32/64 bits. + ASSERT_DEATH(TransformationAddTypeInt(7, 20, false) + .IsApplicable(context.get(), transformation_context), + "Unexpected integer type width"); + ASSERT_DEATH(TransformationAddTypeInt(12, 15, false) + .IsApplicable(context.get(), transformation_context), + "Unexpected integer type width"); +#endif } TEST(TransformationAddTypeIntTest, Apply) { @@ -118,8 +141,14 @@ TEST(TransformationAddTypeIntTest, Apply) { TransformationContext transformation_context( MakeUnique(context.get()), validator_options); // Adds signed 8-bit integer type. + // For this transformation we also check that the def-use manager and type + // manager are updated appropriately. auto transformation = TransformationAddTypeInt(6, 8, true); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(6)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(6)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpTypeInt, context->get_def_use_mgr()->GetDef(6)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(6)->AsInteger()); // Adds signed 16-bit integer type. transformation = TransformationAddTypeInt(7, 16, true); diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_matrix_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_matrix_test.cpp index 926e983e82..df0111e2d7 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_matrix_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_matrix_test.cpp @@ -63,10 +63,21 @@ TEST(TransformationAddTypeMatrixTest, BasicTest) { ASSERT_FALSE(TransformationAddTypeMatrix(100, 11, 2) .IsApplicable(context.get(), transformation_context)); - TransformationAddTypeMatrix transformations[] = { - // %100 = OpTypeMatrix %8 2 - TransformationAddTypeMatrix(100, 8, 2), + { + // %100 = OpTypeMatrix %8 2 + TransformationAddTypeMatrix transformation(100, 8, 2); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpTypeMatrix, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsMatrix()); + } + TransformationAddTypeMatrix transformations[] = { // %101 = OpTypeMatrix %8 3 TransformationAddTypeMatrix(101, 8, 3), diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_pointer_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_pointer_test.cpp index 985e904483..b9072e3c1b 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_pointer_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_pointer_test.cpp @@ -133,10 +133,24 @@ TEST(TransformationAddTypePointerTest, BasicTest) { ASSERT_FALSE(bad_result_id_is_not_fresh.IsApplicable(context.get(), transformation_context)); + { + auto& transformation = good_new_private_pointer_to_t; + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(101)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(101)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + ASSERT_EQ(SpvOpTypePointer, + context->get_def_use_mgr()->GetDef(101)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(101)->AsPointer()); + } + for (auto& transformation : - {good_new_private_pointer_to_t, good_new_uniform_pointer_to_t, - good_another_function_pointer_to_s, good_new_uniform_pointer_to_s, - good_another_private_pointer_to_float, + {good_new_uniform_pointer_to_t, good_another_function_pointer_to_s, + good_new_uniform_pointer_to_s, good_another_private_pointer_to_float, good_new_private_pointer_to_private_pointer_to_float, good_new_uniform_pointer_to_vec2, good_new_private_pointer_to_uniform_pointer_to_vec2}) { diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_struct_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_struct_test.cpp index b57bab2567..7fb91ab4c0 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_struct_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_struct_test.cpp @@ -63,10 +63,21 @@ TEST(TransformationAddTypeStructTest, BasicTest) { ASSERT_FALSE(TransformationAddTypeStruct(100, {3}).IsApplicable( context.get(), transformation_context)); - TransformationAddTypeStruct transformations[] = { - // %100 = OpTypeStruct %6 %7 %8 %9 %10 %11 - TransformationAddTypeStruct(100, {6, 7, 8, 9, 10, 11}), + { + // %100 = OpTypeStruct %6 %7 %8 %9 %10 %11 + TransformationAddTypeStruct transformation(100, {6, 7, 8, 9, 10, 11}); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpTypeStruct, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsStruct()); + } + TransformationAddTypeStruct transformations[] = { // %101 = OpTypeStruct TransformationAddTypeStruct(101, {}), diff --git a/third_party/spirv-tools/test/fuzz/transformation_add_type_vector_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_add_type_vector_test.cpp index a49ba6e6c5..755bc4a81f 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_add_type_vector_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_add_type_vector_test.cpp @@ -57,10 +57,21 @@ TEST(TransformationAddTypeVectorTest, BasicTest) { ASSERT_FALSE(TransformationAddTypeVector(100, 1, 2).IsApplicable( context.get(), transformation_context)); - TransformationAddTypeVector transformations[] = { - // %100 = OpTypeVector %6 2 - TransformationAddTypeVector(100, 6, 2), + { + // %100 = OpTypeVector %6 2 + TransformationAddTypeVector transformation(100, 6, 2); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100)); + ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + ASSERT_EQ(SpvOpTypeVector, + context->get_def_use_mgr()->GetDef(100)->opcode()); + ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsVector()); + } + TransformationAddTypeVector transformations[] = { // %101 = OpTypeVector %7 3 TransformationAddTypeVector(101, 7, 3), diff --git a/third_party/spirv-tools/test/fuzz/transformation_composite_construct_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_composite_construct_test.cpp index d2a18b000f..3c5f7310a7 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_composite_construct_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_composite_construct_test.cpp @@ -142,12 +142,29 @@ TEST(TransformationCompositeConstructTest, ConstructArrays) { TransformationCompositeConstruct make_vec2_array_length_3_bad( 37, {41, 45, 27, 27}, MakeInstructionDescriptor(46, SpvOpAccessChain, 0), 200); + // The first component does not correspond to an instruction with a result + // type so this check should return false. + TransformationCompositeConstruct make_vec2_array_length_3_nores( + 37, {2, 45, 27}, MakeInstructionDescriptor(46, SpvOpAccessChain, 0), 200); ASSERT_TRUE(make_vec2_array_length_3.IsApplicable(context.get(), transformation_context)); ASSERT_FALSE(make_vec2_array_length_3_bad.IsApplicable( context.get(), transformation_context)); + ASSERT_FALSE(make_vec2_array_length_3_nores.IsApplicable( + context.get(), transformation_context)); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(200)); + ASSERT_EQ(nullptr, context->get_instr_block(200)); + uint32_t num_uses_of_41_before = context->get_def_use_mgr()->NumUses(41); + uint32_t num_uses_of_45_before = context->get_def_use_mgr()->NumUses(45); + uint32_t num_uses_of_27_before = context->get_def_use_mgr()->NumUses(27); ApplyAndCheckFreshIds(make_vec2_array_length_3, context.get(), &transformation_context); + ASSERT_EQ(SpvOpCompositeConstruct, + context->get_def_use_mgr()->GetDef(200)->opcode()); + ASSERT_EQ(34, context->get_instr_block(200)->id()); + ASSERT_EQ(num_uses_of_41_before + 1, context->get_def_use_mgr()->NumUses(41)); + ASSERT_EQ(num_uses_of_45_before + 1, context->get_def_use_mgr()->NumUses(45)); + ASSERT_EQ(num_uses_of_27_before + 1, context->get_def_use_mgr()->NumUses(27)); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous( @@ -412,9 +429,15 @@ TEST(TransformationCompositeConstructTest, ConstructMatrices) { // Bad: %35 is mat4x3, not mat3x4. TransformationCompositeConstruct make_mat34_bad( 35, {25, 28, 31}, MakeInstructionDescriptor(31, SpvOpReturn, 0), 200); + // The first component does not correspond to an instruction with a result + // type so this check should return false. + TransformationCompositeConstruct make_mat34_nores( + 32, {2, 28, 31}, MakeInstructionDescriptor(31, SpvOpReturn, 0), 200); ASSERT_TRUE(make_mat34.IsApplicable(context.get(), transformation_context)); ASSERT_FALSE( make_mat34_bad.IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + make_mat34_nores.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(make_mat34, context.get(), &transformation_context); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); @@ -625,9 +648,15 @@ TEST(TransformationCompositeConstructTest, ConstructStructs) { // Bad: Too few fields to make the struct. TransformationCompositeConstruct make_inner_bad( 9, {25}, MakeInstructionDescriptor(57, SpvOpAccessChain, 0), 200); + // The first component does not correspond to an instruction with a result + // type so this check should return false. + TransformationCompositeConstruct make_inner_nores( + 9, {2, 19}, MakeInstructionDescriptor(57, SpvOpAccessChain, 0), 200); ASSERT_TRUE(make_inner.IsApplicable(context.get(), transformation_context)); ASSERT_FALSE( make_inner_bad.IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + make_inner_nores.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(make_inner, context.get(), &transformation_context); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); @@ -1643,6 +1672,55 @@ TEST(TransformationCompositeConstructTest, OneIrrelevantComponent) { MakeDataDescriptor(100, {2}), MakeDataDescriptor(10, {}))); } +TEST(TransformationCompositeConstructTest, IrrelevantVec2ThenFloat) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeVector %6 2 + %8 = OpTypeVector %6 3 + %9 = OpConstant %6 0 + %11 = OpConstant %6 1 + %12 = OpConstant %6 2 + %10 = OpConstantComposite %7 %11 %12 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + transformation_context.GetFactManager()->AddFactIdIsIrrelevant(10); + + TransformationCompositeConstruct transformation( + 8, {10, 9}, MakeInstructionDescriptor(5, SpvOpReturn, 0), 100); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_FALSE(transformation_context.GetFactManager()->IsSynonymous( + MakeDataDescriptor(100, {0}), MakeDataDescriptor(10, {0}))); + ASSERT_FALSE(transformation_context.GetFactManager()->IsSynonymous( + MakeDataDescriptor(100, {1}), MakeDataDescriptor(10, {1}))); + ASSERT_TRUE(transformation_context.GetFactManager()->IsSynonymous( + MakeDataDescriptor(100, {2}), MakeDataDescriptor(9, {}))); + ASSERT_FALSE(transformation_context.GetFactManager()->IsSynonymous( + MakeDataDescriptor(100, {1}), MakeDataDescriptor(9, {}))); +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_composite_extract_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_composite_extract_test.cpp index 383a4db1a1..1df55918c9 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_composite_extract_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_composite_extract_test.cpp @@ -143,10 +143,18 @@ TEST(TransformationCompositeExtractTest, BasicTest) { TransformationCompositeExtract transformation_1( MakeInstructionDescriptor(36, SpvOpConvertFToS, 0), 201, 100, {2}); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(201)); + ASSERT_EQ(nullptr, context->get_instr_block(201)); + uint32_t num_uses_of_100_before = context->get_def_use_mgr()->NumUses(100); ASSERT_TRUE( transformation_1.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation_1, context.get(), &transformation_context); + ASSERT_EQ(SpvOpCompositeExtract, + context->get_def_use_mgr()->GetDef(201)->opcode()); + ASSERT_EQ(15, context->get_instr_block(201)->id()); + ASSERT_EQ(num_uses_of_100_before + 1, + context->get_def_use_mgr()->NumUses(100)); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); diff --git a/third_party/spirv-tools/test/fuzz/transformation_duplicate_region_with_selection_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_duplicate_region_with_selection_test.cpp index f3738e7409..31fb9a2f1a 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_duplicate_region_with_selection_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_duplicate_region_with_selection_test.cpp @@ -1334,6 +1334,9 @@ TEST(TransformationDuplicateRegionWithSelectionTest, OpBranch %50 %50 = OpLabel %51 = OpCopyObject %7 %12 + OpBranch %52 + %52 = OpLabel + %53 = OpCopyObject %7 %51 OpReturn OpFunctionEnd )"; @@ -2275,6 +2278,207 @@ TEST(TransformationDuplicateRegionWithSelectionTest, .IsApplicable(context.get(), transformation_context)); } +TEST(TransformationDuplicateRegionWithSelectionTest, + DoNotProduceOpPhiWithVoidType) { + std::string reference_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %10 = OpTypeBool + %11 = OpConstantTrue %10 + %4 = OpFunction %2 None %3 + %12 = OpLabel + OpBranch %5 + %5 = OpLabel + %8 = OpFunctionCall %2 %6 + OpReturn + OpFunctionEnd + %6 = OpFunction %2 None %3 + %7 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, reference_shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + TransformationDuplicateRegionWithSelection transformation( + 100, 11, 101, 5, 5, {{5, 102}}, {{8, 103}}, {}); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + std::string expected_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %10 = OpTypeBool + %11 = OpConstantTrue %10 + %4 = OpFunction %2 None %3 + %12 = OpLabel + OpBranch %100 + %100 = OpLabel + OpSelectionMerge %101 None + OpBranchConditional %11 %5 %102 + %5 = OpLabel + %8 = OpFunctionCall %2 %6 + OpBranch %101 + %102 = OpLabel + %103 = OpFunctionCall %2 %6 + OpBranch %101 + %101 = OpLabel + OpReturn + OpFunctionEnd + %6 = OpFunction %2 None %3 + %7 = OpLabel + OpReturn + OpFunctionEnd + )"; + + ASSERT_TRUE(IsEqual(env, expected_shader, context.get())); +} + +TEST(TransformationDuplicateRegionWithSelectionTest, + DoNotProduceOpPhiWithDisallowedType) { + std::string reference_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpDecorate %13 DescriptorSet 0 + OpDecorate %13 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeVector %6 2 + %8 = OpTypePointer Function %7 + %10 = OpTypeImage %6 2D 0 0 0 1 Unknown + %11 = OpTypeSampledImage %10 + %12 = OpTypePointer UniformConstant %11 + %13 = OpVariable %12 UniformConstant + %15 = OpConstant %6 1 + %16 = OpConstantComposite %7 %15 %15 + %17 = OpTypeVector %6 4 + %19 = OpTypeInt 32 0 + %20 = OpConstant %19 0 + %22 = OpTypePointer Function %6 + %90 = OpTypeBool + %91 = OpConstantTrue %90 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %9 = OpVariable %8 Function + OpBranch %81 + %81 = OpLabel + %14 = OpLoad %11 %13 + %18 = OpImageSampleImplicitLod %17 %14 %16 + %21 = OpCompositeExtract %6 %18 0 + %23 = OpAccessChain %22 %9 %20 + OpStore %23 %21 + OpBranch %80 + %80 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, reference_shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + TransformationDuplicateRegionWithSelection transformation( + 100, 91, 101, 81, 81, {{81, 102}}, + {{14, 103}, {18, 104}, {21, 105}, {23, 106}}, {{18, 107}, {21, 108}}); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + std::string expected_shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpDecorate %13 DescriptorSet 0 + OpDecorate %13 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeVector %6 2 + %8 = OpTypePointer Function %7 + %10 = OpTypeImage %6 2D 0 0 0 1 Unknown + %11 = OpTypeSampledImage %10 + %12 = OpTypePointer UniformConstant %11 + %13 = OpVariable %12 UniformConstant + %15 = OpConstant %6 1 + %16 = OpConstantComposite %7 %15 %15 + %17 = OpTypeVector %6 4 + %19 = OpTypeInt 32 0 + %20 = OpConstant %19 0 + %22 = OpTypePointer Function %6 + %90 = OpTypeBool + %91 = OpConstantTrue %90 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %9 = OpVariable %8 Function + OpBranch %100 + %100 = OpLabel + OpSelectionMerge %101 None + OpBranchConditional %91 %81 %102 + %81 = OpLabel + %14 = OpLoad %11 %13 + %18 = OpImageSampleImplicitLod %17 %14 %16 + %21 = OpCompositeExtract %6 %18 0 + %23 = OpAccessChain %22 %9 %20 + OpStore %23 %21 + OpBranch %101 + %102 = OpLabel + %103 = OpLoad %11 %13 + %104 = OpImageSampleImplicitLod %17 %103 %16 + %105 = OpCompositeExtract %6 %104 0 + %106 = OpAccessChain %22 %9 %20 + OpStore %106 %105 + OpBranch %101 + %101 = OpLabel + %107 = OpPhi %17 %18 %81 %104 %102 + %108 = OpPhi %6 %21 %81 %105 %102 + OpBranch %80 + %80 = OpLabel + OpReturn + OpFunctionEnd + )"; + + ASSERT_TRUE(IsEqual(env, expected_shader, context.get())); +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_equation_instruction_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_equation_instruction_test.cpp index 654fffcbbd..5b5033d239 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_equation_instruction_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_equation_instruction_test.cpp @@ -102,8 +102,12 @@ TEST(TransformationEquationInstructionTest, SignedNegate) { 14, SpvOpSNegate, {7}, return_instruction); ASSERT_TRUE( transformation1.IsApplicable(context.get(), transformation_context)); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(14)); + ASSERT_EQ(nullptr, context->get_instr_block(14)); ApplyAndCheckFreshIds(transformation1, context.get(), &transformation_context); + ASSERT_EQ(SpvOpSNegate, context->get_def_use_mgr()->GetDef(14)->opcode()); + ASSERT_EQ(13, context->get_instr_block(14)->id()); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); diff --git a/third_party/spirv-tools/test/fuzz/transformation_flatten_conditional_branch_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_flatten_conditional_branch_test.cpp index e0697d4ebd..800af0ea95 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_flatten_conditional_branch_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_flatten_conditional_branch_test.cpp @@ -666,7 +666,6 @@ TEST(TransformationFlattenConditionalBranchTest, EdgeCases) { OpBranchConditional %5 %13 %12 %13 = OpLabel %14 = OpFunctionCall %3 %11 - %15 = OpCopyObject %3 %14 OpBranch %12 %12 = OpLabel OpReturn @@ -774,7 +773,6 @@ TEST(TransformationFlattenConditionalBranchTest, EdgeCases) { OpBranchConditional %5 %13 %12 %13 = OpLabel %14 = OpFunctionCall %3 %11 - %15 = OpCopyObject %3 %14 OpBranch %12 %12 = OpLabel OpReturn @@ -1336,20 +1334,24 @@ TEST(TransformationFlattenConditionalBranchTest, OpFunctionEnd )"; - const auto env = SPV_ENV_UNIVERSAL_1_3; - const auto consumer = nullptr; - const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); - spvtools::ValidatorOptions validator_options; - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); + for (auto env : + {SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1, SPV_ENV_UNIVERSAL_1_2, + SPV_ENV_UNIVERSAL_1_3, SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1}) { + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); - TransformationContext transformation_context( - MakeUnique(context.get()), validator_options); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); - auto transformation = - TransformationFlattenConditionalBranch(5, true, 0, 0, 0, {}); - ASSERT_FALSE( - transformation.IsApplicable(context.get(), transformation_context)); + auto transformation = + TransformationFlattenConditionalBranch(5, true, 0, 0, 0, {}); + ASSERT_FALSE( + transformation.IsApplicable(context.get(), transformation_context)); + } } TEST(TransformationFlattenConditionalBranchTest, @@ -2135,6 +2137,62 @@ TEST(TransformationFlattenConditionalBranchTest, ContainsContinueBlockTest) { .IsApplicable(context.get(), transformation_context)); } +TEST(TransformationFlattenConditionalBranchTest, ContainsSynonymCreation) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %4 "main" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantFalse %6 + %8 = OpTypeInt 32 0 + %9 = OpTypePointer Function %8 + %10 = OpConstant %8 42 + %80 = OpConstant %8 0 + %4 = OpFunction %2 None %3 + %11 = OpLabel + %20 = OpVariable %9 Function + OpBranch %12 + %12 = OpLabel + OpSelectionMerge %31 None + OpBranchConditional %7 %30 %31 + %30 = OpLabel + OpStore %20 %10 + %21 = OpLoad %8 %20 + OpBranch %31 + %31 = OpLabel + OpBranch %14 + %14 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + transformation_context.GetFactManager()->AddFactDataSynonym( + MakeDataDescriptor(10, {}), MakeDataDescriptor(21, {})); + ASSERT_FALSE(TransformationFlattenConditionalBranch( + 12, true, 0, 0, 0, + {MakeSideEffectWrapperInfo( + MakeInstructionDescriptor(30, SpvOpStore, 0), 100, 101), + MakeSideEffectWrapperInfo( + MakeInstructionDescriptor(21, SpvOpLoad, 0), 102, 103, + 104, 105, 106, 80)}) + .IsApplicable(context.get(), transformation_context)); +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_merge_function_returns_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_merge_function_returns_test.cpp index e60d3458de..400d49ad08 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_merge_function_returns_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_merge_function_returns_test.cpp @@ -147,12 +147,12 @@ TEST(TransformationMergeFunctionReturnsTest, SimpleInapplicable) { MakeUnique(context.get()), validator_options); // Function %1 does not exist. - ASSERT_FALSE(TransformationMergeFunctionReturns(1, 100, 101, 0, 0, {{}}) + ASSERT_FALSE(TransformationMergeFunctionReturns(1, 100, 200, 101, 0, 0, {{}}) .IsApplicable(context.get(), transformation_context)); // The entry block (%22) of function %15 does not branch unconditionally to // the following block. - ASSERT_FALSE(TransformationMergeFunctionReturns(16, 100, 101, 0, 0, {{}}) + ASSERT_FALSE(TransformationMergeFunctionReturns(16, 100, 200, 101, 0, 0, {{}}) .IsApplicable(context.get(), transformation_context)); // Block %28 is the merge block of a loop containing a return instruction, but @@ -160,7 +160,7 @@ TEST(TransformationMergeFunctionReturnsTest, SimpleInapplicable) { // not OpLabel, OpPhi or OpBranch). ASSERT_FALSE( TransformationMergeFunctionReturns( - 18, 100, 101, 0, 0, {{MakeReturnMergingInfo(29, 102, 0, {{}})}}) + 18, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(29, 102, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // Block %34 is the merge block of a loop containing a return instruction, but @@ -168,21 +168,24 @@ TEST(TransformationMergeFunctionReturnsTest, SimpleInapplicable) { // that are not OpLabel, OpPhi or OpBranch). ASSERT_FALSE( TransformationMergeFunctionReturns( - 20, 100, 101, 0, 0, {{MakeReturnMergingInfo(35, 102, 0, {{}})}}) + 20, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(35, 102, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // Id %1000 cannot be found in the module and there is no id of the correct // type (float) available at the end of the entry block of function %21. - ASSERT_FALSE(TransformationMergeFunctionReturns(22, 100, 101, 102, 1000, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + TransformationMergeFunctionReturns(22, 100, 200, 101, 102, 1000, {{}}) + .IsApplicable(context.get(), transformation_context)); // Id %47 is of type float, while function %45 has return type int. - ASSERT_FALSE(TransformationMergeFunctionReturns(45, 100, 101, 102, 47, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + TransformationMergeFunctionReturns(45, 100, 200, 101, 102, 47, {{}}) + .IsApplicable(context.get(), transformation_context)); // Id %50 is not available at the end of the entry block of function %45. - ASSERT_FALSE(TransformationMergeFunctionReturns(45, 100, 101, 102, 50, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + TransformationMergeFunctionReturns(45, 100, 200, 101, 102, 50, {{}}) + .IsApplicable(context.get(), transformation_context)); } TEST(TransformationMergeFunctionReturnsTest, MissingBooleans) { @@ -235,8 +238,9 @@ TEST(TransformationMergeFunctionReturnsTest, MissingBooleans) { TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - ASSERT_FALSE(TransformationMergeFunctionReturns(3, 100, 101, 0, 0, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + TransformationMergeFunctionReturns(3, 100, 200, 101, 0, 0, {{}}) + .IsApplicable(context.get(), transformation_context)); } { // OpConstantFalse is missing. @@ -287,8 +291,9 @@ TEST(TransformationMergeFunctionReturnsTest, MissingBooleans) { TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - ASSERT_FALSE(TransformationMergeFunctionReturns(3, 100, 101, 0, 0, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + TransformationMergeFunctionReturns(3, 100, 200, 101, 0, 0, {{}}) + .IsApplicable(context.get(), transformation_context)); } } @@ -386,59 +391,65 @@ TEST(TransformationMergeFunctionReturnsTest, InvalidIds) { // Fresh id %100 is used twice. ASSERT_FALSE( TransformationMergeFunctionReturns( - 17, 100, 100, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) + 17, 100, 200, 100, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // Fresh id %100 is used twice. ASSERT_FALSE( TransformationMergeFunctionReturns( - 17, 100, 101, 0, 0, {{MakeReturnMergingInfo(20, 100, 0, {{}})}}) + 17, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(20, 100, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // %0 cannot be a fresh id for the new merge block. ASSERT_FALSE( TransformationMergeFunctionReturns( - 17, 100, 0, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) + 17, 100, 200, 0, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) + .IsApplicable(context.get(), transformation_context)); + + // %0 cannot be a fresh id for the new continue block. + ASSERT_FALSE( + TransformationMergeFunctionReturns( + 17, 100, 0, 200, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // %0 cannot be a fresh id for the new header block. ASSERT_FALSE( TransformationMergeFunctionReturns( - 17, 0, 100, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) + 17, 0, 200, 100, 0, 0, {{MakeReturnMergingInfo(20, 101, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // %0 cannot be a fresh id for the new |is_returning| instruction in an // existing merge block. ASSERT_FALSE( TransformationMergeFunctionReturns( - 17, 100, 101, 0, 0, {{MakeReturnMergingInfo(20, 0, 0, {{}})}}) + 17, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(20, 0, 0, {{}})}}) .IsApplicable(context.get(), transformation_context)); // %0 cannot be a fresh id for the new |return_val| instruction in the new // return block. - ASSERT_FALSE( - TransformationMergeFunctionReturns( - 14, 100, 101, 0, 10, {{MakeReturnMergingInfo(27, 102, 103, {{}})}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE(TransformationMergeFunctionReturns( + 14, 100, 200, 101, 0, 10, + {{MakeReturnMergingInfo(27, 102, 103, {{}})}}) + .IsApplicable(context.get(), transformation_context)); // %0 cannot be a fresh id for the new |maybe_return_val| instruction in an // existing merge block, inside a non-void function. - ASSERT_FALSE( - TransformationMergeFunctionReturns( - 14, 100, 101, 102, 10, {{MakeReturnMergingInfo(27, 103, 0, {{}})}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE(TransformationMergeFunctionReturns( + 14, 100, 200, 101, 102, 10, + {{MakeReturnMergingInfo(27, 103, 0, {{}})}}) + .IsApplicable(context.get(), transformation_context)); // Fresh id %102 is repeated. - ASSERT_FALSE( - TransformationMergeFunctionReturns( - 14, 100, 101, 102, 10, {{MakeReturnMergingInfo(27, 102, 104, {{}})}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE(TransformationMergeFunctionReturns( + 14, 100, 200, 101, 102, 10, + {{MakeReturnMergingInfo(27, 102, 104, {{}})}}) + .IsApplicable(context.get(), transformation_context)); // Id %11 (type int) does not have the correct type (float) for OpPhi // instruction %31. ASSERT_FALSE( TransformationMergeFunctionReturns( - 16, 100, 101, 0, 0, + 16, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(36, 103, 104, {{{31, 11}, {32, 11}}})}}) .IsApplicable(context.get(), transformation_context)); @@ -446,21 +457,21 @@ TEST(TransformationMergeFunctionReturnsTest, InvalidIds) { // instruction %31. ASSERT_FALSE( TransformationMergeFunctionReturns( - 16, 100, 101, 0, 0, + 16, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(36, 102, 0, {{{31, 11}, {32, 11}}})}}) .IsApplicable(context.get(), transformation_context)); // Id %43 is not available at the end of the entry block. ASSERT_FALSE( TransformationMergeFunctionReturns( - 16, 100, 101, 0, 0, + 16, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(36, 102, 0, {{{31, 44}, {32, 11}}})}}) .IsApplicable(context.get(), transformation_context)); // There is not a mapping for id %31 (float OpPhi instruction in a loop merge // block) and no suitable id is available at the end of the entry block. ASSERT_FALSE(TransformationMergeFunctionReturns( - 16, 100, 101, 0, 0, + 16, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(36, 102, 0, {{{32, 11}}})}}) .IsApplicable(context.get(), transformation_context)); @@ -468,7 +479,7 @@ TEST(TransformationMergeFunctionReturnsTest, InvalidIds) { // available at the end of the entry block. ASSERT_FALSE( TransformationMergeFunctionReturns( - 16, 100, 101, 0, 0, + 16, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(36, 102, 0, {{{31, 1000}, {32, 11}}})}}) .IsApplicable(context.get(), transformation_context)); } @@ -560,7 +571,7 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { // The 0s are allowed because the function's return type is void. auto transformation1 = - TransformationMergeFunctionReturns(14, 100, 101, 0, 0, {{}}); + TransformationMergeFunctionReturns(14, 100, 200, 101, 0, 0, {{}}); ASSERT_TRUE( transformation1.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation1, context.get(), @@ -570,13 +581,14 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { // %12 is available at the end of the entry block of %19 (it is a global // variable). - ASSERT_TRUE(TransformationMergeFunctionReturns(19, 110, 111, 112, 12, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + TransformationMergeFunctionReturns(19, 110, 210, 111, 112, 12, {{}}) + .IsApplicable(context.get(), transformation_context)); // %1000 cannot be found in the module, but there is a suitable id available // at the end of the entry block (%12). auto transformation2 = - TransformationMergeFunctionReturns(19, 110, 111, 112, 1000, {{}}); + TransformationMergeFunctionReturns(19, 110, 210, 111, 112, 1000, {{}}); ASSERT_TRUE( transformation2.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation2, context.get(), @@ -586,13 +598,14 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { // %27 is available at the end of the entry block of %26 (it is a function // parameter). - ASSERT_TRUE(TransformationMergeFunctionReturns(26, 120, 121, 122, 27, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + TransformationMergeFunctionReturns(26, 120, 220, 121, 122, 27, {{}}) + .IsApplicable(context.get(), transformation_context)); // %1000 cannot be found in the module, but there is a suitable id available // at the end of the entry block (%27). auto transformation3 = - TransformationMergeFunctionReturns(26, 120, 121, 122, 1000, {{}}); + TransformationMergeFunctionReturns(26, 120, 220, 121, 122, 1000, {{}}); ASSERT_TRUE( transformation3.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation3, context.get(), @@ -602,13 +615,14 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { // %35 is available at the end of the entry block of %33 (it is in the entry // block). - ASSERT_TRUE(TransformationMergeFunctionReturns(26, 130, 131, 132, 27, {{}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + TransformationMergeFunctionReturns(26, 130, 230, 131, 132, 27, {{}}) + .IsApplicable(context.get(), transformation_context)); // %1000 cannot be found in the module, but there is a suitable id available // at the end of the entry block (%35). auto transformation4 = - TransformationMergeFunctionReturns(33, 130, 131, 132, 1000, {{}}); + TransformationMergeFunctionReturns(33, 130, 230, 131, 132, 1000, {{}}); ASSERT_TRUE( transformation4.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation4, context.get(), @@ -642,8 +656,8 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { %15 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %11 %16 %100 + OpLoopMerge %101 %200 None + OpBranch %16 %16 = OpLabel OpSelectionMerge %17 None OpBranchConditional %11 %18 %17 @@ -653,13 +667,15 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { OpBranch %101 %101 = OpLabel OpReturn + %200 = OpLabel + OpBranch %100 OpFunctionEnd %19 = OpFunction %5 None %6 %20 = OpLabel OpBranch %110 %110 = OpLabel - OpLoopMerge %111 %110 None - OpBranchConditional %11 %21 %110 + OpLoopMerge %111 %210 None + OpBranch %21 %21 = OpLabel OpSelectionMerge %22 None OpBranchConditional %11 %23 %24 @@ -673,14 +689,16 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { %111 = OpLabel %112 = OpPhi %5 %12 %23 %25 %24 OpReturnValue %112 + %210 = OpLabel + OpBranch %110 OpFunctionEnd %26 = OpFunction %7 None %8 %27 = OpFunctionParameter %7 %28 = OpLabel OpBranch %120 %120 = OpLabel - OpLoopMerge %121 %120 None - OpBranchConditional %11 %29 %120 + OpLoopMerge %121 %220 None + OpBranch %29 %29 = OpLabel OpSelectionMerge %30 None OpBranchConditional %11 %31 %30 @@ -692,14 +710,16 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { %121 = OpLabel %122 = OpPhi %7 %27 %30 %32 %31 OpReturnValue %122 + %220 = OpLabel + OpBranch %120 OpFunctionEnd %33 = OpFunction %7 None %9 %34 = OpLabel %35 = OpConvertSToF %7 %12 OpBranch %130 %130 = OpLabel - OpLoopMerge %131 %130 None - OpBranchConditional %11 %36 %130 + OpLoopMerge %131 %230 None + OpBranch %36 %36 = OpLabel OpSelectionMerge %37 None OpBranchConditional %11 %38 %37 @@ -711,6 +731,8 @@ TEST(TransformationMergeFunctionReturnsTest, Simple) { %131 = OpLabel %132 = OpPhi %7 %35 %37 %39 %38 OpReturnValue %132 + %230 = OpLabel + OpBranch %130 OpFunctionEnd )"; @@ -743,8 +765,8 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { %15 = OpLabel OpBranch %16 %16 = OpLabel - OpLoopMerge %17 %16 None - OpBranchConditional %8 %18 %16 + OpLoopMerge %17 %916 None + OpBranch %18 %18 = OpLabel OpLoopMerge %19 %20 None OpBranchConditional %8 %19 %21 @@ -767,8 +789,8 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { %28 = OpLabel OpBranch %29 %29 = OpLabel - OpLoopMerge %30 %29 None - OpBranchConditional %8 %30 %29 + OpLoopMerge %30 %929 None + OpBranch %30 %30 = OpLabel OpLoopMerge %31 %32 None OpBranch %33 @@ -792,6 +814,10 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { OpBranch %38 %38 = OpLabel OpReturnValue %12 + %916 = OpLabel + OpBranch %16 + %929 = OpLabel + OpBranch %29 OpFunctionEnd )"; @@ -805,7 +831,7 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { MakeUnique(context.get()), validator_options); auto transformation = TransformationMergeFunctionReturns( - 14, 100, 101, 102, 11, + 14, 100, 200, 101, 102, 11, {{MakeReturnMergingInfo(19, 103, 104, {{}}), MakeReturnMergingInfo(17, 105, 106, {{}}), MakeReturnMergingInfo(31, 107, 108, {{{35, 10}, {36, 12}}}), @@ -841,11 +867,11 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { %15 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %8 %16 %100 + OpLoopMerge %101 %200 None + OpBranch %16 %16 = OpLabel - OpLoopMerge %17 %16 None - OpBranchConditional %8 %18 %16 + OpLoopMerge %17 %916 None + OpBranch %18 %18 = OpLabel OpLoopMerge %19 %20 None OpBranchConditional %8 %19 %21 @@ -872,8 +898,8 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { %28 = OpLabel OpBranch %29 %29 = OpLabel - OpLoopMerge %30 %29 None - OpBranchConditional %8 %30 %29 + OpLoopMerge %30 %929 None + OpBranch %30 %30 = OpLabel OpLoopMerge %31 %32 None OpBranch %33 @@ -901,9 +927,15 @@ TEST(TransformationMergeFunctionReturnsTest, NestedLoops) { OpBranchConditional %109 %101 %38 %38 = OpLabel OpBranch %101 + %916 = OpLabel + OpBranch %16 + %929 = OpLabel + OpBranch %29 %101 = OpLabel %102 = OpPhi %5 %106 %17 %110 %23 %12 %38 OpReturnValue %102 + %200 = OpLabel + OpBranch %100 OpFunctionEnd )"; @@ -997,7 +1029,7 @@ TEST(TransformationMergeFunctionReturnsTest, OverflowIds) { // No mapping from merge block %16 to fresh ids is given, so overflow ids are // needed. auto transformation1 = - TransformationMergeFunctionReturns(12, 100, 101, 102, 10, {{}}); + TransformationMergeFunctionReturns(12, 100, 200, 101, 102, 10, {{}}); #ifndef NDEBUG ASSERT_DEATH( @@ -1016,7 +1048,7 @@ TEST(TransformationMergeFunctionReturnsTest, OverflowIds) { // No mapping from merge block %27 to fresh ids is given, so overflow ids are // needed. auto transformation2 = - TransformationMergeFunctionReturns(24, 110, 111, 0, 0, {{}}); + TransformationMergeFunctionReturns(24, 110, 210, 111, 0, 0, {{}}); #ifndef NDEBUG ASSERT_DEATH( @@ -1054,8 +1086,8 @@ TEST(TransformationMergeFunctionReturnsTest, OverflowIds) { %13 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %8 %14 %100 + OpLoopMerge %101 %200 None + OpBranch %14 %14 = OpLabel %15 = OpIAdd %5 %10 %10 OpLoopMerge %16 %17 None @@ -1081,13 +1113,15 @@ TEST(TransformationMergeFunctionReturnsTest, OverflowIds) { %101 = OpLabel %102 = OpPhi %5 %1001 %16 %22 %23 OpReturnValue %102 + %200 = OpLabel + OpBranch %100 OpFunctionEnd %24 = OpFunction %3 None %4 %25 = OpLabel OpBranch %110 %110 = OpLabel - OpLoopMerge %111 %110 None - OpBranchConditional %8 %26 %110 + OpLoopMerge %111 %210 None + OpBranch %26 %26 = OpLabel OpLoopMerge %27 %28 None OpBranch %29 @@ -1110,6 +1144,8 @@ TEST(TransformationMergeFunctionReturnsTest, OverflowIds) { OpBranch %111 %111 = OpLabel OpReturn + %210 = OpLabel + OpBranch %110 OpFunctionEnd )"; @@ -1179,7 +1215,7 @@ TEST(TransformationMergeFunctionReturnsTest, MissingIdsForOpPhi) { // corresponding mapping. auto transformation = TransformationMergeFunctionReturns( - 12, 101, 102, 0, 0, + 12, 101, 200, 102, 0, 0, {{MakeReturnMergingInfo(17, 103, 0, {{{25, 7}, {35, 8}}})}}); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); @@ -1212,8 +1248,8 @@ TEST(TransformationMergeFunctionReturnsTest, MissingIdsForOpPhi) { %15 = OpConvertSToF %10 %13 OpBranch %101 %101 = OpLabel - OpLoopMerge %102 %101 None - OpBranchConditional %6 %16 %101 + OpLoopMerge %102 %200 None + OpBranch %16 %16 = OpLabel OpLoopMerge %17 %18 None OpBranch %19 @@ -1238,6 +1274,8 @@ TEST(TransformationMergeFunctionReturnsTest, MissingIdsForOpPhi) { OpBranch %102 %102 = OpLabel OpReturn + %200 = OpLabel + OpBranch %101 OpFunctionEnd )"; @@ -1324,14 +1362,14 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules1) { // block %14 is added. ASSERT_FALSE( TransformationMergeFunctionReturns( - 2, 100, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}) + 2, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}) .IsApplicable(context.get(), transformation_context)); // In function %18, The definition of id %26 will still dominate its use in // instruction %27 (inside merge block %21), because %27 is an OpPhi // instruction. auto transformation = TransformationMergeFunctionReturns( - 18, 100, 101, 0, 0, {{MakeReturnMergingInfo(21, 102, 103, {{}})}}); + 18, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(21, 102, 103, {{}})}}); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); @@ -1376,8 +1414,8 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules1) { %19 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %6 %20 %100 + OpLoopMerge %101 %200 None + OpBranch %20 %20 = OpLabel OpLoopMerge %21 %22 None OpBranch %23 @@ -1399,6 +1437,8 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules1) { OpBranch %101 %101 = OpLabel OpReturn + %200 = OpLabel + OpBranch %100 OpFunctionEnd )"; @@ -1482,17 +1522,17 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules2) { // block %14 to merge block %10 is added. ASSERT_FALSE( TransformationMergeFunctionReturns( - 2, 100, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}) + 2, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}) .IsApplicable(context.get(), transformation_context)); // In function %18, the definition of id %26 will not dominate its use in // instruction %28 (inside block %27) after a new branch from return // block %25 to merge block %21 is added. - ASSERT_FALSE(TransformationMergeFunctionReturns( - 2, 100, 101, 0, 0, - {{MakeReturnMergingInfo(10, 102, 0, {{}}), - MakeReturnMergingInfo(21, 103, 0, {{}})}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + TransformationMergeFunctionReturns( + 2, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 0, {{}}), + MakeReturnMergingInfo(21, 103, 0, {{}})}}) + .IsApplicable(context.get(), transformation_context)); } TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules3) { @@ -1556,7 +1596,7 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules3) { // fact that the id definition dominates the uses does not depend on it // dominating the merge block. auto transformation = TransformationMergeFunctionReturns( - 2, 100, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}); + 2, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); @@ -1579,8 +1619,8 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules3) { %8 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %6 %9 %100 + OpLoopMerge %101 %200 None + OpBranch %9 %9 = OpLabel OpLoopMerge %10 %11 None OpBranch %12 @@ -1608,6 +1648,8 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules3) { OpBranch %101 %101 = OpLabel OpReturn + %200 = OpLabel + OpBranch %100 OpFunctionEnd )"; @@ -1700,7 +1742,7 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules4) { // instruction %19 after the transformation is applied, because %13 dominates // all of the return blocks. auto transformation = TransformationMergeFunctionReturns( - 2, 100, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}); + 2, 100, 200, 101, 0, 0, {{MakeReturnMergingInfo(10, 102, 103, {{}})}}); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); @@ -1710,10 +1752,10 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules4) { // In function %20, the definition of id %28 will not dominate its use in // instruction %32 after the transformation is applied, because %28 dominates // only one of the return blocks. - ASSERT_FALSE( - TransformationMergeFunctionReturns( - 20, 100, 101, 0, 0, {{MakeReturnMergingInfo(23, 102, 103, {{}})}}) - .IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE(TransformationMergeFunctionReturns( + 20, 100, 200, 101, 0, 0, + {{MakeReturnMergingInfo(23, 102, 103, {{}})}}) + .IsApplicable(context.get(), transformation_context)); std::string after_transformation = R"( OpCapability Shader @@ -1731,8 +1773,8 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules4) { %8 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %6 %9 %100 + OpLoopMerge %101 %200 None + OpBranch %9 %9 = OpLabel OpLoopMerge %10 %11 None OpBranch %12 @@ -1759,6 +1801,8 @@ TEST(TransformationMergeFunctionReturnsTest, RespectDominanceRules4) { OpBranch %101 %101 = OpLabel OpReturn + %200 = OpLabel + OpBranch %100 OpFunctionEnd %20 = OpFunction %3 None %4 %21 = OpLabel @@ -1830,7 +1874,7 @@ TEST(TransformationMergeFunctionReturnsTest, OpPhiAfterFirstBlock) { MakeUnique(context.get()), validator_options); auto transformation = - TransformationMergeFunctionReturns(2, 100, 101, 0, 0, {}); + TransformationMergeFunctionReturns(2, 100, 200, 101, 0, 0, {}); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); @@ -1863,8 +1907,8 @@ TEST(TransformationMergeFunctionReturnsTest, OpPhiAfterFirstBlock) { %8 = OpLabel OpBranch %100 %100 = OpLabel - OpLoopMerge %101 %100 None - OpBranchConditional %6 %9 %100 + OpLoopMerge %101 %200 None + OpBranch %9 %9 = OpLabel %10 = OpPhi %5 %6 %100 OpSelectionMerge %11 None @@ -1875,6 +1919,8 @@ TEST(TransformationMergeFunctionReturnsTest, OpPhiAfterFirstBlock) { OpBranch %101 %101 = OpLabel OpReturn + %200 = OpLabel + OpBranch %100 OpFunctionEnd )"; diff --git a/third_party/spirv-tools/test/fuzz/transformation_outline_function_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_outline_function_test.cpp index 6c0bff4b51..cc62049d23 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_outline_function_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_outline_function_test.cpp @@ -2531,98 +2531,6 @@ TEST(TransformationOutlineFunctionTest, ExitBlockHeadsLoop) { ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); } -TEST(TransformationOutlineFunctionTest, SkipVoidOutputId) { - std::string shader = R"( - OpCapability Shader - %1 = OpExtInstImport "GLSL.std.450" - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %6 "main" - OpExecutionMode %6 OriginUpperLeft - OpSource ESSL 310 - %2 = OpTypeVoid - %3 = OpTypeFunction %2 - %21 = OpTypeBool - %81 = OpConstantTrue %21 - %6 = OpFunction %2 None %3 - %7 = OpLabel - OpBranch %80 - %80 = OpLabel - %84 = OpFunctionCall %2 %87 - OpBranch %90 - %90 = OpLabel - %86 = OpPhi %2 %84 %80 - OpReturn - OpFunctionEnd - %87 = OpFunction %2 None %3 - %88 = OpLabel - OpReturn - OpFunctionEnd - )"; - - const auto env = SPV_ENV_UNIVERSAL_1_5; - const auto consumer = nullptr; - const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); - spvtools::ValidatorOptions validator_options; - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); - TransformationContext transformation_context( - MakeUnique(context.get()), validator_options); - TransformationOutlineFunction transformation( - /*entry_block*/ 80, - /*exit_block*/ 80, - /*new_function_struct_return_type_id*/ 300, - /*new_function_type_id*/ 301, - /*new_function_id*/ 302, - /*new_function_region_entry_block*/ 304, - /*new_caller_result_id*/ 305, - /*new_callee_result_id*/ 306, - /*input_id_to_fresh_id*/ {}, - /*output_id_to_fresh_id*/ {{84, 307}}); - - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); - - std::string after_transformation = R"( - OpCapability Shader - %1 = OpExtInstImport "GLSL.std.450" - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %6 "main" - OpExecutionMode %6 OriginUpperLeft - OpSource ESSL 310 - %2 = OpTypeVoid - %3 = OpTypeFunction %2 - %21 = OpTypeBool - %81 = OpConstantTrue %21 - %300 = OpTypeStruct - %301 = OpTypeFunction %300 - %6 = OpFunction %2 None %3 - %7 = OpLabel - OpBranch %80 - %80 = OpLabel - %305 = OpFunctionCall %300 %302 - %84 = OpUndef %2 - OpBranch %90 - %90 = OpLabel - %86 = OpPhi %2 %84 %80 - OpReturn - OpFunctionEnd - %87 = OpFunction %2 None %3 - %88 = OpLabel - OpReturn - OpFunctionEnd - %302 = OpFunction %300 None %301 - %304 = OpLabel - %307 = OpFunctionCall %2 %87 - %306 = OpCompositeConstruct %300 - OpReturnValue %306 - OpFunctionEnd - )"; - ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); -} - TEST(TransformationOutlineFunctionTest, Miscellaneous1) { // This tests outlining of some non-trivial code, and also tests the way // overflow ids are used by the transformation. @@ -3299,6 +3207,45 @@ TEST(TransformationOutlineFunctionTest, Miscellaneous4) { ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); } +TEST(TransformationOutlineFunctionTest, NoOutlineWithUnreachableBlocks) { + // This checks that outlining will not be performed if a node in the region + // has an unreachable predecessor. + + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %4 = OpFunction %2 None %3 + %7 = OpLabel + OpBranch %5 + %5 = OpLabel + OpReturn + %6 = OpLabel + OpBranch %5 + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + TransformationOutlineFunction transformation(5, 5, /* not relevant */ 200, + 100, 101, 102, 103, + /* not relevant */ 201, {}, {}); + ASSERT_FALSE( + transformation.IsApplicable(context.get(), transformation_context)); +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_permute_phi_operands_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_permute_phi_operands_test.cpp index 2843cfc555..0774dcf3d0 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_permute_phi_operands_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_permute_phi_operands_test.cpp @@ -60,6 +60,7 @@ TEST(TransformationPermutePhiOperandsTest, BasicTest) { OpBranch %17 %17 = OpLabel %25 = OpPhi %6 %20 %16 %24 %21 + %30 = OpIAdd %6 %25 %25 OpStore %8 %25 OpReturn OpFunctionEnd @@ -105,6 +106,47 @@ TEST(TransformationPermutePhiOperandsTest, BasicTest) { transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + // Check that the def-use manager knows that the phi instruction's ids have + // been permuted. + std::vector> phi_operand_to_new_operand_index = + {{20, 4}, {16, 5}, {24, 2}, {21, 3}}; + for (std::pair& entry : + phi_operand_to_new_operand_index) { + context->get_def_use_mgr()->WhileEachUse( + entry.first, + [&entry](opt::Instruction* inst, uint32_t operand_index) -> bool { + if (inst->result_id() == 25) { + EXPECT_EQ(entry.second, operand_index); + return false; + } + return true; + }); + } + bool found_use_in_store = false; + bool found_use_in_add_lhs = false; + bool found_use_in_add_rhs = false; + context->get_def_use_mgr()->ForEachUse( + 25, [&found_use_in_store, &found_use_in_add_lhs, &found_use_in_add_rhs]( + opt::Instruction* inst, uint32_t operand_index) { + if (inst->opcode() == SpvOpStore) { + ASSERT_FALSE(found_use_in_store); + found_use_in_store = true; + } else { + ASSERT_EQ(SpvOpIAdd, inst->opcode()); + if (operand_index == 2) { + ASSERT_FALSE(found_use_in_add_lhs); + found_use_in_add_lhs = true; + } else { + ASSERT_EQ(3, operand_index); + ASSERT_FALSE(found_use_in_add_rhs); + found_use_in_add_rhs = true; + } + } + }); + ASSERT_TRUE(found_use_in_store); + ASSERT_TRUE(found_use_in_add_lhs); + ASSERT_TRUE(found_use_in_add_rhs); + std::string after_transformation = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" @@ -142,6 +184,7 @@ TEST(TransformationPermutePhiOperandsTest, BasicTest) { OpBranch %17 %17 = OpLabel %25 = OpPhi %6 %24 %21 %20 %16 + %30 = OpIAdd %6 %25 %25 OpStore %8 %25 OpReturn OpFunctionEnd diff --git a/third_party/spirv-tools/test/fuzz/transformation_push_id_through_variable_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_push_id_through_variable_test.cpp index cd45c4ce93..7487cab9df 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_push_id_through_variable_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_push_id_through_variable_test.cpp @@ -341,7 +341,26 @@ TEST(TransformationPushIdThroughVariableTest, Apply) { auto transformation = TransformationPushIdThroughVariable( value_id, value_synonym_id, variable_id, variable_storage_class, initializer_id, instruction_descriptor); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(value_synonym_id)); + ASSERT_EQ(nullptr, context->get_instr_block(value_synonym_id)); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(variable_id)); + ASSERT_EQ(nullptr, context->get_instr_block(variable_id)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpLoad, + context->get_def_use_mgr()->GetDef(value_synonym_id)->opcode()); + ASSERT_EQ(36, context->get_instr_block(value_synonym_id)->id()); + ASSERT_EQ(SpvOpVariable, + context->get_def_use_mgr()->GetDef(variable_id)->opcode()); + ASSERT_EQ(5, context->get_instr_block(variable_id)->id()); + uint32_t variable_use_count = 0; + context->get_def_use_mgr()->ForEachUse( + variable_id, + [&variable_use_count](opt::Instruction* inst, uint32_t /*unused*/) { + ASSERT_TRUE(inst->opcode() == SpvOpLoad || + inst->opcode() == SpvOpStore); + variable_use_count++; + }); + ASSERT_EQ(2, variable_use_count); value_id = 21; value_synonym_id = 102; diff --git a/third_party/spirv-tools/test/fuzz/transformation_replace_branch_from_dead_block_with_exit_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_replace_branch_from_dead_block_with_exit_test.cpp index 45325038c5..6bba14f637 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_replace_branch_from_dead_block_with_exit_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_replace_branch_from_dead_block_with_exit_test.cpp @@ -566,6 +566,302 @@ TEST(TransformationReplaceBranchFromDeadBlockWithExitTest, OpPhi) { ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); } +TEST(TransformationReplaceBranchFromDeadBlockWithExitTest, + DominatorAfterDeadBlockSuccessor) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantFalse %6 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpBranchConditional %7 %9 %10 + %9 = OpLabel + OpBranch %11 + %11 = OpLabel + %12 = OpCopyObject %6 %7 + OpBranch %8 + %10 = OpLabel + OpBranch %13 + %8 = OpLabel + OpReturn + %13 = OpLabel + OpBranch %8 + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + transformation_context.GetFactManager()->AddFactBlockIsDead(9); + transformation_context.GetFactManager()->AddFactBlockIsDead(11); + + ASSERT_FALSE( + TransformationReplaceBranchFromDeadBlockWithExit(11, SpvOpUnreachable, 0) + .IsApplicable(context.get(), transformation_context)); +} + +TEST(TransformationReplaceBranchFromDeadBlockWithExitTest, + UnreachableSuccessor) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantFalse %6 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpBranchConditional %7 %9 %10 + %9 = OpLabel + OpBranch %11 + %11 = OpLabel + %12 = OpCopyObject %6 %7 + OpBranch %8 + %10 = OpLabel + OpReturn + %8 = OpLabel + OpReturn + %13 = OpLabel + OpBranch %8 + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + transformation_context.GetFactManager()->AddFactBlockIsDead(9); + transformation_context.GetFactManager()->AddFactBlockIsDead(11); + + TransformationReplaceBranchFromDeadBlockWithExit transformation( + 11, SpvOpUnreachable, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + transformation.Apply(context.get(), &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantFalse %6 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpBranchConditional %7 %9 %10 + %9 = OpLabel + OpBranch %11 + %11 = OpLabel + %12 = OpCopyObject %6 %7 + OpUnreachable + %10 = OpLabel + OpReturn + %8 = OpLabel + OpReturn + %13 = OpLabel + OpBranch %8 + OpFunctionEnd + )"; + + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); +} + +TEST(TransformationReplaceBranchFromDeadBlockWithExitTest, + DeadBlockAfterItsSuccessor) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantTrue %6 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpBranchConditional %7 %9 %10 + %9 = OpLabel + OpBranch %11 + %11 = OpLabel + %12 = OpCopyObject %6 %7 + OpBranch %8 + %10 = OpLabel + OpBranch %13 + %8 = OpLabel + OpReturn + %13 = OpLabel + OpBranch %8 + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + transformation_context.GetFactManager()->AddFactBlockIsDead(10); + transformation_context.GetFactManager()->AddFactBlockIsDead(13); + + TransformationReplaceBranchFromDeadBlockWithExit transformation( + 13, SpvOpUnreachable, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + transformation.Apply(context.get(), &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantTrue %6 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpBranchConditional %7 %9 %10 + %9 = OpLabel + OpBranch %11 + %11 = OpLabel + %12 = OpCopyObject %6 %7 + OpBranch %8 + %10 = OpLabel + OpBranch %13 + %8 = OpLabel + OpReturn + %13 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); +} + +TEST(TransformationReplaceBranchFromDeadBlockWithExitTest, + BranchToOuterMergeBlock) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantTrue %6 + %15 = OpTypeInt 32 0 + %14 = OpUndef %15 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpSwitch %14 %9 1 %8 + %9 = OpLabel + OpSelectionMerge %10 None + OpBranchConditional %7 %11 %10 + %8 = OpLabel + OpReturn + %11 = OpLabel + OpBranch %8 + %10 = OpLabel + OpBranch %8 + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_4; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + transformation_context.GetFactManager()->AddFactBlockIsDead(10); + + TransformationReplaceBranchFromDeadBlockWithExit transformation( + 10, SpvOpUnreachable, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + transformation.Apply(context.get(), &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeBool + %7 = OpConstantTrue %6 + %15 = OpTypeInt 32 0 + %14 = OpUndef %15 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %8 None + OpSwitch %14 %9 1 %8 + %9 = OpLabel + OpSelectionMerge %10 None + OpBranchConditional %7 %11 %10 + %8 = OpLabel + OpReturn + %11 = OpLabel + OpBranch %8 + %10 = OpLabel + OpUnreachable + OpFunctionEnd + )"; + + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_replace_id_with_synonym_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_replace_id_with_synonym_test.cpp index 5c10fc59a6..c0739c3bae 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_replace_id_with_synonym_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_replace_id_with_synonym_test.cpp @@ -303,10 +303,18 @@ TEST(TransformationReplaceIdWithSynonymTest, LegalTransformations) { auto global_constant_synonym = TransformationReplaceIdWithSynonym( MakeIdUseDescriptor(19, MakeInstructionDescriptor(47, SpvOpStore, 0), 1), 210); + uint32_t num_uses_of_original_id_before_replacement = + context->get_def_use_mgr()->NumUses(19); + uint32_t num_uses_of_synonym_before_replacement = + context->get_def_use_mgr()->NumUses(210); ASSERT_TRUE(global_constant_synonym.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(global_constant_synonym, context.get(), &transformation_context); + ASSERT_EQ(num_uses_of_original_id_before_replacement - 1, + context->get_def_use_mgr()->NumUses(19)); + ASSERT_EQ(num_uses_of_synonym_before_replacement + 1, + context->get_def_use_mgr()->NumUses(210)); ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, kConsoleMessageConsumer)); @@ -1788,6 +1796,300 @@ TEST(TransformationReplaceIdWithSynonymTest, IncompatibleTypes) { .IsApplicable(context.get(), transformation_context)); } +// TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/4346): This test +// should be updated to cover more atomic operations, and once the issue is +// fixed the test should be enabled. +TEST(TransformationReplaceIdWithSynonymTest, + DISABLED_AtomicScopeAndMemorySemanticsMustBeConstant) { + // The following SPIR-V came from this GLSL, edited to add some synonyms: + // + // #version 320 es + // + // #extension GL_KHR_memory_scope_semantics : enable + // + // layout(set = 0, binding = 0) buffer Buf { + // int x; + // }; + // + // void main() { + // int tmp = atomicLoad(x, + // gl_ScopeWorkgroup, + // gl_StorageSemanticsBuffer, + // gl_SemanticsRelaxed); + // } + const std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %4 "main" + OpExecutionMode %4 LocalSize 1 1 1 + OpSource ESSL 320 + OpSourceExtension "GL_KHR_memory_scope_semantics" + OpMemberDecorate %9 0 Offset 0 + OpDecorate %9 Block + OpDecorate %11 DescriptorSet 0 + OpDecorate %11 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpTypeStruct %6 + %10 = OpTypePointer StorageBuffer %9 + %11 = OpVariable %10 StorageBuffer + %12 = OpConstant %6 0 + %13 = OpTypePointer StorageBuffer %6 + %15 = OpConstant %6 2 + %16 = OpConstant %6 64 + %17 = OpTypeInt 32 0 + %18 = OpConstant %17 1 + %19 = OpConstant %17 0 + %20 = OpConstant %17 64 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %100 = OpCopyObject %6 %15 ; A non-constant version of %15 + %101 = OpCopyObject %17 %20 ; A non-constant version of %20 + %14 = OpAccessChain %13 %11 %12 + %21 = OpAtomicLoad %6 %14 %15 %20 + OpStore %8 %21 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + // Tell the fact manager that %100 and %15 are synonymous + transformation_context.GetFactManager()->AddFactDataSynonym( + MakeDataDescriptor(100, {}), MakeDataDescriptor(15, {})); + + // Tell the fact manager that %101 and %20 are synonymous + transformation_context.GetFactManager()->AddFactDataSynonym( + MakeDataDescriptor(101, {}), MakeDataDescriptor(20, {})); + + const auto& scope_operand = MakeIdUseDescriptorFromUse( + context.get(), context->get_def_use_mgr()->GetDef(21), 1); + ASSERT_FALSE(TransformationReplaceIdWithSynonym(scope_operand, 100) + .IsApplicable(context.get(), transformation_context)); + + const auto& semantics_operand = MakeIdUseDescriptorFromUse( + context.get(), context->get_def_use_mgr()->GetDef(21), 2); + ASSERT_FALSE(TransformationReplaceIdWithSynonym(semantics_operand, 101) + .IsApplicable(context.get(), transformation_context)); +} + +// TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/4345): Improve this +// test so that it covers more atomic operations, and enable the test once the +// issue is fixed. +TEST(TransformationReplaceIdWithSynonymTest, + DISABLED_SignOfAtomicScopeAndMemorySemanticsDoesNotMatter) { + // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/4345): both the + // GLSL comment and the corresponding SPIR-V should be updated to cover a + // larger number of atomic operations. + // The following SPIR-V came from this GLSL, edited to add some synonyms: + // + // #version 320 es + // + // #extension GL_KHR_memory_scope_semantics : enable + // + // layout(set = 0, binding = 0) buffer Buf { + // int x; + // }; + // + // void main() { + // int tmp = atomicLoad(x, + // gl_ScopeWorkgroup, + // gl_StorageSemanticsBuffer, + // gl_SemanticsRelaxed); + // } + const std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %4 "main" + OpExecutionMode %4 LocalSize 1 1 1 + OpSource ESSL 320 + OpSourceExtension "GL_KHR_memory_scope_semantics" + OpMemberDecorate %9 0 Offset 0 + OpDecorate %9 Block + OpDecorate %11 DescriptorSet 0 + OpDecorate %11 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpTypeStruct %6 + %10 = OpTypePointer StorageBuffer %9 + %11 = OpVariable %10 StorageBuffer + %12 = OpConstant %6 0 + %13 = OpTypePointer StorageBuffer %6 + %15 = OpConstant %6 2 + %16 = OpConstant %6 64 + %17 = OpTypeInt 32 0 + %100 = OpConstant %17 2 ; The same as %15, but with unsigned int type + %18 = OpConstant %17 1 + %19 = OpConstant %17 0 + %20 = OpConstant %17 64 + %101 = OpConstant %6 64 ; The same as %20, but with signed int type + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %14 = OpAccessChain %13 %11 %12 + %21 = OpAtomicLoad %6 %14 %15 %20 + OpStore %8 %21 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + // Tell the fact manager that %100 and %15 are synonymous + transformation_context.GetFactManager()->AddFactDataSynonym( + MakeDataDescriptor(100, {}), MakeDataDescriptor(15, {})); + + // Tell the fact manager that %101 and %20 are synonymous + transformation_context.GetFactManager()->AddFactDataSynonym( + MakeDataDescriptor(101, {}), MakeDataDescriptor(20, {})); + + { + const auto& scope_operand = MakeIdUseDescriptorFromUse( + context.get(), context->get_def_use_mgr()->GetDef(21), 1); + TransformationReplaceIdWithSynonym replace_scope(scope_operand, 100); + ASSERT_TRUE( + replace_scope.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(replace_scope, context.get(), + &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + } + + { + const auto& semantics_operand = MakeIdUseDescriptorFromUse( + context.get(), context->get_def_use_mgr()->GetDef(21), 2); + TransformationReplaceIdWithSynonym replace_semantics(semantics_operand, + 101); + ASSERT_TRUE( + replace_semantics.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(replace_semantics, context.get(), + &transformation_context); + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + } + + const std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %4 "main" + OpExecutionMode %4 LocalSize 1 1 1 + OpSource ESSL 320 + OpSourceExtension "GL_KHR_memory_scope_semantics" + OpMemberDecorate %9 0 Offset 0 + OpDecorate %9 Block + OpDecorate %11 DescriptorSet 0 + OpDecorate %11 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpTypeStruct %6 + %10 = OpTypePointer StorageBuffer %9 + %11 = OpVariable %10 StorageBuffer + %12 = OpConstant %6 0 + %13 = OpTypePointer StorageBuffer %6 + %15 = OpConstant %6 2 + %16 = OpConstant %6 64 + %17 = OpTypeInt 32 0 + %100 = OpConstant %17 2 + %18 = OpConstant %17 1 + %19 = OpConstant %17 0 + %20 = OpConstant %17 64 + %101 = OpConstant %6 64 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + %14 = OpAccessChain %13 %11 %12 + %21 = OpAtomicLoad %6 %14 %100 %101 + OpStore %8 %21 + OpReturn + OpFunctionEnd + )"; + + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); +} + +// TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/4345): Improve this +// test so that it covers more atomic operations, and enable the test once the +// issue is fixed. +TEST(TransformationReplaceIdWithSynonymTest, DISABLED_TypesAreCompatible) { + const std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %9 = OpTypeInt 32 0 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + const uint32_t int_type = 6; // The id of OpTypeInt 32 1 + const uint32_t uint_type = 9; // The id of OpTypeInt 32 0 + + // OpAtomicLoad +#ifndef NDEBUG + ASSERT_DEATH(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicLoad, 0, int_type, uint_type), + "Invalid operand index"); +#endif + ASSERT_TRUE(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicLoad, 1, int_type, uint_type)); + ASSERT_TRUE(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicLoad, 2, int_type, uint_type)); + + // OpAtomicExchange +#ifndef NDEBUG + ASSERT_DEATH(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicExchange, 0, int_type, uint_type), + "Invalid operand index"); +#endif + ASSERT_TRUE(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicExchange, 1, int_type, uint_type)); + ASSERT_TRUE(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicExchange, 2, int_type, uint_type)); + ASSERT_FALSE(TransformationReplaceIdWithSynonym::TypesAreCompatible( + context.get(), SpvOpAtomicExchange, 2, int_type, uint_type)); + + // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/4345): Similar for + // other atomic instructions +} + } // namespace } // namespace fuzz } // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_set_loop_control_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_set_loop_control_test.cpp index 3312a6792d..88b4aab580 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_set_loop_control_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_set_loop_control_test.cpp @@ -947,7 +947,9 @@ TEST(TransformationSetLoopControlTest, CheckSPIRVVersionsRespected) { for (auto env : {SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1, SPV_ENV_UNIVERSAL_1_2, - SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_4, SPV_ENV_UNIVERSAL_1_5}) { + SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_4, SPV_ENV_UNIVERSAL_1_5, + SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1, SPV_ENV_VULKAN_1_1_SPIRV_1_4, + SPV_ENV_VULKAN_1_2}) { const auto consumer = nullptr; const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); @@ -956,23 +958,33 @@ TEST(TransformationSetLoopControlTest, CheckSPIRVVersionsRespected) { context.get(), validator_options, kConsoleMessageConsumer)); TransformationContext transformation_context( MakeUnique(context.get()), validator_options); - TransformationSetLoopControl transformation( - 10, SpvLoopControlPeelCountMask | SpvLoopControlPartialCountMask, 4, 4); + TransformationSetLoopControl peel_count(10, SpvLoopControlPeelCountMask, 4, + 0); + TransformationSetLoopControl partial_count( + 10, SpvLoopControlPartialCountMask, 0, 4); switch (env) { case SPV_ENV_UNIVERSAL_1_0: case SPV_ENV_UNIVERSAL_1_1: case SPV_ENV_UNIVERSAL_1_2: case SPV_ENV_UNIVERSAL_1_3: + case SPV_ENV_VULKAN_1_0: + case SPV_ENV_VULKAN_1_1: // PeelCount and PartialCount were introduced in SPIRV 1.4, so are not // valid in the context of older versions. ASSERT_FALSE( - transformation.IsApplicable(context.get(), transformation_context)); + peel_count.IsApplicable(context.get(), transformation_context)); + ASSERT_FALSE( + partial_count.IsApplicable(context.get(), transformation_context)); break; case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_UNIVERSAL_1_5: + case SPV_ENV_VULKAN_1_1_SPIRV_1_4: + case SPV_ENV_VULKAN_1_2: ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); + peel_count.IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + partial_count.IsApplicable(context.get(), transformation_context)); break; default: assert(false && "Unhandled environment"); diff --git a/third_party/spirv-tools/test/fuzz/transformation_set_memory_operands_mask_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_set_memory_operands_mask_test.cpp index 4763d7ad80..29e57f42ea 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_set_memory_operands_mask_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_set_memory_operands_mask_test.cpp @@ -90,187 +90,205 @@ TEST(TransformationSetMemoryOperandsMaskTest, PreSpirv14) { OpFunctionEnd )"; - const auto env = SPV_ENV_UNIVERSAL_1_3; - const auto consumer = nullptr; - const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); - spvtools::ValidatorOptions validator_options; - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); - TransformationContext transformation_context( - MakeUnique(context.get()), validator_options); - // Not OK: the instruction is not a memory access. - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpAccessChain, 0), - SpvMemoryAccessMaskNone, 0) - .IsApplicable(context.get(), transformation_context)); + for (auto env : + {SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1, SPV_ENV_UNIVERSAL_1_2, + SPV_ENV_UNIVERSAL_1_3, SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1}) { + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); - // Not OK to remove Aligned - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(147, SpvOpLoad, 0), - SpvMemoryAccessVolatileMask | SpvMemoryAccessNontemporalMask, - 0) - .IsApplicable(context.get(), transformation_context)); +#ifndef NDEBUG + { + // Not OK: multiple operands are not supported pre SPIR-V 1.4. + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 3), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 1); + ASSERT_DEATH( + transformation.IsApplicable(context.get(), transformation_context), + "Multiple memory operand masks are not supported"); + } +#endif - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(147, SpvOpLoad, 0), - SpvMemoryAccessAlignedMask | SpvMemoryAccessVolatileMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); + // Not OK: the instruction is not a memory access. + ASSERT_FALSE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpAccessChain, 0), + SpvMemoryAccessMaskNone, 0) + .IsApplicable(context.get(), transformation_context)); + + // Not OK to remove Aligned + ASSERT_FALSE( + TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(147, SpvOpLoad, 0), + SpvMemoryAccessVolatileMask | SpvMemoryAccessNontemporalMask, 0) + .IsApplicable(context.get(), transformation_context)); + + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(147, SpvOpLoad, 0), + SpvMemoryAccessAlignedMask | SpvMemoryAccessVolatileMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + + // Not OK to remove Aligned + ASSERT_FALSE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), + SpvMemoryAccessMaskNone, 0) + .IsApplicable(context.get(), transformation_context)); + + // OK: leaves the mask as is + ASSERT_TRUE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), + SpvMemoryAccessAlignedMask, 0) + .IsApplicable(context.get(), transformation_context)); + + { + // OK: adds Nontemporal and Volatile + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), + SpvMemoryAccessAlignedMask | SpvMemoryAccessNontemporalMask | + SpvMemoryAccessVolatileMask, + 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + + // Not OK to remove Volatile + ASSERT_FALSE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), + SpvMemoryAccessNontemporalMask, 0) + .IsApplicable(context.get(), transformation_context)); + + // Not OK to add Aligned + ASSERT_FALSE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), + SpvMemoryAccessAlignedMask | SpvMemoryAccessVolatileMask, + 0) + .IsApplicable(context.get(), transformation_context)); + + { + // OK: adds Nontemporal + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + + { + // OK: adds Nontemporal (creates new operand) + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 2), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + + { + // OK: adds Nontemporal and Volatile + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(138, SpvOpCopyMemory, 0), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + + { + // OK: removes Nontemporal, adds Volatile + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(148, SpvOpStore, 0), + SpvMemoryAccessVolatileMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } + + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %7 "Point3D" + OpMemberName %7 0 "x" + OpMemberName %7 1 "y" + OpMemberName %7 2 "z" + OpName %12 "global_points" + OpName %15 "block" + OpMemberName %15 0 "in_points" + OpMemberName %15 1 "in_point" + OpName %17 "" + OpName %133 "local_points" + OpMemberDecorate %7 0 Offset 0 + OpMemberDecorate %7 1 Offset 4 + OpMemberDecorate %7 2 Offset 8 + OpDecorate %10 ArrayStride 16 + OpMemberDecorate %15 0 Offset 0 + OpMemberDecorate %15 1 Offset 192 + OpDecorate %15 Block + OpDecorate %17 DescriptorSet 0 + OpDecorate %17 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeStruct %6 %6 %6 + %8 = OpTypeInt 32 0 + %9 = OpConstant %8 12 + %10 = OpTypeArray %7 %9 + %11 = OpTypePointer Private %10 + %12 = OpVariable %11 Private + %15 = OpTypeStruct %10 %7 + %16 = OpTypePointer Uniform %15 + %17 = OpVariable %16 Uniform + %18 = OpTypeInt 32 1 + %19 = OpConstant %18 0 + %20 = OpTypePointer Uniform %10 + %24 = OpTypePointer Private %7 + %27 = OpTypePointer Private %6 + %30 = OpConstant %18 1 + %132 = OpTypePointer Function %10 + %135 = OpTypePointer Uniform %7 + %145 = OpTypePointer Function %7 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %133 = OpVariable %132 Function + %21 = OpAccessChain %20 %17 %19 + OpCopyMemory %12 %21 Aligned|Nontemporal|Volatile 16 + OpCopyMemory %133 %12 Nontemporal|Volatile + OpCopyMemory %133 %12 Nontemporal|Volatile + %136 = OpAccessChain %135 %17 %30 + %138 = OpAccessChain %24 %12 %19 + OpCopyMemory %138 %136 Nontemporal|Volatile + %146 = OpAccessChain %145 %133 %30 + %147 = OpLoad %7 %146 Aligned|Volatile 16 + %148 = OpAccessChain %24 %12 %19 + OpStore %148 %147 Volatile + OpReturn + OpFunctionEnd + )"; + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); } - - // Not OK to remove Aligned - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), - SpvMemoryAccessMaskNone, 0) - .IsApplicable(context.get(), transformation_context)); - - // OK: leaves the mask as is - ASSERT_TRUE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), - SpvMemoryAccessAlignedMask, 0) - .IsApplicable(context.get(), transformation_context)); - - { - // OK: adds Nontemporal and Volatile - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), - SpvMemoryAccessAlignedMask | SpvMemoryAccessNontemporalMask | - SpvMemoryAccessVolatileMask, - 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } - - // Not OK to remove Volatile - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), - SpvMemoryAccessNontemporalMask, 0) - .IsApplicable(context.get(), transformation_context)); - - // Not OK to add Aligned - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), - SpvMemoryAccessAlignedMask | SpvMemoryAccessVolatileMask, 0) - .IsApplicable(context.get(), transformation_context)); - - { - // OK: adds Nontemporal - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), - SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } - - { - // OK: adds Nontemporal (creates new operand) - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 2), - SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } - - { - // OK: adds Nontemporal and Volatile - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(138, SpvOpCopyMemory, 0), - SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } - - { - // OK: removes Nontemporal, adds Volatile - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(148, SpvOpStore, 0), - SpvMemoryAccessVolatileMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } - - std::string after_transformation = R"( - OpCapability Shader - %1 = OpExtInstImport "GLSL.std.450" - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %4 "main" - OpExecutionMode %4 OriginUpperLeft - OpSource ESSL 310 - OpName %4 "main" - OpName %7 "Point3D" - OpMemberName %7 0 "x" - OpMemberName %7 1 "y" - OpMemberName %7 2 "z" - OpName %12 "global_points" - OpName %15 "block" - OpMemberName %15 0 "in_points" - OpMemberName %15 1 "in_point" - OpName %17 "" - OpName %133 "local_points" - OpMemberDecorate %7 0 Offset 0 - OpMemberDecorate %7 1 Offset 4 - OpMemberDecorate %7 2 Offset 8 - OpDecorate %10 ArrayStride 16 - OpMemberDecorate %15 0 Offset 0 - OpMemberDecorate %15 1 Offset 192 - OpDecorate %15 Block - OpDecorate %17 DescriptorSet 0 - OpDecorate %17 Binding 0 - %2 = OpTypeVoid - %3 = OpTypeFunction %2 - %6 = OpTypeFloat 32 - %7 = OpTypeStruct %6 %6 %6 - %8 = OpTypeInt 32 0 - %9 = OpConstant %8 12 - %10 = OpTypeArray %7 %9 - %11 = OpTypePointer Private %10 - %12 = OpVariable %11 Private - %15 = OpTypeStruct %10 %7 - %16 = OpTypePointer Uniform %15 - %17 = OpVariable %16 Uniform - %18 = OpTypeInt 32 1 - %19 = OpConstant %18 0 - %20 = OpTypePointer Uniform %10 - %24 = OpTypePointer Private %7 - %27 = OpTypePointer Private %6 - %30 = OpConstant %18 1 - %132 = OpTypePointer Function %10 - %135 = OpTypePointer Uniform %7 - %145 = OpTypePointer Function %7 - %4 = OpFunction %2 None %3 - %5 = OpLabel - %133 = OpVariable %132 Function - %21 = OpAccessChain %20 %17 %19 - OpCopyMemory %12 %21 Aligned|Nontemporal|Volatile 16 - OpCopyMemory %133 %12 Nontemporal|Volatile - OpCopyMemory %133 %12 Nontemporal|Volatile - %136 = OpAccessChain %135 %17 %30 - %138 = OpAccessChain %24 %12 %19 - OpCopyMemory %138 %136 Nontemporal|Volatile - %146 = OpAccessChain %145 %133 %30 - %147 = OpLoad %7 %146 Aligned|Volatile 16 - %148 = OpAccessChain %24 %12 %19 - OpStore %148 %147 Volatile - OpReturn - OpFunctionEnd - )"; - ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); } -TEST(TransformationSetMemoryOperandsMaskTest, Spirv14) { +TEST(TransformationSetMemoryOperandsMaskTest, Spirv14OrHigher) { std::string shader = R"( OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" @@ -339,180 +357,183 @@ TEST(TransformationSetMemoryOperandsMaskTest, Spirv14) { OpFunctionEnd )"; - const auto env = SPV_ENV_UNIVERSAL_1_4; - const auto consumer = nullptr; - const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); - spvtools::ValidatorOptions validator_options; - ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, - kConsoleMessageConsumer)); - TransformationContext transformation_context( - MakeUnique(context.get()), validator_options); - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), - SpvMemoryAccessAlignedMask | SpvMemoryAccessVolatileMask, 1); - // Bad: cannot remove aligned - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), - SpvMemoryAccessVolatileMask, 1) - .IsApplicable(context.get(), transformation_context)); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + for (auto env : {SPV_ENV_UNIVERSAL_1_4, SPV_ENV_UNIVERSAL_1_5, + SPV_ENV_VULKAN_1_1_SPIRV_1_4, SPV_ENV_VULKAN_1_2}) { + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), + SpvMemoryAccessAlignedMask | SpvMemoryAccessVolatileMask, 1); + // Bad: cannot remove aligned + ASSERT_FALSE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 0), + SpvMemoryAccessVolatileMask, 1) + .IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), - SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 1); - // Bad: cannot remove volatile - ASSERT_FALSE(TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), - SpvMemoryAccessNontemporalMask, 0) - .IsApplicable(context.get(), transformation_context)); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 1); + // Bad: cannot remove volatile + ASSERT_FALSE(TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 1), + SpvMemoryAccessNontemporalMask, 0) + .IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - // Creates the first operand. - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 2), - SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + // Creates the first operand. + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 2), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - // Creates both operands. - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(21, SpvOpCopyMemory, 3), - SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 1); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + // Creates both operands. + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(21, SpvOpCopyMemory, 3), + SpvMemoryAccessNontemporalMask | SpvMemoryAccessVolatileMask, 1); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(138, SpvOpCopyMemory, 0), - SpvMemoryAccessAlignedMask | SpvMemoryAccessNontemporalMask, 1); - // Bad: the first mask is None, so Aligned cannot be added to it. - ASSERT_FALSE( - TransformationSetMemoryOperandsMask( - MakeInstructionDescriptor(138, SpvOpCopyMemory, 0), - SpvMemoryAccessAlignedMask | SpvMemoryAccessNontemporalMask, 0) - .IsApplicable(context.get(), transformation_context)); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(138, SpvOpCopyMemory, 0), + SpvMemoryAccessAlignedMask | SpvMemoryAccessNontemporalMask, 1); + // Bad: the first mask is None, so Aligned cannot be added to it. + ASSERT_FALSE( + TransformationSetMemoryOperandsMask( + MakeInstructionDescriptor(138, SpvOpCopyMemory, 0), + SpvMemoryAccessAlignedMask | SpvMemoryAccessNontemporalMask, 0) + .IsApplicable(context.get(), transformation_context)); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(138, SpvOpCopyMemory, 1), - SpvMemoryAccessVolatileMask, 1); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(138, SpvOpCopyMemory, 1), + SpvMemoryAccessVolatileMask, 1); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(147, SpvOpLoad, 0), - SpvMemoryAccessVolatileMask | SpvMemoryAccessAlignedMask, 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(147, SpvOpLoad, 0), + SpvMemoryAccessVolatileMask | SpvMemoryAccessAlignedMask, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - { - TransformationSetMemoryOperandsMask transformation( - MakeInstructionDescriptor(148, SpvOpStore, 0), SpvMemoryAccessMaskNone, - 0); - ASSERT_TRUE( - transformation.IsApplicable(context.get(), transformation_context)); - ApplyAndCheckFreshIds(transformation, context.get(), - &transformation_context); - } + { + TransformationSetMemoryOperandsMask transformation( + MakeInstructionDescriptor(148, SpvOpStore, 0), + SpvMemoryAccessMaskNone, 0); + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + } - std::string after_transformation = R"( - OpCapability Shader - %1 = OpExtInstImport "GLSL.std.450" - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %4 "main" %12 %17 - OpExecutionMode %4 OriginUpperLeft - OpSource ESSL 310 - OpName %4 "main" - OpName %7 "Point3D" - OpMemberName %7 0 "x" - OpMemberName %7 1 "y" - OpMemberName %7 2 "z" - OpName %12 "global_points" - OpName %15 "block" - OpMemberName %15 0 "in_points" - OpMemberName %15 1 "in_point" - OpName %17 "" - OpName %133 "local_points" - OpMemberDecorate %7 0 Offset 0 - OpMemberDecorate %7 1 Offset 4 - OpMemberDecorate %7 2 Offset 8 - OpDecorate %10 ArrayStride 16 - OpMemberDecorate %15 0 Offset 0 - OpMemberDecorate %15 1 Offset 192 - OpDecorate %15 Block - OpDecorate %17 DescriptorSet 0 - OpDecorate %17 Binding 0 - %2 = OpTypeVoid - %3 = OpTypeFunction %2 - %6 = OpTypeFloat 32 - %7 = OpTypeStruct %6 %6 %6 - %8 = OpTypeInt 32 0 - %9 = OpConstant %8 12 - %10 = OpTypeArray %7 %9 - %11 = OpTypePointer Private %10 - %12 = OpVariable %11 Private - %15 = OpTypeStruct %10 %7 - %16 = OpTypePointer Uniform %15 - %17 = OpVariable %16 Uniform - %18 = OpTypeInt 32 1 - %19 = OpConstant %18 0 - %20 = OpTypePointer Uniform %10 - %24 = OpTypePointer Private %7 - %27 = OpTypePointer Private %6 - %30 = OpConstant %18 1 - %132 = OpTypePointer Function %10 - %135 = OpTypePointer Uniform %7 - %145 = OpTypePointer Function %7 - %4 = OpFunction %2 None %3 - %5 = OpLabel - %133 = OpVariable %132 Function - %21 = OpAccessChain %20 %17 %19 - OpCopyMemory %12 %21 Aligned 16 Aligned|Volatile 16 - OpCopyMemory %133 %12 Volatile Nontemporal|Volatile - OpCopyMemory %133 %12 Nontemporal|Volatile - OpCopyMemory %133 %12 None Nontemporal|Volatile - %136 = OpAccessChain %135 %17 %30 - %138 = OpAccessChain %24 %12 %19 - OpCopyMemory %138 %136 None Aligned|Nontemporal 16 - OpCopyMemory %138 %136 Aligned 16 Volatile - %146 = OpAccessChain %145 %133 %30 - %147 = OpLoad %7 %146 Volatile|Aligned 16 - %148 = OpAccessChain %24 %12 %19 - OpStore %148 %147 None - OpReturn - OpFunctionEnd - )"; - ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %12 %17 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %7 "Point3D" + OpMemberName %7 0 "x" + OpMemberName %7 1 "y" + OpMemberName %7 2 "z" + OpName %12 "global_points" + OpName %15 "block" + OpMemberName %15 0 "in_points" + OpMemberName %15 1 "in_point" + OpName %17 "" + OpName %133 "local_points" + OpMemberDecorate %7 0 Offset 0 + OpMemberDecorate %7 1 Offset 4 + OpMemberDecorate %7 2 Offset 8 + OpDecorate %10 ArrayStride 16 + OpMemberDecorate %15 0 Offset 0 + OpMemberDecorate %15 1 Offset 192 + OpDecorate %15 Block + OpDecorate %17 DescriptorSet 0 + OpDecorate %17 Binding 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypeStruct %6 %6 %6 + %8 = OpTypeInt 32 0 + %9 = OpConstant %8 12 + %10 = OpTypeArray %7 %9 + %11 = OpTypePointer Private %10 + %12 = OpVariable %11 Private + %15 = OpTypeStruct %10 %7 + %16 = OpTypePointer Uniform %15 + %17 = OpVariable %16 Uniform + %18 = OpTypeInt 32 1 + %19 = OpConstant %18 0 + %20 = OpTypePointer Uniform %10 + %24 = OpTypePointer Private %7 + %27 = OpTypePointer Private %6 + %30 = OpConstant %18 1 + %132 = OpTypePointer Function %10 + %135 = OpTypePointer Uniform %7 + %145 = OpTypePointer Function %7 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %133 = OpVariable %132 Function + %21 = OpAccessChain %20 %17 %19 + OpCopyMemory %12 %21 Aligned 16 Aligned|Volatile 16 + OpCopyMemory %133 %12 Volatile Nontemporal|Volatile + OpCopyMemory %133 %12 Nontemporal|Volatile + OpCopyMemory %133 %12 None Nontemporal|Volatile + %136 = OpAccessChain %135 %17 %30 + %138 = OpAccessChain %24 %12 %19 + OpCopyMemory %138 %136 None Aligned|Nontemporal 16 + OpCopyMemory %138 %136 Aligned 16 Volatile + %146 = OpAccessChain %145 %133 %30 + %147 = OpLoad %7 %146 Volatile|Aligned 16 + %148 = OpAccessChain %24 %12 %19 + OpStore %148 %147 None + OpReturn + OpFunctionEnd + )"; + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); + } } } // namespace diff --git a/third_party/spirv-tools/test/fuzz/transformation_swap_conditional_branch_operands_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_swap_conditional_branch_operands_test.cpp index e7a8732e63..6133a7a8e9 100644 --- a/third_party/spirv-tools/test/fuzz/transformation_swap_conditional_branch_operands_test.cpp +++ b/third_party/spirv-tools/test/fuzz/transformation_swap_conditional_branch_operands_test.cpp @@ -91,9 +91,31 @@ TEST(TransformationSwapConditionalBranchOperandsTest, BasicTest) { TransformationSwapConditionalBranchOperands transformation( MakeInstructionDescriptor(15, SpvOpBranchConditional, 0), 26); + ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(26)); + ASSERT_EQ(nullptr, context->get_instr_block(26)); ASSERT_TRUE( transformation.IsApplicable(context.get(), transformation_context)); ApplyAndCheckFreshIds(transformation, context.get(), &transformation_context); + ASSERT_EQ(SpvOpLogicalNot, context->get_def_use_mgr()->GetDef(26)->opcode()); + ASSERT_EQ(5, context->get_instr_block(26)->id()); + ASSERT_EQ(1, context->get_def_use_mgr()->NumUses(26)); + + // Check that the def-use manager knows that the conditional branch operands + // have been swapped. + std::vector> phi_operand_to_new_operand_index = + {{16, 2}, {21, 1}}; + for (std::pair& entry : + phi_operand_to_new_operand_index) { + context->get_def_use_mgr()->WhileEachUse( + entry.first, + [&entry](opt::Instruction* inst, uint32_t operand_index) -> bool { + if (inst->opcode() == SpvOpBranchConditional) { + EXPECT_EQ(entry.second, operand_index); + return false; + } + return true; + }); + } std::string after_transformation = R"( OpCapability Shader diff --git a/third_party/spirv-tools/test/fuzz/transformation_swap_function_variables_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_swap_function_variables_test.cpp new file mode 100644 index 0000000000..8132aa4b0f --- /dev/null +++ b/third_party/spirv-tools/test/fuzz/transformation_swap_function_variables_test.cpp @@ -0,0 +1,288 @@ +// Copyright (c) 2021 Mostafa Ashraf +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/transformation_swap_function_variables.h" + +#include "gtest/gtest.h" +#include "source/fuzz/fuzzer_util.h" +#include "source/fuzz/instruction_descriptor.h" +#include "test/fuzz/fuzz_test_util.h" + +namespace spvtools { +namespace fuzz { +namespace { + +TEST(TransformationSwapFunctionVariables, NotApplicable) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %8 = OpTypeFloat 32 + %9 = OpTypePointer Function %8 + %10 = OpTypeVector %8 2 + %11 = OpTypePointer Function %10 + %12 = OpTypeVector %8 3 + %13 = OpTypeMatrix %12 3 + %14 = OpTypePointer Function %13 + %15 = OpTypeFunction %2 %7 %9 %11 %14 %7 %7 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %24 = OpVariable %7 Function + %25 = OpVariable %9 Function + %26 = OpVariable %11 Function + %27 = OpVariable %14 Function + %28 = OpVariable %7 Function + %29 = OpVariable %7 Function + %30 = OpVariable %7 Function + %32 = OpVariable %9 Function + %34 = OpVariable %11 Function + %36 = OpVariable %14 Function + %38 = OpVariable %7 Function + %40 = OpVariable %7 Function + %31 = OpLoad %6 %24 + OpStore %30 %31 + %33 = OpLoad %8 %25 + OpStore %32 %33 + %35 = OpLoad %10 %26 + OpStore %34 %35 + %37 = OpLoad %13 %27 + OpStore %36 %37 + %39 = OpLoad %6 %28 + OpStore %38 %39 + %41 = OpLoad %6 %29 + OpStore %40 %41 + %42 = OpFunctionCall %2 %22 %30 %32 %34 %36 %38 %40 + OpReturn + OpFunctionEnd + %22 = OpFunction %2 None %15 + %16 = OpFunctionParameter %7 + %17 = OpFunctionParameter %9 + %18 = OpFunctionParameter %11 + %19 = OpFunctionParameter %14 + %20 = OpFunctionParameter %7 + %21 = OpFunctionParameter %7 + %23 = OpLabel + OpReturn + OpFunctionEnd +)"; + + const auto env = SPV_ENV_UNIVERSAL_1_5; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + +#ifndef NDEBUG + // Can't swap variable with itself. + ASSERT_DEATH(TransformationSwapFunctionVariables(7, 7).IsApplicable( + context.get(), transformation_context), + "Two results ids are equal"); +#endif + + // Invalid because 200 is not the id of an instruction. + ASSERT_FALSE(TransformationSwapFunctionVariables(1, 200).IsApplicable( + context.get(), transformation_context)); + // Invalid because 5 is not the id of an instruction. + ASSERT_FALSE(TransformationSwapFunctionVariables(5, 24).IsApplicable( + context.get(), transformation_context)); + // Can't swap two instructions from two different blocks. + ASSERT_FALSE(TransformationSwapFunctionVariables(16, 26).IsApplicable( + context.get(), transformation_context)); +} + +TEST(TransformationSwapFunctionVariables, IsApplicable) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %8 = OpTypeFloat 32 + %9 = OpTypePointer Function %8 + %10 = OpTypeVector %8 2 + %11 = OpTypePointer Function %10 + %12 = OpTypeVector %8 3 + %13 = OpTypeMatrix %12 3 + %14 = OpTypePointer Function %13 + %15 = OpTypeFunction %2 %7 %9 %11 %14 %7 %7 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %24 = OpVariable %7 Function + %25 = OpVariable %9 Function + %26 = OpVariable %11 Function + %27 = OpVariable %14 Function + %28 = OpVariable %7 Function + %29 = OpVariable %7 Function + %30 = OpVariable %7 Function + %32 = OpVariable %9 Function + %34 = OpVariable %11 Function + %36 = OpVariable %14 Function + %38 = OpVariable %7 Function + %40 = OpVariable %7 Function + %31 = OpLoad %6 %24 + OpStore %30 %31 + %33 = OpLoad %8 %25 + OpStore %32 %33 + %35 = OpLoad %10 %26 + OpStore %34 %35 + %37 = OpLoad %13 %27 + OpStore %36 %37 + %39 = OpLoad %6 %28 + OpStore %38 %39 + %41 = OpLoad %6 %29 + OpStore %40 %41 + %42 = OpFunctionCall %2 %22 %30 %32 %34 %36 %38 %40 + OpReturn + OpFunctionEnd + %22 = OpFunction %2 None %15 + %16 = OpFunctionParameter %7 + %17 = OpFunctionParameter %9 + %18 = OpFunctionParameter %11 + %19 = OpFunctionParameter %14 + %20 = OpFunctionParameter %7 + %21 = OpFunctionParameter %7 + %23 = OpLabel + OpReturn + OpFunctionEnd +)"; + + const auto env = SPV_ENV_UNIVERSAL_1_5; + const auto consumer = nullptr; + // Get Unique pointer of IRContext. + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + + // Successful transformations + { + auto first_instruction = context->get_def_use_mgr()->GetDef(24); + auto second_instruction = context->get_def_use_mgr()->GetDef(28); + // Swap two OpVariable instructions in the same function. + TransformationSwapFunctionVariables transformation(24, 28); + + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + + ASSERT_EQ(first_instruction, context->get_def_use_mgr()->GetDef(24)); + ASSERT_EQ(second_instruction, context->get_def_use_mgr()->GetDef(28)); + } + { + auto first_instruction = context->get_def_use_mgr()->GetDef(38); + auto second_instruction = context->get_def_use_mgr()->GetDef(40); + // Swap two OpVariable instructions in the same function. + TransformationSwapFunctionVariables transformation(38, 40); + + ASSERT_TRUE( + transformation.IsApplicable(context.get(), transformation_context)); + + ApplyAndCheckFreshIds(transformation, context.get(), + &transformation_context); + + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed( + context.get(), validator_options, kConsoleMessageConsumer)); + + ASSERT_EQ(first_instruction, context->get_def_use_mgr()->GetDef(38)); + ASSERT_EQ(second_instruction, context->get_def_use_mgr()->GetDef(40)); + } + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %8 = OpTypeFloat 32 + %9 = OpTypePointer Function %8 + %10 = OpTypeVector %8 2 + %11 = OpTypePointer Function %10 + %12 = OpTypeVector %8 3 + %13 = OpTypeMatrix %12 3 + %14 = OpTypePointer Function %13 + %15 = OpTypeFunction %2 %7 %9 %11 %14 %7 %7 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %28 = OpVariable %7 Function + %25 = OpVariable %9 Function + %26 = OpVariable %11 Function + %27 = OpVariable %14 Function + %24 = OpVariable %7 Function + %29 = OpVariable %7 Function + %30 = OpVariable %7 Function + %32 = OpVariable %9 Function + %34 = OpVariable %11 Function + %36 = OpVariable %14 Function + %40 = OpVariable %7 Function + %38 = OpVariable %7 Function + %31 = OpLoad %6 %24 + OpStore %30 %31 + %33 = OpLoad %8 %25 + OpStore %32 %33 + %35 = OpLoad %10 %26 + OpStore %34 %35 + %37 = OpLoad %13 %27 + OpStore %36 %37 + %39 = OpLoad %6 %28 + OpStore %38 %39 + %41 = OpLoad %6 %29 + OpStore %40 %41 + %42 = OpFunctionCall %2 %22 %30 %32 %34 %36 %38 %40 + OpReturn + OpFunctionEnd + %22 = OpFunction %2 None %15 + %16 = OpFunctionParameter %7 + %17 = OpFunctionParameter %9 + %18 = OpFunctionParameter %11 + %19 = OpFunctionParameter %14 + %20 = OpFunctionParameter %7 + %21 = OpFunctionParameter %7 + %23 = OpLabel + OpReturn + OpFunctionEnd +)"; + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); +} + +} // namespace +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzz/transformation_swap_two_functions_test.cpp b/third_party/spirv-tools/test/fuzz/transformation_swap_two_functions_test.cpp new file mode 100644 index 0000000000..20342526a0 --- /dev/null +++ b/third_party/spirv-tools/test/fuzz/transformation_swap_two_functions_test.cpp @@ -0,0 +1,257 @@ +// Copyright (c) 2021 Shiyu Liu +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/fuzz/transformation_swap_two_functions.h" + +#include "gtest/gtest.h" +#include "source/fuzz/fuzzer_util.h" +#include "test/fuzz/fuzz_test_util.h" + +namespace spvtools { +namespace fuzz { +namespace { + +TEST(TransformationSwapTwoFunctionsTest, SimpleTest) { + // float multiplyBy2(in float value) { + // return value*2.0; + // } + + // float multiplyBy4(in float value) { + // return multiplyBy2(value)*2.0; + // } + + // float multiplyBy8(in float value) { + // return multiplyBy2(value)*multiplyBy4(value); + // } + + // layout(location=0) in float value; + // void main() { //4 + // multiplyBy2(3.7); //10 + // multiplyBy4(3.9); //13 + // multiplyBy8(5.0); //16 + // } + + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %48 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %10 "multiplyBy2(f1;" + OpName %9 "value" + OpName %13 "multiplyBy4(f1;" + OpName %12 "value" + OpName %16 "multiplyBy8(f1;" + OpName %15 "value" + OpName %23 "param" + OpName %29 "param" + OpName %32 "param" + OpName %39 "param" + OpName %42 "param" + OpName %45 "param" + OpName %48 "value" + OpDecorate %48 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypePointer Function %6 + %8 = OpTypeFunction %6 %7 + %19 = OpConstant %6 2 + %38 = OpConstant %6 3.70000005 + %41 = OpConstant %6 3.9000001 + %44 = OpConstant %6 5 + %47 = OpTypePointer Input %6 + %48 = OpVariable %47 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %39 = OpVariable %7 Function + %42 = OpVariable %7 Function + %45 = OpVariable %7 Function + OpStore %39 %38 + %40 = OpFunctionCall %6 %10 %39 + OpStore %42 %41 + %43 = OpFunctionCall %6 %13 %42 + OpStore %45 %44 + %46 = OpFunctionCall %6 %16 %45 + OpReturn + OpFunctionEnd + %10 = OpFunction %6 None %8 + %9 = OpFunctionParameter %7 + %11 = OpLabel + %18 = OpLoad %6 %9 + %20 = OpFMul %6 %18 %19 + OpReturnValue %20 + OpFunctionEnd + %13 = OpFunction %6 None %8 + %12 = OpFunctionParameter %7 + %14 = OpLabel + %23 = OpVariable %7 Function + %24 = OpLoad %6 %12 + OpStore %23 %24 + %25 = OpFunctionCall %6 %10 %23 + %26 = OpFMul %6 %25 %19 + OpReturnValue %26 + OpFunctionEnd + %16 = OpFunction %6 None %8 + %15 = OpFunctionParameter %7 + %17 = OpLabel + %29 = OpVariable %7 Function + %32 = OpVariable %7 Function + %30 = OpLoad %6 %15 + OpStore %29 %30 + %31 = OpFunctionCall %6 %10 %29 + %33 = OpLoad %6 %15 + OpStore %32 %33 + %34 = OpFunctionCall %6 %13 %32 + %35 = OpFMul %6 %31 %34 + OpReturnValue %35 + OpFunctionEnd + )"; + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption); + spvtools::ValidatorOptions validator_options; + + // Check context validity. + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + TransformationContext transformation_context( + MakeUnique(context.get()), validator_options); + +#ifndef NDEBUG + // Function should not swap with itself. + ASSERT_DEATH(TransformationSwapTwoFunctions(4, 4).IsApplicable( + context.get(), transformation_context), + "The two function ids cannot be the same."); +#endif + + // Function with id 29 does not exist. + ASSERT_FALSE(TransformationSwapTwoFunctions(10, 29).IsApplicable( + context.get(), transformation_context)); + + // Function with id 30 does not exist. + ASSERT_FALSE(TransformationSwapTwoFunctions(30, 13).IsApplicable( + context.get(), transformation_context)); + + // Both functions with id 5 and 6 do not exist. + ASSERT_FALSE(TransformationSwapTwoFunctions(5, 6).IsApplicable( + context.get(), transformation_context)); + + // Function with result_id 10 and 13 should swap successfully. + auto swap_test5 = TransformationSwapTwoFunctions(10, 13); + ASSERT_TRUE(swap_test5.IsApplicable(context.get(), transformation_context)); + + // Get the definitions of functions 10 and 13, as recorded by the def-use + // manager. + auto def_use_manager = context->get_def_use_mgr(); + auto function_10_inst = def_use_manager->GetDef(10); + auto function_13_inst = def_use_manager->GetDef(13); + + ApplyAndCheckFreshIds(swap_test5, context.get(), &transformation_context); + + // Check that def-use information for functions 10 and 13 has been preserved + // by the transformation. + ASSERT_EQ(function_10_inst, def_use_manager->GetDef(10)); + ASSERT_EQ(function_13_inst, def_use_manager->GetDef(13)); + + ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options, + kConsoleMessageConsumer)); + + std::string after_transformation = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" %48 + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 310 + OpName %4 "main" + OpName %10 "multiplyBy2(f1;" + OpName %9 "value" + OpName %13 "multiplyBy4(f1;" + OpName %12 "value" + OpName %16 "multiplyBy8(f1;" + OpName %15 "value" + OpName %23 "param" + OpName %29 "param" + OpName %32 "param" + OpName %39 "param" + OpName %42 "param" + OpName %45 "param" + OpName %48 "value" + OpDecorate %48 Location 0 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeFloat 32 + %7 = OpTypePointer Function %6 + %8 = OpTypeFunction %6 %7 + %19 = OpConstant %6 2 + %38 = OpConstant %6 3.70000005 + %41 = OpConstant %6 3.9000001 + %44 = OpConstant %6 5 + %47 = OpTypePointer Input %6 + %48 = OpVariable %47 Input + %4 = OpFunction %2 None %3 + %5 = OpLabel + %39 = OpVariable %7 Function + %42 = OpVariable %7 Function + %45 = OpVariable %7 Function + OpStore %39 %38 + %40 = OpFunctionCall %6 %10 %39 + OpStore %42 %41 + %43 = OpFunctionCall %6 %13 %42 + OpStore %45 %44 + %46 = OpFunctionCall %6 %16 %45 + OpReturn + OpFunctionEnd + %13 = OpFunction %6 None %8 + %12 = OpFunctionParameter %7 + %14 = OpLabel + %23 = OpVariable %7 Function + %24 = OpLoad %6 %12 + OpStore %23 %24 + %25 = OpFunctionCall %6 %10 %23 + %26 = OpFMul %6 %25 %19 + OpReturnValue %26 + OpFunctionEnd + %10 = OpFunction %6 None %8 + %9 = OpFunctionParameter %7 + %11 = OpLabel + %18 = OpLoad %6 %9 + %20 = OpFMul %6 %18 %19 + OpReturnValue %20 + OpFunctionEnd + %16 = OpFunction %6 None %8 + %15 = OpFunctionParameter %7 + %17 = OpLabel + %29 = OpVariable %7 Function + %32 = OpVariable %7 Function + %30 = OpLoad %6 %15 + OpStore %29 %30 + %31 = OpFunctionCall %6 %10 %29 + %33 = OpLoad %6 %15 + OpStore %32 %33 + %34 = OpFunctionCall %6 %13 %32 + %35 = OpFMul %6 %31 %34 + OpReturnValue %35 + OpFunctionEnd + )"; + ASSERT_TRUE(IsEqual(env, after_transformation, context.get())); +} + +} // namespace +} // namespace fuzz +} // namespace spvtools diff --git a/third_party/spirv-tools/test/fuzzers/BUILD.gn b/third_party/spirv-tools/test/fuzzers/BUILD.gn index be1258a459..ec09b2b067 100644 --- a/third_party/spirv-tools/test/fuzzers/BUILD.gn +++ b/third_party/spirv-tools/test/fuzzers/BUILD.gn @@ -39,10 +39,7 @@ if (!build_with_chromium || use_fuzzing_engine) { ":spvtools_opt_legalization_fuzzer", ":spvtools_opt_performance_fuzzer", ":spvtools_opt_size_fuzzer", - ":spvtools_opt_webgputovulkan_fuzzer", - ":spvtools_opt_vulkantowebgpu_fuzzer", ":spvtools_val_fuzzer", - ":spvtools_val_webgpu_fuzzer", ] } } @@ -104,31 +101,12 @@ spvtools_fuzzer("spvtools_opt_size_fuzzer_src") { ] } - -spvtools_fuzzer("spvtools_opt_webgputovulkan_fuzzer_src") { - sources = [ - "spvtools_opt_webgputovulkan_fuzzer.cpp", - ] -} - -spvtools_fuzzer("spvtools_opt_vulkantowebgpu_fuzzer_src") { - sources = [ - "spvtools_opt_vulkantowebgpu_fuzzer.cpp", - ] -} - spvtools_fuzzer("spvtools_val_fuzzer_src") { sources = [ "spvtools_val_fuzzer.cpp", ] } -spvtools_fuzzer("spvtools_val_webgpu_fuzzer_src") { - sources = [ - "spvtools_val_webgpu_fuzzer.cpp", - ] -} - if (!build_with_chromium || use_fuzzing_engine) { fuzzer_test("spvtools_as_fuzzer") { sources = [] @@ -181,22 +159,6 @@ if (!build_with_chromium || use_fuzzing_engine) { seed_corpus = "corpora/spv" } - fuzzer_test("spvtools_opt_webgputovulkan_fuzzer") { - sources = [] - deps = [ - ":spvtools_opt_webgputovulkan_fuzzer_src", - ] - seed_corpus = "corpora/spv" - } - - fuzzer_test("spvtools_opt_vulkantowebgpu_fuzzer") { - sources = [] - deps = [ - ":spvtools_opt_vulkantowebgpu_fuzzer_src", - ] - seed_corpus = "corpora/spv" - } - fuzzer_test("spvtools_val_fuzzer") { sources = [] deps = [ @@ -204,12 +166,4 @@ if (!build_with_chromium || use_fuzzing_engine) { ] seed_corpus = "corpora/spv" } - - fuzzer_test("spvtools_val_webgpu_fuzzer") { - sources = [] - deps = [ - ":spvtools_val_webgpu_fuzzer_src", - ] - seed_corpus = "corpora/spv" - } } diff --git a/third_party/spirv-tools/test/fuzzers/spvtools_opt_vulkantowebgpu_fuzzer.cpp b/third_party/spirv-tools/test/fuzzers/spvtools_opt_vulkantowebgpu_fuzzer.cpp deleted file mode 100644 index 9371c0df08..0000000000 --- a/third_party/spirv-tools/test/fuzzers/spvtools_opt_vulkantowebgpu_fuzzer.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2019 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include -#include - -#include "spirv-tools/optimizer.hpp" - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_1); - optimizer.SetMessageConsumer([](spv_message_level_t, const char*, - const spv_position_t&, const char*) {}); - - std::vector input; - input.resize(size >> 2); - - size_t count = 0; - for (size_t i = 0; (i + 3) < size; i += 4) { - input[count++] = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) | - (data[i + 3]) << 24; - } - - optimizer.RegisterVulkanToWebGPUPasses(); - optimizer.Run(input.data(), input.size(), &input); - - return 0; -} diff --git a/third_party/spirv-tools/test/fuzzers/spvtools_opt_webgputovulkan_fuzzer.cpp b/third_party/spirv-tools/test/fuzzers/spvtools_opt_webgputovulkan_fuzzer.cpp deleted file mode 100644 index 78ddbb75c0..0000000000 --- a/third_party/spirv-tools/test/fuzzers/spvtools_opt_webgputovulkan_fuzzer.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2019 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include -#include - -#include "spirv-tools/optimizer.hpp" - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - spvtools::Optimizer optimizer(SPV_ENV_WEBGPU_0); - optimizer.SetMessageConsumer([](spv_message_level_t, const char*, - const spv_position_t&, const char*) {}); - - std::vector input; - input.resize(size >> 2); - - size_t count = 0; - for (size_t i = 0; (i + 3) < size; i += 4) { - input[count++] = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) | - (data[i + 3]) << 24; - } - - optimizer.RegisterWebGPUToVulkanPasses(); - optimizer.Run(input.data(), input.size(), &input); - - return 0; -} diff --git a/third_party/spirv-tools/test/fuzzers/spvtools_val_webgpu_fuzzer.cpp b/third_party/spirv-tools/test/fuzzers/spvtools_val_webgpu_fuzzer.cpp deleted file mode 100644 index bed6e1a21f..0000000000 --- a/third_party/spirv-tools/test/fuzzers/spvtools_val_webgpu_fuzzer.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2019 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include -#include - -#include "spirv-tools/libspirv.hpp" - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - spvtools::SpirvTools tools(SPV_ENV_WEBGPU_0); - tools.SetMessageConsumer([](spv_message_level_t, const char*, - const spv_position_t&, const char*) {}); - - std::vector input; - input.resize(size >> 2); - - size_t count = 0; - for (size_t i = 0; (i + 3) < size; i += 4) { - input[count++] = data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) | - (data[i + 3]) << 24; - } - - tools.Validate(input); - return 0; -} diff --git a/third_party/spirv-tools/test/operand_capabilities_test.cpp b/third_party/spirv-tools/test/operand_capabilities_test.cpp index addb08a793..6f83dfeb8e 100644 --- a/third_party/spirv-tools/test/operand_capabilities_test.cpp +++ b/third_party/spirv-tools/test/operand_capabilities_test.cpp @@ -199,7 +199,8 @@ INSTANTIATE_TEST_SUITE_P( CASE1(STORAGE_CLASS, StorageClassOutput, Shader), CASE0(STORAGE_CLASS, StorageClassWorkgroup), CASE0(STORAGE_CLASS, StorageClassCrossWorkgroup), - CASE1(STORAGE_CLASS, StorageClassPrivate, Shader), + CASE2(STORAGE_CLASS, StorageClassPrivate, Shader, + VectorComputeINTEL), CASE0(STORAGE_CLASS, StorageClassFunction), CASE1(STORAGE_CLASS, StorageClassGeneric, GenericPointer), // Bug 14287 @@ -498,11 +499,11 @@ INSTANTIATE_TEST_SUITE_P( CASE1(BUILT_IN, BuiltInCullDistance, CullDistance), // Bug 1407, 15234 CASE1(BUILT_IN, BuiltInVertexId, Shader), CASE1(BUILT_IN, BuiltInInstanceId, Shader), - CASE4(BUILT_IN, BuiltInPrimitiveId, Geometry, Tessellation, - RayTracingNV, RayTracingProvisionalKHR), + CASE5(BUILT_IN, BuiltInPrimitiveId, Geometry, Tessellation, + RayTracingNV, RayTracingKHR, MeshShadingNV), CASE2(BUILT_IN, BuiltInInvocationId, Geometry, Tessellation), - CASE2(BUILT_IN, BuiltInLayer, Geometry, ShaderViewportIndexLayerEXT), - CASE2(BUILT_IN, BuiltInViewportIndex, MultiViewport, ShaderViewportIndexLayerEXT), // Bug 15234 + CASE3(BUILT_IN, BuiltInLayer, Geometry, ShaderViewportIndexLayerEXT, MeshShadingNV), + CASE3(BUILT_IN, BuiltInViewportIndex, MultiViewport, ShaderViewportIndexLayerEXT, MeshShadingNV), // Bug 15234 CASE1(BUILT_IN, BuiltInTessLevelOuter, Tessellation), CASE1(BUILT_IN, BuiltInTessLevelInner, Tessellation), CASE1(BUILT_IN, BuiltInTessCoord, Tessellation), @@ -545,10 +546,11 @@ INSTANTIATE_TEST_SUITE_P( Values(SPV_ENV_UNIVERSAL_1_5), ValuesIn(std::vector{ // SPIR-V 1.5 adds new capabilities to enable these two builtins. - CASE3(BUILT_IN, BuiltInLayer, Geometry, ShaderLayer, - ShaderViewportIndexLayerEXT), - CASE3(BUILT_IN, BuiltInViewportIndex, MultiViewport, - ShaderViewportIndex, ShaderViewportIndexLayerEXT), + CASE4(BUILT_IN, BuiltInLayer, Geometry, ShaderLayer, + ShaderViewportIndexLayerEXT, MeshShadingNV), + CASE4(BUILT_IN, BuiltInViewportIndex, MultiViewport, + ShaderViewportIndex, ShaderViewportIndexLayerEXT, + MeshShadingNV), }))); // See SPIR-V Section 3.22 Selection Control diff --git a/third_party/spirv-tools/test/opt/CMakeLists.txt b/third_party/spirv-tools/test/opt/CMakeLists.txt index 3426958783..621a6aa46d 100644 --- a/third_party/spirv-tools/test/opt/CMakeLists.txt +++ b/third_party/spirv-tools/test/opt/CMakeLists.txt @@ -34,7 +34,6 @@ add_spvtools_unittest(TARGET opt dead_insert_elim_test.cpp dead_variable_elim_test.cpp debug_info_manager_test.cpp - decompose_initialized_variables_test.cpp decoration_manager_test.cpp def_use_test.cpp desc_sroa_test.cpp @@ -48,7 +47,6 @@ add_spvtools_unittest(TARGET opt fold_test.cpp freeze_spec_const_test.cpp function_test.cpp - generate_webgpu_initializers_test.cpp graphics_robust_access_test.cpp if_conversion_test.cpp inline_opaque_test.cpp @@ -59,11 +57,11 @@ add_spvtools_unittest(TARGET opt inst_debug_printf_test.cpp instruction_list_test.cpp instruction_test.cpp + interp_fixup_test.cpp ir_builder.cpp ir_context_test.cpp ir_loader_test.cpp iterator_test.cpp - legalize_vector_shuffle_test.cpp line_debug_info_test.cpp local_access_chain_convert_test.cpp local_redundancy_elimination_test.cpp @@ -81,6 +79,7 @@ add_spvtools_unittest(TARGET opt propagator_test.cpp reduce_load_size_test.cpp redundancy_elimination_test.cpp + remove_unused_interface_variables_test.cpp register_liveness.cpp relax_float_ops_test.cpp replace_invalid_opc_test.cpp @@ -88,9 +87,7 @@ add_spvtools_unittest(TARGET opt scalar_replacement_test.cpp set_spec_const_default_value_test.cpp simplification_test.cpp - split_invalid_unreachable_test.cpp strength_reduction_test.cpp - strip_atomic_counter_memory_test.cpp strip_debug_info_test.cpp strip_reflect_info_test.cpp struct_cfg_analysis_test.cpp diff --git a/third_party/spirv-tools/test/opt/aggressive_dead_code_elim_test.cpp b/third_party/spirv-tools/test/opt/aggressive_dead_code_elim_test.cpp index 972e6e5734..5b4291dacd 100644 --- a/third_party/spirv-tools/test/opt/aggressive_dead_code_elim_test.cpp +++ b/third_party/spirv-tools/test/opt/aggressive_dead_code_elim_test.cpp @@ -3948,12 +3948,15 @@ OpBranch %12 OpLoopMerge %14 %15 None OpBranch %16 %16 = OpLabel -OpSwitch %13 %14 0 %17 1 %15 +OpSelectionMerge %18 None +OpSwitch %13 %18 0 %17 1 %15 %17 = OpLabel OpStore %3 %uint_1 OpBranch %15 %15 = OpLabel OpBranch %12 +%18 = OpLabel +OpBranch %14 %14 = OpLabel OpStore %3 %uint_0 OpReturn diff --git a/third_party/spirv-tools/test/opt/block_merge_test.cpp b/third_party/spirv-tools/test/opt/block_merge_test.cpp index 7381908ed4..140a5c09ee 100644 --- a/third_party/spirv-tools/test/opt/block_merge_test.cpp +++ b/third_party/spirv-tools/test/opt/block_merge_test.cpp @@ -744,6 +744,7 @@ TEST_F(BlockMergeTest, DontMergeSwitch) { ; CHECK: OpLoopMerge [[merge:%\w+]] [[cont:%\w+]] None ; CHECK-NEXT: OpBranch [[ret:%\w+]] ; CHECK: [[ret:%\w+]] = OpLabel +; CHECK-NEXT: OpSelectionMerge ; CHECK-NEXT: OpSwitch ; CHECK-DAG: [[cont]] = OpLabel ; CHECK-DAG: [[merge]] = OpLabel @@ -763,6 +764,7 @@ OpBranch %2 OpLoopMerge %3 %4 None OpBranch %5 %5 = OpLabel +OpSelectionMerge %6 None OpSwitch %int_0 %6 %6 = OpLabel OpReturn diff --git a/third_party/spirv-tools/test/opt/convert_relaxed_to_half_test.cpp b/third_party/spirv-tools/test/opt/convert_relaxed_to_half_test.cpp index c138154773..ca6ee5838e 100644 --- a/third_party/spirv-tools/test/opt/convert_relaxed_to_half_test.cpp +++ b/third_party/spirv-tools/test/opt/convert_relaxed_to_half_test.cpp @@ -1331,6 +1331,72 @@ OpFunctionEnd SinglePassRunAndMatch(defs + func, true); } +TEST_F(ConvertToHalfTest, RemoveRelaxDec) { + // See https://github.com/KhronosGroup/SPIRV-Tools/issues/4117 + + // This test is a case where the relax precision decorations need to be + // removed, but the body of the function does not change because there are not + // arithmetic operations. So, there is not need for the Float16 capability. + const std::string test = + R"( +; CHECK-NOT: OpCapability Float16 +; GLSL seems to generate this decoration on the load of a texture, which seems odd to me. +; This pass does not currently remove it, and I'm not sure what we should do with it, so I will leave it. +; CHECK: OpDecorate [[tex:%\w+]] RelaxedPrecision +; CHECK-NOT: OpDecorate {{%\w+}} RelaxedPrecision +; CHECK: OpLabel +; CHECK: [[tex]] = OpLoad {{%\w+}} %sTexture +; CHECK: [[coord:%\w+]] = OpLoad %v2float +; CHECK: [[retval:%\w+]] = OpImageSampleImplicitLod %v4float {{%\w+}} [[coord]] +; CHECK: OpStore %outFragColor [[retval]] + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %outFragColor %v_texcoord + OpExecutionMode %main OriginUpperLeft + OpSource ESSL 310 + OpName %main "main" + OpName %outFragColor "outFragColor" + OpName %sTexture "sTexture" + OpName %v_texcoord "v_texcoord" + OpDecorate %outFragColor RelaxedPrecision + OpDecorate %outFragColor Location 0 + OpDecorate %sTexture RelaxedPrecision + OpDecorate %sTexture DescriptorSet 0 + OpDecorate %sTexture Binding 0 + OpDecorate %14 RelaxedPrecision + OpDecorate %v_texcoord RelaxedPrecision + OpDecorate %v_texcoord Location 0 + OpDecorate %18 RelaxedPrecision + OpDecorate %19 RelaxedPrecision + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 +%_ptr_Output_v4float = OpTypePointer Output %v4float +%outFragColor = OpVariable %_ptr_Output_v4float Output + %10 = OpTypeImage %float 2D 0 0 0 1 Unknown + %11 = OpTypeSampledImage %10 +%_ptr_UniformConstant_11 = OpTypePointer UniformConstant %11 + %sTexture = OpVariable %_ptr_UniformConstant_11 UniformConstant + %v2float = OpTypeVector %float 2 +%_ptr_Input_v2float = OpTypePointer Input %v2float + %v_texcoord = OpVariable %_ptr_Input_v2float Input + %main = OpFunction %void None %3 + %5 = OpLabel + %14 = OpLoad %11 %sTexture + %18 = OpLoad %v2float %v_texcoord + %19 = OpImageSampleImplicitLod %v4float %14 %18 + OpStore %outFragColor %19 + OpReturn + OpFunctionEnd +)"; + + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + auto result = SinglePassRunAndMatch(test, true); + EXPECT_EQ(Pass::Status::SuccessWithChange, std::get<1>(result)); +} + } // namespace } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/dead_branch_elim_test.cpp b/third_party/spirv-tools/test/opt/dead_branch_elim_test.cpp index 41ce31da14..f89befb496 100644 --- a/third_party/spirv-tools/test/opt/dead_branch_elim_test.cpp +++ b/third_party/spirv-tools/test/opt/dead_branch_elim_test.cpp @@ -2722,6 +2722,7 @@ OpSource GLSL 140 ; CHECK: [[bb1]] = OpLabel ; CHECK-NEXT: OpBranch [[bb2:%\w+]] ; CHECK: [[bb2]] = OpLabel +; CHECK-NEXT: OpSelectionMerge ; CHECK-NEXT: OpSwitch {{%\w+}} [[bb3:%\w+]] 0 [[loop_merge]] 1 [[bb3:%\w+]] ; CHECK: [[bb3]] = OpLabel ; CHECK-NEXT: OpBranch [[sel_merge:%\w+]] @@ -2739,6 +2740,7 @@ OpBranch %bb1 OpSelectionMerge %sel_merge None OpBranchConditional %true %bb2 %bb4 %bb2 = OpLabel +OpSelectionMerge %bb3 None OpSwitch %undef_int %bb3 0 %loop_merge 1 %bb3 %bb3 = OpLabel OpBranch %sel_merge @@ -2782,6 +2784,7 @@ OpSource GLSL 140 ; CHECK: [[bb1]] = OpLabel ; CHECK-NEXT: OpBranch [[bb2:%\w+]] ; CHECK: [[bb2]] = OpLabel +; CHECK-NEXT: OpSelectionMerge ; CHECK-NEXT: OpSwitch {{%\w+}} [[bb3:%\w+]] 0 [[loop_cont]] 1 [[bb3:%\w+]] ; CHECK: [[bb3]] = OpLabel ; CHECK-NEXT: OpBranch [[sel_merge:%\w+]] @@ -2799,6 +2802,7 @@ OpBranch %bb1 OpSelectionMerge %sel_merge None OpBranchConditional %true %bb2 %bb4 %bb2 = OpLabel +OpSelectionMerge %bb3 None OpSwitch %undef_int %bb3 0 %cont 1 %bb3 %bb3 = OpLabel OpBranch %sel_merge diff --git a/third_party/spirv-tools/test/opt/debug_info_manager_test.cpp b/third_party/spirv-tools/test/opt/debug_info_manager_test.cpp index 911331a74c..49407fd580 100644 --- a/third_party/spirv-tools/test/opt/debug_info_manager_test.cpp +++ b/third_party/spirv-tools/test/opt/debug_info_manager_test.cpp @@ -31,6 +31,9 @@ static const uint32_t kDebugFunctionOperandFunctionIndex = 13; static const uint32_t kDebugInlinedAtOperandLineIndex = 4; static const uint32_t kDebugInlinedAtOperandScopeIndex = 5; static const uint32_t kDebugInlinedAtOperandInlinedIndex = 6; +static const uint32_t kOpLineInOperandFileIndex = 0; +static const uint32_t kOpLineInOperandLineIndex = 1; +static const uint32_t kOpLineInOperandColumnIndex = 2; namespace spvtools { namespace opt { @@ -609,6 +612,80 @@ void main(float in_var_color : COLOR) { EXPECT_FALSE(dbg_info_mgr->IsVariableDebugDeclared(100)); } +TEST(DebugInfoManager, AddDebugValueForDecl) { + const std::string text = R"( + OpCapability Shader + %1 = OpExtInstImport "OpenCL.DebugInfo.100" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %in_var_COLOR + OpExecutionMode %main OriginUpperLeft + %5 = OpString "ps.hlsl" + %14 = OpString "#line 1 \"ps.hlsl\" +void main(float in_var_color : COLOR) { + float color = in_var_color; +} +" + %17 = OpString "float" + %21 = OpString "main" + %24 = OpString "color" + OpName %in_var_COLOR "in.var.COLOR" + OpName %main "main" + OpDecorate %in_var_COLOR Location 0 + %uint = OpTypeInt 32 0 + %uint_32 = OpConstant %uint 32 + %float = OpTypeFloat 32 +%_ptr_Input_float = OpTypePointer Input %float + %void = OpTypeVoid + %27 = OpTypeFunction %void +%_ptr_Function_float = OpTypePointer Function %float +%in_var_COLOR = OpVariable %_ptr_Input_float Input + %13 = OpExtInst %void %1 DebugExpression + %15 = OpExtInst %void %1 DebugSource %5 %14 + %16 = OpExtInst %void %1 DebugCompilationUnit 1 4 %15 HLSL + %18 = OpExtInst %void %1 DebugTypeBasic %17 %uint_32 Float + %20 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %18 %18 + %22 = OpExtInst %void %1 DebugFunction %21 %20 %15 1 1 %16 %21 FlagIsProtected|FlagIsPrivate 1 %main + %12 = OpExtInst %void %1 DebugInfoNone + %25 = OpExtInst %void %1 DebugLocalVariable %24 %18 %15 1 20 %22 FlagIsLocal 0 + %main = OpFunction %void None %27 + %28 = OpLabel + %100 = OpVariable %_ptr_Function_float Function + %31 = OpLoad %float %in_var_COLOR + %101 = OpExtInst %void %1 DebugScope %22 + OpLine %5 13 7 + OpStore %100 %31 + OpNoLine + %102 = OpExtInst %void %1 DebugNoScope + %36 = OpExtInst %void %1 DebugDeclare %25 %100 %13 + OpReturn + OpFunctionEnd + )"; + + std::unique_ptr context = + BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + auto* def_use_mgr = context->get_def_use_mgr(); + auto* dbg_decl = def_use_mgr->GetDef(36); + EXPECT_EQ(dbg_decl->GetOpenCL100DebugOpcode(), + OpenCLDebugInfo100DebugDeclare); + + auto* dbg_info_mgr = context->get_debug_info_mgr(); + Instruction* store = dbg_decl->PreviousNode(); + auto* dbg_value = + dbg_info_mgr->AddDebugValueForDecl(dbg_decl, 100, dbg_decl, store); + + EXPECT_EQ(dbg_value->GetOpenCL100DebugOpcode(), OpenCLDebugInfo100DebugValue); + EXPECT_EQ(dbg_value->dbg_line_inst()->GetSingleWordInOperand( + kOpLineInOperandFileIndex), + 5); + EXPECT_EQ(dbg_value->dbg_line_inst()->GetSingleWordInOperand( + kOpLineInOperandLineIndex), + 13); + EXPECT_EQ(dbg_value->dbg_line_inst()->GetSingleWordInOperand( + kOpLineInOperandColumnIndex), + 7); +} + } // namespace } // namespace analysis } // namespace opt diff --git a/third_party/spirv-tools/test/opt/decompose_initialized_variables_test.cpp b/third_party/spirv-tools/test/opt/decompose_initialized_variables_test.cpp deleted file mode 100644 index 06ba59a584..0000000000 --- a/third_party/spirv-tools/test/opt/decompose_initialized_variables_test.cpp +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include - -#include "test/opt/pass_fixture.h" -#include "test/opt/pass_utils.h" - -namespace spvtools { -namespace opt { -namespace { - -using DecomposeInitializedVariablesTest = PassTest<::testing::Test>; - -std::string single_entry_header = R"(OpCapability Shader -OpCapability VulkanMemoryModel -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical Vulkan -OpEntryPoint Vertex %1 "shader" -%uint = OpTypeInt 32 0 -%uint_1 = OpConstant %uint 1 -%4 = OpConstantNull %uint -%void = OpTypeVoid -%6 = OpTypeFunction %void -)"; - -std::string GetFunctionTest(std::string body) { - auto result = single_entry_header; - result += "%_ptr_Function_uint = OpTypePointer Function %uint\n"; - result += "%1 = OpFunction %void None %6\n"; - result += "%8 = OpLabel\n"; - result += body + "\n"; - result += "OpReturn\n"; - result += "OpFunctionEnd\n"; - return result; -} - -TEST_F(DecomposeInitializedVariablesTest, FunctionChanged) { - std::string input = "%9 = OpVariable %_ptr_Function_uint Function %uint_1"; - std::string expected = R"(%9 = OpVariable %_ptr_Function_uint Function -OpStore %9 %uint_1)"; - - SinglePassRunAndCheck( - GetFunctionTest(input), GetFunctionTest(expected), - /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, FunctionUnchanged) { - std::string input = "%9 = OpVariable %_ptr_Function_uint Function"; - - SinglePassRunAndCheck( - GetFunctionTest(input), GetFunctionTest(input), /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, FunctionMultipleVariables) { - std::string input = R"(%9 = OpVariable %_ptr_Function_uint Function %uint_1 -%10 = OpVariable %_ptr_Function_uint Function %4)"; - std::string expected = R"(%9 = OpVariable %_ptr_Function_uint Function -%10 = OpVariable %_ptr_Function_uint Function -OpStore %9 %uint_1 -OpStore %10 %4)"; - - SinglePassRunAndCheck( - GetFunctionTest(input), GetFunctionTest(expected), - /* skip_nop = */ false); -} - -std::string GetGlobalTest(std::string storage_class, bool initialized, - bool decomposed) { - auto result = single_entry_header; - - result += "%_ptr_" + storage_class + "_uint = OpTypePointer " + - storage_class + " %uint\n"; - if (initialized) { - result += "%8 = OpVariable %_ptr_" + storage_class + "_uint " + - storage_class + " %4\n"; - } else { - result += "%8 = OpVariable %_ptr_" + storage_class + "_uint " + - storage_class + "\n"; - } - result += R"(%1 = OpFunction %void None %9 -%9 = OpLabel -)"; - if (decomposed) result += "OpStore %8 %4\n"; - result += R"(OpReturn -OpFunctionEnd -)"; - return result; -} - -TEST_F(DecomposeInitializedVariablesTest, PrivateChanged) { - std::string input = GetGlobalTest("Private", true, false); - std::string expected = GetGlobalTest("Private", false, true); - SinglePassRunAndCheck( - input, expected, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, PrivateUnchanged) { - std::string input = GetGlobalTest("Private", false, false); - SinglePassRunAndCheck( - input, input, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, OutputChanged) { - std::string input = GetGlobalTest("Output", true, false); - std::string expected = GetGlobalTest("Output", false, true); - SinglePassRunAndCheck( - input, expected, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, OutputUnchanged) { - std::string input = GetGlobalTest("Output", false, false); - SinglePassRunAndCheck( - input, input, /* skip_nop = */ false); -} - -std::string multiple_entry_header = R"(OpCapability Shader -OpCapability VulkanMemoryModel -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical Vulkan -OpEntryPoint Vertex %1 "vertex" -OpEntryPoint Fragment %2 "fragment" -%uint = OpTypeInt 32 0 -%4 = OpConstantNull %uint -%void = OpTypeVoid -%6 = OpTypeFunction %void -)"; - -std::string GetGlobalMultipleEntryTest(std::string storage_class, - bool initialized, bool decomposed) { - auto result = multiple_entry_header; - result += "%_ptr_" + storage_class + "_uint = OpTypePointer " + - storage_class + " %uint\n"; - if (initialized) { - result += "%8 = OpVariable %_ptr_" + storage_class + "_uint " + - storage_class + " %4\n"; - } else { - result += "%8 = OpVariable %_ptr_" + storage_class + "_uint " + - storage_class + "\n"; - } - result += R"(%1 = OpFunction %void None %9 -%9 = OpLabel -)"; - if (decomposed) result += "OpStore %8 %4\n"; - result += R"(OpReturn -OpFunctionEnd -%2 = OpFunction %void None %10 -%10 = OpLabel -)"; - if (decomposed) result += "OpStore %8 %4\n"; - result += R"(OpReturn -OpFunctionEnd -)"; - - return result; -} - -TEST_F(DecomposeInitializedVariablesTest, PrivateMultipleEntryChanged) { - std::string input = GetGlobalMultipleEntryTest("Private", true, false); - std::string expected = GetGlobalMultipleEntryTest("Private", false, true); - SinglePassRunAndCheck( - input, expected, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, PrivateMultipleEntryUnchanged) { - std::string input = GetGlobalMultipleEntryTest("Private", false, false); - SinglePassRunAndCheck( - input, input, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, OutputMultipleEntryChanged) { - std::string input = GetGlobalMultipleEntryTest("Output", true, false); - std::string expected = GetGlobalMultipleEntryTest("Output", false, true); - SinglePassRunAndCheck( - input, expected, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, OutputMultipleEntryUnchanged) { - std::string input = GetGlobalMultipleEntryTest("Output", false, false); - SinglePassRunAndCheck( - input, input, /* skip_nop = */ false); -} - -std::string GetGlobalWithNonEntryPointTest(std::string storage_class, - bool initialized, bool decomposed) { - auto result = single_entry_header; - result += "%_ptr_" + storage_class + "_uint = OpTypePointer " + - storage_class + " %uint\n"; - if (initialized) { - result += "%8 = OpVariable %_ptr_" + storage_class + "_uint " + - storage_class + " %4\n"; - } else { - result += "%8 = OpVariable %_ptr_" + storage_class + "_uint " + - storage_class + "\n"; - } - result += R"(%1 = OpFunction %void None %9 -%9 = OpLabel -)"; - if (decomposed) result += "OpStore %8 %4\n"; - result += R"(OpReturn -OpFunctionEnd -%10 = OpFunction %void None %11 -%11 = OpLabel -OpReturn -OpFunctionEnd -)"; - - return result; -} - -TEST_F(DecomposeInitializedVariablesTest, PrivateWithNonEntryPointChanged) { - std::string input = GetGlobalWithNonEntryPointTest("Private", true, false); - std::string expected = GetGlobalWithNonEntryPointTest("Private", false, true); - SinglePassRunAndCheck( - input, expected, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, PrivateWithNonEntryPointUnchanged) { - std::string input = GetGlobalWithNonEntryPointTest("Private", false, false); - // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); - SinglePassRunAndCheck( - input, input, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, OutputWithNonEntryPointChanged) { - std::string input = GetGlobalWithNonEntryPointTest("Output", true, false); - std::string expected = GetGlobalWithNonEntryPointTest("Output", false, true); - SinglePassRunAndCheck( - input, expected, /* skip_nop = */ false); -} - -TEST_F(DecomposeInitializedVariablesTest, OutputWithNonEntryPointUnchanged) { - std::string input = GetGlobalWithNonEntryPointTest("Output", false, false); - // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); - SinglePassRunAndCheck( - input, input, /* skip_nop = */ false); -} - -} // namespace -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/desc_sroa_test.cpp b/third_party/spirv-tools/test/opt/desc_sroa_test.cpp index cdcc9a835f..b35ad474da 100644 --- a/third_party/spirv-tools/test/opt/desc_sroa_test.cpp +++ b/third_party/spirv-tools/test/opt/desc_sroa_test.cpp @@ -729,6 +729,47 @@ TEST_F(DescriptorScalarReplacementTest, ResourceStructAsFunctionParam) { SinglePassRunAndMatch(checks + shader, true); } +TEST_F(DescriptorScalarReplacementTest, BindingForResourceArrayOfStructs) { + // Check that correct binding numbers are given to an array of descriptors + // to structs. + + const std::string shader = R"( +; CHECK: OpDecorate {{%\w+}} Binding 0 +; CHECK: OpDecorate {{%\w+}} Binding 1 + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %2 "psmain" + OpExecutionMode %2 OriginUpperLeft + OpDecorate %5 DescriptorSet 0 + OpDecorate %5 Binding 0 + OpMemberDecorate %_struct_4 0 Offset 0 + OpMemberDecorate %_struct_4 1 Offset 4 + OpDecorate %_struct_4 Block + %float = OpTypeFloat 32 + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %int_1 = OpConstant %int 1 + %uint = OpTypeInt 32 0 + %uint_2 = OpConstant %uint 2 + %_struct_4 = OpTypeStruct %float %int +%_arr__struct_4_uint_2 = OpTypeArray %_struct_4 %uint_2 +%_ptr_Uniform__arr__struct_4_uint_2 = OpTypePointer Uniform %_arr__struct_4_uint_2 + %void = OpTypeVoid + %25 = OpTypeFunction %void +%_ptr_Uniform_int = OpTypePointer Uniform %int + %5 = OpVariable %_ptr_Uniform__arr__struct_4_uint_2 Uniform + %2 = OpFunction %void None %25 + %29 = OpLabel + %40 = OpAccessChain %_ptr_Uniform_int %5 %int_0 %int_1 + %41 = OpAccessChain %_ptr_Uniform_int %5 %int_1 %int_1 + OpReturn + OpFunctionEnd +)"; + + SinglePassRunAndMatch(shader, true); +} + } // namespace } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/eliminate_dead_functions_test.cpp b/third_party/spirv-tools/test/opt/eliminate_dead_functions_test.cpp index 96ecdc6055..96deb2a68c 100644 --- a/third_party/spirv-tools/test/opt/eliminate_dead_functions_test.cpp +++ b/third_party/spirv-tools/test/opt/eliminate_dead_functions_test.cpp @@ -439,6 +439,84 @@ OpFunctionEnd SinglePassRunAndMatch(text, true); } +TEST_F(EliminateDeadFunctionsBasicTest, NonSemanticInfoRemoveDebugPrintf) { + const std::string text = R"( +; CHECK-NOT: %foo_ = OpFunction %void None % 3 +; CHECK-NOT: % 7 = OpLabel +; CHECK-NOT: %c = OpVariable %_ptr_Function_v4float Function +; CHECK-NOT: % 22 = OpAccessChain %_ptr_UniformConstant_13 %samplers %int_0 +; CHECK-NOT: % 23 = OpLoad % 13 % 22 +; CHECK-NOT: % 27 = OpImageSampleExplicitLod %v4float % 23 % 26 Lod %float_0 +; CHECK-NOT: OpStore %c % 27 +; CHECK-NOT: % 31 = OpAccessChain %_ptr_Function_float %c %uint_0 +; CHECK-NOT: % 32 = OpLoad %float %31 +; CHECK-NOT: % 34 = OpExtInst %void %33 1 % 28 % 32 +OpCapability RayTracingKHR +OpExtension "SPV_KHR_non_semantic_info" +OpExtension "SPV_KHR_ray_tracing" +%1 = OpExtInstImport "GLSL.std.450" +%33 = OpExtInstImport "NonSemantic.DebugPrintf" +OpMemoryModel Logical GLSL450 +OpEntryPoint ClosestHitNV %main "main" %samplers +%28 = OpString "%f" +OpSource GLSL 460 +OpSourceExtension "GL_EXT_debug_printf" +OpName %main "main" +OpName %foo_ "foo(" +OpName %c "c" +OpName %samplers "samplers" +OpDecorate %samplers DescriptorSet 0 +OpDecorate %samplers Binding 0 +%void = OpTypeVoid +%3 = OpTypeFunction %void +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%_ptr_Function_v4float = OpTypePointer Function %v4float +%12 = OpTypeImage %float 3D 0 0 0 1 Unknown +%13 = OpTypeSampledImage %12 +%uint = OpTypeInt 32 0 +%uint_1 = OpConstant %uint 1 +%_arr_13_uint_1 = OpTypeArray %13 %uint_1 +%_ptr_UniformConstant__arr_13_uint_1 = OpTypePointer UniformConstant %_arr_13_uint_1 +%samplers = OpVariable %_ptr_UniformConstant__arr_13_uint_1 UniformConstant +%int = OpTypeInt 32 1 +%int_0 = OpConstant %int 0 +%_ptr_UniformConstant_13 = OpTypePointer UniformConstant %13 +%v3float = OpTypeVector %float 3 +%float_0 = OpConstant %float 0 +%26 = OpConstantComposite %v3float %float_0 %float_0 %float_0 +%uint_0 = OpConstant %uint 0 +%_ptr_Function_float = OpTypePointer Function %float +%main = OpFunction %void None %3 +%5 = OpLabel +%36 = OpVariable %_ptr_Function_v4float Function +%38 = OpAccessChain %_ptr_UniformConstant_13 %samplers %int_0 +%39 = OpLoad %13 %38 +%40 = OpImageSampleExplicitLod %v4float %39 %26 Lod %float_0 +OpStore %36 %40 +%41 = OpAccessChain %_ptr_Function_float %36 %uint_0 +%42 = OpLoad %float %41 +%43 = OpExtInst %void %33 1 %28 %42 +OpReturn +OpFunctionEnd +%foo_ = OpFunction %void None %3 +%7 = OpLabel +%c = OpVariable %_ptr_Function_v4float Function +%22 = OpAccessChain %_ptr_UniformConstant_13 %samplers %int_0 +%23 = OpLoad %13 %22 +%27 = OpImageSampleExplicitLod %v4float %23 %26 Lod %float_0 +OpStore %c %27 +%31 = OpAccessChain %_ptr_Function_float %c %uint_0 +%32 = OpLoad %float %31 +%34 = OpExtInst %void %33 1 %28 %32 +OpReturn +OpFunctionEnd +)"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SinglePassRunAndMatch(text, true); +} + } // namespace } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/eliminate_dead_member_test.cpp b/third_party/spirv-tools/test/opt/eliminate_dead_member_test.cpp index a9b0f28c74..7728782e70 100644 --- a/third_party/spirv-tools/test/opt/eliminate_dead_member_test.cpp +++ b/third_party/spirv-tools/test/opt/eliminate_dead_member_test.cpp @@ -1184,4 +1184,86 @@ TEST_F(EliminateDeadMemberTest, UpdateSpecConstOpInsert) { SinglePassRunAndMatch(text, true); } +TEST_F(EliminateDeadMemberTest, 8BitIndexNoChange) { + // Test that the pass does not crash when an 8 bit index is used in an + // OpAccessChain. No change is expected. + const std::string text = R"( + OpCapability ImageQuery + OpCapability Int8 + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %1 "OpnSeman/" %2 + OpExecutionMode %1 OriginUpperLeft + %void = OpTypeVoid + %4 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %_struct_7 = OpTypeStruct %v4float +%_ptr_Function__struct_7 = OpTypePointer Function %_struct_7 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %10 = OpTypeFunction %v4float %_ptr_Function__struct_7 + %char = OpTypeInt 8 1 + %char_0 = OpConstant %char 0 +%_ptr_Function_v4float = OpTypePointer Function %v4float + %2 = OpVariable %_ptr_Output_v4float Output + %1 = OpFunction %void None %4 + %14 = OpLabel + %15 = OpVariable %_ptr_Function__struct_7 Function + %16 = OpFunctionCall %v4float %17 %15 + OpReturn + OpFunctionEnd + %17 = OpFunction %v4float DontInline %10 + %18 = OpFunctionParameter %_ptr_Function__struct_7 + %19 = OpLabel + %20 = OpAccessChain %_ptr_Function_v4float %18 %char_0 + %21 = OpLoad %v4float %20 + OpReturnValue %21 + OpFunctionEnd +)"; + + auto result = SinglePassRunAndDisassemble( + text, /* skip_nop = */ true, /* do_validation = */ true); + EXPECT_EQ(opt::Pass::Status::SuccessWithoutChange, std::get<1>(result)); +} + +TEST_F(EliminateDeadMemberTest, 8BitIndexWithChange) { + // Test that the pass does not crash when an 8 bit index is used in an + // OpAccessChain. The index in the access change should be changed to 0. + const std::string text = R"( + OpCapability ImageQuery + OpCapability Int8 + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %1 "OpnSeman/" %2 + OpExecutionMode %1 OriginUpperLeft + %void = OpTypeVoid + %4 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %_struct_7 = OpTypeStruct %v4float %v4float +%_ptr_Function__struct_7 = OpTypePointer Function %_struct_7 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %10 = OpTypeFunction %v4float %_ptr_Function__struct_7 + %char = OpTypeInt 8 1 + %char_1 = OpConstant %char 1 +%_ptr_Function_v4float = OpTypePointer Function %v4float + %2 = OpVariable %_ptr_Output_v4float Output + %1 = OpFunction %void None %4 + %14 = OpLabel + %15 = OpVariable %_ptr_Function__struct_7 Function + %16 = OpFunctionCall %v4float %17 %15 + OpReturn + OpFunctionEnd + %17 = OpFunction %v4float DontInline %10 +; CHECK: [[param:%\w+]] = OpFunctionParameter + %18 = OpFunctionParameter %_ptr_Function__struct_7 + %19 = OpLabel +; CHECK: OpAccessChain %_ptr_Function_v4float [[param]] %uint_0 + %20 = OpAccessChain %_ptr_Function_v4float %18 %char_1 + %21 = OpLoad %v4float %20 + OpReturnValue %21 + OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, true); +} + } // namespace diff --git a/third_party/spirv-tools/test/opt/fix_storage_class_test.cpp b/third_party/spirv-tools/test/opt/fix_storage_class_test.cpp index 4c8504ae12..1c0101a0e6 100644 --- a/third_party/spirv-tools/test/opt/fix_storage_class_test.cpp +++ b/third_party/spirv-tools/test/opt/fix_storage_class_test.cpp @@ -528,6 +528,48 @@ TEST_F(FixStorageClassTest, FixLinkedAccessChain2) { SinglePassRunAndMatch(text, false); } +TEST_F(FixStorageClassTest, AllowImageFormatMismatch) { + const std::string text = R"(OpCapability Shader +OpCapability SampledBuffer +OpCapability ImageBuffer +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 1 1 1 +OpSource HLSL 600 +OpName %type_buffer_image "type.buffer.image" +OpName %Buf "Buf" +OpName %main "main" +OpName %src_main "src.main" +OpName %bb_entry "bb.entry" +OpName %type_buffer_image_0 "type.buffer.image" +OpName %b "b" +OpDecorate %Buf DescriptorSet 0 +OpDecorate %Buf Binding 0 +%float = OpTypeFloat 32 +%type_buffer_image = OpTypeImage %float Buffer 2 0 0 2 Rgba16f +%_ptr_UniformConstant_type_buffer_image = OpTypePointer UniformConstant %type_buffer_image +%void = OpTypeVoid +%11 = OpTypeFunction %void +%type_buffer_image_0 = OpTypeImage %float Buffer 2 0 0 2 Rgba32f +%_ptr_Function_type_buffer_image_0 = OpTypePointer Function %type_buffer_image_0 +%Buf = OpVariable %_ptr_UniformConstant_type_buffer_image UniformConstant +%main = OpFunction %void None %11 +%13 = OpLabel +%14 = OpFunctionCall %void %src_main +OpReturn +OpFunctionEnd +%src_main = OpFunction %void None %11 +%bb_entry = OpLabel +%b = OpVariable %_ptr_Function_type_buffer_image_0 Function +%15 = OpLoad %type_buffer_image %Buf +OpStore %b %15 +OpReturn +OpFunctionEnd +)"; + + SinglePassRunAndCheck(text, text, false, false); +} + using FixTypeTest = PassTest<::testing::Test>; TEST_F(FixTypeTest, FixAccessChain) { diff --git a/third_party/spirv-tools/test/opt/fold_test.cpp b/third_party/spirv-tools/test/opt/fold_test.cpp index bb6098ccc1..8457bbfe63 100644 --- a/third_party/spirv-tools/test/opt/fold_test.cpp +++ b/third_party/spirv-tools/test/opt/fold_test.cpp @@ -141,6 +141,7 @@ OpName %main "main" %v4int = OpTypeVector %int 4 %v4float = OpTypeVector %float 4 %v4double = OpTypeVector %double 4 +%v2uint = OpTypeVector %uint 2 %v2float = OpTypeVector %float 2 %v2double = OpTypeVector %double 2 %v2half = OpTypeVector %half 2 @@ -191,6 +192,7 @@ OpName %main "main" %v2int_2_3 = OpConstantComposite %v2int %int_2 %int_3 %v2int_3_2 = OpConstantComposite %v2int %int_3 %int_2 %v2int_4_4 = OpConstantComposite %v2int %int_4 %int_4 +%v2int_min_max = OpConstantComposite %v2int %int_min %int_max %v2bool_null = OpConstantNull %v2bool %v2bool_true_false = OpConstantComposite %v2bool %true %false %v2bool_false_true = OpConstantComposite %v2bool %false %true @@ -258,6 +260,15 @@ OpName %main "main" %v4double_1_1_1_0p5 = OpConstantComposite %v4double %double_1 %double_1 %double_1 %double_0p5 %v4double_null = OpConstantNull %v4double %v4float_n1_2_1_3 = OpConstantComposite %v4float %float_n1 %float_2 %float_1 %float_3 +%uint_0x3f800000 = OpConstant %uint 0x3f800000 +%uint_0xbf800000 = OpConstant %uint 0xbf800000 +%v2uint_0x3f800000_0xbf800000 = OpConstantComposite %v2uint %uint_0x3f800000 %uint_0xbf800000 +%long_0xbf8000003f800000 = OpConstant %long 0xbf8000003f800000 +%int_0x3FF00000 = OpConstant %int 0x3FF00000 +%int_0x00000000 = OpConstant %int 0x00000000 +%int_0xC05FD666 = OpConstant %int 0xC05FD666 +%int_0x66666666 = OpConstant %int 0x66666666 +%v4int_0x3FF00000_0x00000000_0xC05FD666_0x66666666 = OpConstantComposite %v4int %int_0x00000000 %int_0x3FF00000 %int_0x66666666 %int_0xC05FD666 )"; return header; @@ -708,7 +719,31 @@ INSTANTIATE_TEST_SUITE_P(TestCase, IntegerInstructionFoldingTest, "%2 = OpExtInst %uint %1 UClamp %uint_2 %undef %uint_1\n" + "OpReturn\n" + "OpFunctionEnd", - 2, 1) + 2, 1), + // Test case 46: Bit-cast int 0 to unsigned int + InstructionFoldingCase( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%2 = OpBitcast %uint %int_0\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, 0), + // Test case 47: Bit-cast int -24 to unsigned int + InstructionFoldingCase( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%2 = OpBitcast %uint %int_n24\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, static_cast(-24)), + // Test case 48: Bit-cast float 1.0f to unsigned int + InstructionFoldingCase( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%2 = OpBitcast %uint %float_1\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, static_cast(0x3f800000)) )); // clang-format on @@ -790,10 +825,72 @@ INSTANTIATE_TEST_SUITE_P(TestCase, IntVectorInstructionFoldingTest, "%2 = OpVectorShuffle %v2int %v2int_null %v2int_2_3 0 4294967295 \n" + "OpReturn\n" + "OpFunctionEnd", - 2, {0,0}) + 2, {0,0}), + // Test case 4: fold bit-cast int -24 to unsigned int + InstructionFoldingCase>( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%n = OpVariable %_ptr_int Function\n" + + "%load = OpLoad %int %n\n" + + "%2 = OpBitcast %v2uint %v2int_min_max\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, {2147483648, 2147483647}) )); // clang-format on +using DoubleVectorInstructionFoldingTest = + ::testing::TestWithParam>>; + +TEST_P(DoubleVectorInstructionFoldingTest, Case) { + const auto& tc = GetParam(); + + // Build module. + std::unique_ptr context = + BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, tc.test_body, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + ASSERT_NE(nullptr, context); + + // Fold the instruction to test. + analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr(); + Instruction* inst = def_use_mgr->GetDef(tc.id_to_fold); + bool succeeded = context->get_instruction_folder().FoldInstruction(inst); + + // Make sure the instruction folded as expected. + EXPECT_TRUE(succeeded); + if (succeeded && inst != nullptr) { + EXPECT_EQ(inst->opcode(), SpvOpCopyObject); + inst = def_use_mgr->GetDef(inst->GetSingleWordInOperand(0)); + std::vector opcodes = {SpvOpConstantComposite}; + EXPECT_THAT(opcodes, Contains(inst->opcode())); + analysis::ConstantManager* const_mrg = context->get_constant_mgr(); + const analysis::Constant* result = const_mrg->GetConstantFromInst(inst); + EXPECT_NE(result, nullptr); + if (result != nullptr) { + const std::vector& componenets = + result->AsVectorConstant()->GetComponents(); + EXPECT_EQ(componenets.size(), tc.expected_result.size()); + for (size_t i = 0; i < componenets.size(); i++) { + EXPECT_EQ(tc.expected_result[i], componenets[i]->GetDouble()); + } + } + } +} + +// clang-format off +INSTANTIATE_TEST_SUITE_P(TestCase, DoubleVectorInstructionFoldingTest, +::testing::Values( + // Test case 0: bit-cast int {0x3FF00000,0x00000000,0xC05FD666,0x66666666} + // to double vector + InstructionFoldingCase>( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%2 = OpBitcast %v2double %v4int_0x3FF00000_0x00000000_0xC05FD666_0x66666666\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, {1.0,-127.35}) +)); + using FloatVectorInstructionFoldingTest = ::testing::TestWithParam>>; @@ -843,7 +940,24 @@ INSTANTIATE_TEST_SUITE_P(TestCase, FloatVectorInstructionFoldingTest, "%2 = OpExtInst %v2float %1 FMix %v2float_2_3 %v2float_0_0 %v2float_0p2_0p5\n" + "OpReturn\n" + "OpFunctionEnd", - 2, {1.6f,1.5f}) + 2, {1.6f,1.5f}), + // Test case 1: bit-cast unsigned int vector {0x3f800000, 0xbf800000} to + // float vector + InstructionFoldingCase>( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%2 = OpBitcast %v2float %v2uint_0x3f800000_0xbf800000\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, {1.0f,-1.0f}), + // Test case 2: bit-cast long int 0xbf8000003f800000 to float vector + InstructionFoldingCase>( + Header() + "%main = OpFunction %void None %void_func\n" + + "%main_lab = OpLabel\n" + + "%2 = OpBitcast %v2float %long_0xbf8000003f800000\n" + + "OpReturn\n" + + "OpFunctionEnd", + 2, {1.0f,-1.0f}) )); // clang-format on using BooleanInstructionFoldingTest = diff --git a/third_party/spirv-tools/test/opt/generate_webgpu_initializers_test.cpp b/third_party/spirv-tools/test/opt/generate_webgpu_initializers_test.cpp deleted file mode 100644 index 4aab2ce21f..0000000000 --- a/third_party/spirv-tools/test/opt/generate_webgpu_initializers_test.cpp +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include - -#include "test/opt/pass_fixture.h" -#include "test/opt/pass_utils.h" - -namespace spvtools { -namespace opt { -namespace { - -typedef std::tuple GenerateWebGPUInitializersParam; - -using GlobalVariableTest = - PassTest<::testing::TestWithParam>; -using LocalVariableTest = - PassTest<::testing::TestWithParam>; - -using GenerateWebGPUInitializersTest = PassTest<::testing::Test>; - -void operator+=(std::vector& lhs, const char* rhs) { - lhs.push_back(rhs); -} - -void operator+=(std::vector& lhs, - const std::vector& rhs) { - lhs.reserve(lhs.size() + rhs.size()); - for (auto* c : rhs) lhs.push_back(c); -} - -std::string GetGlobalVariableTestString(std::string ptr_str, - std::string var_str, - std::string const_str = "") { - std::vector result = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - ptr_str.c_str()}; - // clang-format on - - if (!const_str.empty()) result += const_str.c_str(); - - result += { - // clang-format off - var_str.c_str(), - "%uint_0 = OpConstant %uint 0", - "%void = OpTypeVoid", - "%7 = OpTypeFunction %void", - "%1 = OpFunction %void None %7", - "%8 = OpLabel", - "OpStore %4 %uint_0", - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - return JoinAllInsts(result); -} - -std::string GetPointerString(std::string storage_type) { - std::string result = "%_ptr_"; - result += storage_type + "_uint = OpTypePointer "; - result += storage_type + " %uint"; - return result; -} - -std::string GetGlobalVariableString(std::string storage_type, - bool initialized) { - std::string result = "%4 = OpVariable %_ptr_"; - result += storage_type + "_uint "; - result += storage_type; - if (initialized) result += " %9"; - return result; -} - -std::string GetUninitializedGlobalVariableTestString(std::string storage_type) { - return GetGlobalVariableTestString( - GetPointerString(storage_type), - GetGlobalVariableString(storage_type, false)); -} - -std::string GetNullConstantString() { return "%9 = OpConstantNull %uint"; } - -std::string GetInitializedGlobalVariableTestString(std::string storage_type) { - return GetGlobalVariableTestString( - GetPointerString(storage_type), - GetGlobalVariableString(storage_type, true), GetNullConstantString()); -} - -TEST_P(GlobalVariableTest, Check) { - std::string storage_class = std::get<0>(GetParam()); - bool changed = std::get<1>(GetParam()); - std::string input = GetUninitializedGlobalVariableTestString(storage_class); - std::string expected = - changed ? GetInitializedGlobalVariableTestString(storage_class) : input; - - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -// clang-format off -INSTANTIATE_TEST_SUITE_P( - GenerateWebGPUInitializers, GlobalVariableTest, - ::testing::ValuesIn(std::vector({ - std::make_tuple("Private", true), - std::make_tuple("Output", true), - std::make_tuple("Function", true), - std::make_tuple("UniformConstant", false), - std::make_tuple("Input", false), - std::make_tuple("Uniform", false), - std::make_tuple("Workgroup", false) - }))); -// clang-format on - -std::string GetLocalVariableTestString(std::string ptr_str, std::string var_str, - std::string const_str = "") { - std::vector result = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - ptr_str.c_str(), - "%uint_0 = OpConstant %uint 0", - "%void = OpTypeVoid", - "%6 = OpTypeFunction %void"}; - // clang-format on - - if (!const_str.empty()) result += const_str.c_str(); - - result += { - // clang-format off - "%1 = OpFunction %void None %6", - "%7 = OpLabel", - var_str.c_str(), - "OpStore %8 %uint_0" - // clang-format on - }; - return JoinAllInsts(result); -} - -std::string GetLocalVariableString(std::string storage_type, bool initialized) { - std::string result = "%8 = OpVariable %_ptr_"; - result += storage_type + "_uint "; - result += storage_type; - if (initialized) result += " %9"; - return result; -} - -std::string GetUninitializedLocalVariableTestString(std::string storage_type) { - return GetLocalVariableTestString( - GetPointerString(storage_type), - GetLocalVariableString(storage_type, false)); -} - -std::string GetInitializedLocalVariableTestString(std::string storage_type) { - return GetLocalVariableTestString(GetPointerString(storage_type), - GetLocalVariableString(storage_type, true), - GetNullConstantString()); -} - -TEST_P(LocalVariableTest, Check) { - std::string storage_class = std::get<0>(GetParam()); - bool changed = std::get<1>(GetParam()); - - std::string input = GetUninitializedLocalVariableTestString(storage_class); - std::string expected = - changed ? GetInitializedLocalVariableTestString(storage_class) : input; - - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -// clang-format off -INSTANTIATE_TEST_SUITE_P( - GenerateWebGPUInitializers, LocalVariableTest, - ::testing::ValuesIn(std::vector({ - std::make_tuple("Private", true), - std::make_tuple("Output", true), - std::make_tuple("Function", true), - std::make_tuple("UniformConstant", false), - std::make_tuple("Input", false), - std::make_tuple("Uniform", false), - std::make_tuple("Workgroup", false) - }))); -// clang-format on - -TEST_F(GenerateWebGPUInitializersTest, AlreadyInitializedUnchanged) { - std::vector spirv = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - "%_ptr_Private_uint = OpTypePointer Private %uint", - "%uint_0 = OpConstant %uint 0", - "%5 = OpVariable %_ptr_Private_uint Private %uint_0", - "%void = OpTypeVoid", - "%7 = OpTypeFunction %void", - "%1 = OpFunction %void None %7", - "%8 = OpLabel", - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - std::string str = JoinAllInsts(spirv); - - SinglePassRunAndCheck(str, str, - /* skip_nop = */ false); -} - -TEST_F(GenerateWebGPUInitializersTest, AmbigiousArrays) { - std::vector input_spirv = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - "%uint_2 = OpConstant %uint 2", - "%_arr_uint_uint_2 = OpTypeArray %uint %uint_2", - "%_arr_uint_uint_2_0 = OpTypeArray %uint %uint_2", - "%_ptr_Private__arr_uint_uint_2 = OpTypePointer Private %_arr_uint_uint_2", -"%_ptr_Private__arr_uint_uint_2_0 = OpTypePointer Private %_arr_uint_uint_2_0", - "%8 = OpConstantNull %_arr_uint_uint_2_0", - "%9 = OpVariable %_ptr_Private__arr_uint_uint_2 Private", - "%10 = OpVariable %_ptr_Private__arr_uint_uint_2_0 Private %8", - "%void = OpTypeVoid", - "%12 = OpTypeFunction %void", - "%1 = OpFunction %void None %12", - "%13 = OpLabel", - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - std::string input_str = JoinAllInsts(input_spirv); - - std::vector expected_spirv = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - "%uint_2 = OpConstant %uint 2", - "%_arr_uint_uint_2 = OpTypeArray %uint %uint_2", - "%_arr_uint_uint_2_0 = OpTypeArray %uint %uint_2", - "%_ptr_Private__arr_uint_uint_2 = OpTypePointer Private %_arr_uint_uint_2", -"%_ptr_Private__arr_uint_uint_2_0 = OpTypePointer Private %_arr_uint_uint_2_0", - "%8 = OpConstantNull %_arr_uint_uint_2_0", - "%14 = OpConstantNull %_arr_uint_uint_2", - "%9 = OpVariable %_ptr_Private__arr_uint_uint_2 Private %14", - "%10 = OpVariable %_ptr_Private__arr_uint_uint_2_0 Private %8", - "%void = OpTypeVoid", - "%12 = OpTypeFunction %void", - "%1 = OpFunction %void None %12", - "%13 = OpLabel", - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - std::string expected_str = JoinAllInsts(expected_spirv); - - SinglePassRunAndCheck(input_str, expected_str, - /* skip_nop = */ false); -} - -TEST_F(GenerateWebGPUInitializersTest, AmbigiousStructs) { - std::vector input_spirv = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - "%_struct_3 = OpTypeStruct %uint", - "%_struct_4 = OpTypeStruct %uint", -"%_ptr_Private__struct_3 = OpTypePointer Private %_struct_3", -"%_ptr_Private__struct_4 = OpTypePointer Private %_struct_4", - "%7 = OpConstantNull %_struct_3", - "%8 = OpVariable %_ptr_Private__struct_3 Private %7", - "%9 = OpVariable %_ptr_Private__struct_4 Private", - "%void = OpTypeVoid", - "%11 = OpTypeFunction %void", - "%1 = OpFunction %void None %11", - "%12 = OpLabel", - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - std::string input_str = JoinAllInsts(input_spirv); - - std::vector expected_spirv = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - "%_struct_3 = OpTypeStruct %uint", - "%_struct_4 = OpTypeStruct %uint", -"%_ptr_Private__struct_3 = OpTypePointer Private %_struct_3", -"%_ptr_Private__struct_4 = OpTypePointer Private %_struct_4", - "%7 = OpConstantNull %_struct_3", - "%8 = OpVariable %_ptr_Private__struct_3 Private %7", - "%13 = OpConstantNull %_struct_4", - "%9 = OpVariable %_ptr_Private__struct_4 Private %13", - "%void = OpTypeVoid", - "%11 = OpTypeFunction %void", - "%1 = OpFunction %void None %11", - "%12 = OpLabel", - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - std::string expected_str = JoinAllInsts(expected_spirv); - - SinglePassRunAndCheck(input_str, expected_str, - /* skip_nop = */ false); -} - -} // namespace -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/graphics_robust_access_test.cpp b/third_party/spirv-tools/test/opt/graphics_robust_access_test.cpp index 4b2cd447fc..3c23347d02 100644 --- a/third_party/spirv-tools/test/opt/graphics_robust_access_test.cpp +++ b/third_party/spirv-tools/test/opt/graphics_robust_access_test.cpp @@ -1548,6 +1548,105 @@ OpFunctionEnd true); } +TEST_F(GraphicsRobustAccessTest, ReplaceIndexReportsChanged) { + // A ClusterFuzz generated shader that triggered a + // "Binary size unexpectedly changed despite the optimizer saying there was no + // change" assertion. + // See https://github.com/KhronosGroup/SPIRV-Tools/issues/4166. + std::string shader = R"( +; SPIR-V +; Version: 1.0 +; Generator: Google Shaderc over Glslang; 245 +; Bound: 41 +; Schema: 0 + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "else" %gl_GlobalInvocationID + OpExecutionMode %main LocalSize 1 1 3338665985 + OpSource GLSL 450 + OpSourceExtension "GL_GOOGLE_cpp_style_line_directive" + OpSourceExtension "GL_GOOGLE_include_directive" + OpName %main "main" + OpName %index "index" + OpName %gl_GlobalInvocationID "gl_GlobalInvocationID" + OpName %S "S" + OpMemberName %_struct_24 0 "" + OpMemberName %_struct_24 1 "" + OpName %Dst "Dst" + OpMemberName %Dst 0 "s" + OpName %dst "dst" + OpName %Src "Src" + OpMemberName %Src 0 "s" + OpName %src "src" + OpDecorate %gl_GlobalInvocationID BuiltIn GlobalInvocationId + OpMemberDecorate %_struct_24 0 Offset 64 + OpMemberDecorate %_struct_24 1 Offset 8 + OpDecorate %_arr__struct_24_uint_1 ArrayStride 16 + OpMemberDecorate %Dst 0 Offset 0 + OpDecorate %Dst BufferBlock + OpDecorate %dst DescriptorSet 0 + OpDecorate %dst Binding 1 + OpDecorate %_arr__struct_24_uint_1_0 ArrayStride 16 + OpMemberDecorate %Src 0 Offset 0 + OpDecorate %Src Block + OpDecorate %src DescriptorSet 0 + OpDecorate %src Binding 0 + %void = OpTypeVoid + %3 = OpTypeFunction %void + %uint = OpTypeInt 32 0 +%_ptr_Function_uint = OpTypePointer Function %uint + %v3uint = OpTypeVector %uint 3 +%_ptr_Input_v3uint = OpTypePointer Input %v3uint +%gl_GlobalInvocationID = OpVariable %_ptr_Input_v3uint Input + %uint_4864 = OpConstant %uint 4864 +%_ptr_Input_uint = OpTypePointer Input %uint + %uint_1 = OpConstant %uint 1 + %bool = OpTypeBool + %v2uint = OpTypeVector %uint 2 + %_struct_24 = OpTypeStruct %_ptr_Input_uint %v2uint +%_arr__struct_24_uint_1 = OpTypeArray %_struct_24 %uint_1 + %Dst = OpTypeStruct %_arr__struct_24_uint_1 +%_ptr_Uniform_Dst = OpTypePointer Uniform %Dst + %dst = OpVariable %_ptr_Uniform_Dst Uniform + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 +%_arr__struct_24_uint_1_0 = OpTypeArray %_struct_24 %uint_1 + %Src = OpTypeStruct %_arr__struct_24_uint_1_0 +%_ptr_Uniform_Src = OpTypePointer Uniform %Src + %src = OpVariable %_ptr_Uniform_Src Uniform +%_ptr_Uniform__struct_24 = OpTypePointer Uniform %_struct_24 + %main = OpFunction %void None %3 + %5 = OpLabel + %index = OpVariable %_ptr_Function_uint Function + %14 = OpAccessChain %_ptr_Input_uint %gl_GlobalInvocationID %uint_4864 + %15 = OpLoad %uint %14 + OpStore %index %15 + %16 = OpLoad %uint %index + %S = OpUGreaterThanEqual %bool %16 %uint_1 + OpSelectionMerge %21 None + OpBranchConditional %S %20 %21 + %20 = OpLabel + OpReturn + %21 = OpLabel + %31 = OpLoad %uint %index + %36 = OpLoad %uint %index + %38 = OpAccessChain %_ptr_Uniform__struct_24 %src %int_0 %36 + %39 = OpLoad %_struct_24 %38 + %40 = OpAccessChain %_ptr_Uniform__struct_24 %dst %int_0 %31 + OpStore %40 %39 + OpReturn + OpFunctionEnd +)"; + + std::vector optimized_bin; + auto status = spvtools::opt::Pass::Status::Failure; + std::tie(optimized_bin, status) = + SinglePassRunToBinary(shader, false); + // Check whether the pass returns the correct modification indication. + EXPECT_EQ(status, spvtools::opt::Pass::Status::SuccessWithChange); +} + // TODO(dneto): Test access chain index wider than 64 bits? // TODO(dneto): Test struct access chain index wider than 64 bits? // TODO(dneto): OpImageTexelPointer diff --git a/third_party/spirv-tools/test/opt/inline_opaque_test.cpp b/third_party/spirv-tools/test/opt/inline_opaque_test.cpp index 47e0533391..8cb8925cdb 100644 --- a/third_party/spirv-tools/test/opt/inline_opaque_test.cpp +++ b/third_party/spirv-tools/test/opt/inline_opaque_test.cpp @@ -28,7 +28,7 @@ TEST_F(InlineOpaqueTest, InlineCallWithStructArgContainingSampledImage) { // Function with opaque argument is inlined. // TODO(greg-lunarg): Add HLSL code - const std::string predefs = + const std::string predefs_1 = R"(OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 @@ -47,22 +47,27 @@ OpName %sampler15 "sampler15" OpName %s0 "s0" OpName %texCoords "texCoords" OpName %param "param" -OpDecorate %sampler15 DescriptorSet 0 +)"; + + const std::string name = R"(OpName %return_value "return_value" +)"; + + const std::string predefs_2 = R"(OpDecorate %sampler15 DescriptorSet 0 %void = OpTypeVoid -%12 = OpTypeFunction %void +%13 = OpTypeFunction %void %float = OpTypeFloat 32 %v2float = OpTypeVector %float 2 %v4float = OpTypeVector %float 4 %_ptr_Output_v4float = OpTypePointer Output %v4float %outColor = OpVariable %_ptr_Output_v4float Output -%17 = OpTypeImage %float 2D 0 0 0 1 Unknown -%18 = OpTypeSampledImage %17 -%S_t = OpTypeStruct %v2float %v2float %18 +%18 = OpTypeImage %float 2D 0 0 0 1 Unknown +%19 = OpTypeSampledImage %18 +%S_t = OpTypeStruct %v2float %v2float %19 %_ptr_Function_S_t = OpTypePointer Function %S_t -%20 = OpTypeFunction %void %_ptr_Function_S_t -%_ptr_UniformConstant_18 = OpTypePointer UniformConstant %18 -%_ptr_Function_18 = OpTypePointer Function %18 -%sampler15 = OpVariable %_ptr_UniformConstant_18 UniformConstant +%21 = OpTypeFunction %void %_ptr_Function_S_t +%_ptr_UniformConstant_19 = OpTypePointer UniformConstant %19 +%_ptr_Function_19 = OpTypePointer Function %19 +%sampler15 = OpVariable %_ptr_UniformConstant_19 UniformConstant %int = OpTypeInt 32 1 %int_0 = OpConstant %int 0 %int_2 = OpConstant %int 2 @@ -72,39 +77,38 @@ OpDecorate %sampler15 DescriptorSet 0 )"; const std::string before = - R"(%main = OpFunction %void None %12 -%28 = OpLabel + R"(%main = OpFunction %void None %13 +%29 = OpLabel %s0 = OpVariable %_ptr_Function_S_t Function %param = OpVariable %_ptr_Function_S_t Function -%29 = OpLoad %v2float %texCoords -%30 = OpAccessChain %_ptr_Function_v2float %s0 %int_0 -OpStore %30 %29 -%31 = OpLoad %18 %sampler15 -%32 = OpAccessChain %_ptr_Function_18 %s0 %int_2 -OpStore %32 %31 -%33 = OpLoad %S_t %s0 -OpStore %param %33 -%34 = OpFunctionCall %void %foo_struct_S_t_vf2_vf21_ %param +%30 = OpLoad %v2float %texCoords +%31 = OpAccessChain %_ptr_Function_v2float %s0 %int_0 +OpStore %31 %30 +%32 = OpLoad %19 %sampler15 +%33 = OpAccessChain %_ptr_Function_19 %s0 %int_2 +OpStore %33 %32 +%34 = OpLoad %S_t %s0 +OpStore %param %34 +%return_value = OpFunctionCall %void %foo_struct_S_t_vf2_vf21_ %param OpReturn OpFunctionEnd )"; const std::string after = - R"(%34 = OpUndef %void -%main = OpFunction %void None %12 -%28 = OpLabel + R"(%main = OpFunction %void None %13 +%29 = OpLabel %s0 = OpVariable %_ptr_Function_S_t Function %param = OpVariable %_ptr_Function_S_t Function -%29 = OpLoad %v2float %texCoords -%30 = OpAccessChain %_ptr_Function_v2float %s0 %int_0 -OpStore %30 %29 -%31 = OpLoad %18 %sampler15 -%32 = OpAccessChain %_ptr_Function_18 %s0 %int_2 -OpStore %32 %31 -%33 = OpLoad %S_t %s0 -OpStore %param %33 -%42 = OpAccessChain %_ptr_Function_18 %param %int_2 -%43 = OpLoad %18 %42 +%30 = OpLoad %v2float %texCoords +%31 = OpAccessChain %_ptr_Function_v2float %s0 %int_0 +OpStore %31 %30 +%32 = OpLoad %19 %sampler15 +%33 = OpAccessChain %_ptr_Function_19 %s0 %int_2 +OpStore %33 %32 +%34 = OpLoad %S_t %s0 +OpStore %param %34 +%42 = OpAccessChain %_ptr_Function_19 %param %int_2 +%43 = OpLoad %19 %42 %44 = OpAccessChain %_ptr_Function_v2float %param %int_0 %45 = OpLoad %v2float %44 %46 = OpImageSampleImplicitLod %v4float %43 %45 @@ -114,11 +118,11 @@ OpFunctionEnd )"; const std::string post_defs = - R"(%foo_struct_S_t_vf2_vf21_ = OpFunction %void None %20 + R"(%foo_struct_S_t_vf2_vf21_ = OpFunction %void None %21 %s = OpFunctionParameter %_ptr_Function_S_t %35 = OpLabel -%36 = OpAccessChain %_ptr_Function_18 %s %int_2 -%37 = OpLoad %18 %36 +%36 = OpAccessChain %_ptr_Function_19 %s %int_2 +%37 = OpLoad %19 %36 %38 = OpAccessChain %_ptr_Function_v2float %s %int_0 %39 = OpLoad %v2float %38 %40 = OpImageSampleImplicitLod %v4float %37 %39 @@ -128,7 +132,8 @@ OpFunctionEnd )"; SinglePassRunAndCheck( - predefs + before + post_defs, predefs + after + post_defs, true, true); + predefs_1 + name + predefs_2 + before + post_defs, + predefs_1 + predefs_2 + after + post_defs, true, true); } TEST_F(InlineOpaqueTest, InlineOpaqueReturn) { @@ -290,8 +295,7 @@ OpFunctionEnd )"; const std::string after = - R"(%35 = OpUndef %void -%main2 = OpFunction %void None %13 + R"(%main2 = OpFunction %void None %13 %29 = OpLabel %s0 = OpVariable %_ptr_Function_S_t Function %param = OpVariable %_ptr_Function_S_t Function diff --git a/third_party/spirv-tools/test/opt/inline_test.cpp b/third_party/spirv-tools/test/opt/inline_test.cpp index c0ca6da7f4..2939901338 100644 --- a/third_party/spirv-tools/test/opt/inline_test.cpp +++ b/third_party/spirv-tools/test/opt/inline_test.cpp @@ -381,7 +381,6 @@ TEST_F(InlineTest, InOutParameter) { const std::vector after = { // clang-format off - "%26 = OpUndef %void", "%main = OpFunction %void None %11", "%23 = OpLabel", "%b = OpVariable %_ptr_Function_v4float Function", @@ -1543,11 +1542,9 @@ OpReturn OpFunctionEnd )"; - const std::string undef = "%11 = OpUndef %void\n"; - - SinglePassRunAndCheck( - predefs + nonEntryFuncs + before, predefs + undef + nonEntryFuncs + after, - false, true); + SinglePassRunAndCheck(predefs + nonEntryFuncs + before, + predefs + nonEntryFuncs + after, + false, true); } TEST_F(InlineTest, MultiBlockLoopHeaderCallsMultiBlockCallee) { @@ -1622,10 +1619,9 @@ OpReturn OpFunctionEnd )"; - const std::string undef = "%20 = OpUndef %void\n"; - SinglePassRunAndCheck( - predefs + nonEntryFuncs + before, predefs + undef + nonEntryFuncs + after, - false, true); + SinglePassRunAndCheck(predefs + nonEntryFuncs + before, + predefs + nonEntryFuncs + after, + false, true); } TEST_F(InlineTest, SingleBlockLoopCallsMultiBlockCalleeHavingSelectionMerge) { @@ -1711,10 +1707,9 @@ OpBranchConditional %true %13 %16 OpReturn OpFunctionEnd )"; - const std::string undef = "%15 = OpUndef %void\n"; - SinglePassRunAndCheck( - predefs + nonEntryFuncs + before, predefs + undef + nonEntryFuncs + after, - false, true); + SinglePassRunAndCheck(predefs + nonEntryFuncs + before, + predefs + nonEntryFuncs + after, + false, true); } TEST_F(InlineTest, @@ -1793,10 +1788,9 @@ OpReturn OpFunctionEnd )"; - const std::string undef = "%20 = OpUndef %void\n"; - SinglePassRunAndCheck( - predefs + nonEntryFuncs + before, predefs + undef + nonEntryFuncs + after, - false, true); + SinglePassRunAndCheck(predefs + nonEntryFuncs + before, + predefs + nonEntryFuncs + after, + false, true); } TEST_F(InlineTest, NonInlinableCalleeWithSingleReturn) { @@ -2169,7 +2163,6 @@ OpName %foo "foo" OpName %foo_entry "foo_entry" %void = OpTypeVoid %void_fn = OpTypeFunction %void -%3 = OpUndef %void %foo = OpFunction %void None %void_fn %foo_entry = OpLabel OpReturn @@ -2475,7 +2468,6 @@ OpName %kill_ "kill(" %3 = OpTypeFunction %void %bool = OpTypeBool %true = OpConstantTrue %bool -%16 = OpUndef %void %main = OpFunction %void None %3 %5 = OpLabel OpKill @@ -2573,7 +2565,6 @@ OpName %kill_ "kill(" %3 = OpTypeFunction %void %bool = OpTypeBool %true = OpConstantTrue %bool -%16 = OpUndef %void %main = OpFunction %void None %3 %5 = OpLabel OpTerminateInvocation @@ -2590,6 +2581,63 @@ OpFunctionEnd SinglePassRunAndCheck(before, after, false, true); } +TEST_F(InlineTest, InlineFuncWithOpTerminateRayNotInContinue) { + const std::string text = + R"( + OpCapability RayTracingKHR + OpExtension "SPV_KHR_ray_tracing" + OpMemoryModel Logical GLSL450 + OpEntryPoint AnyHitKHR %MyAHitMain2 "MyAHitMain2" %a + OpSource HLSL 630 + OpName %a "a" + OpName %MyAHitMain2 "MyAHitMain2" + OpName %param_var_a "param.var.a" + OpName %src_MyAHitMain2 "src.MyAHitMain2" + OpName %a_0 "a" + OpName %bb_entry "bb.entry" + %int = OpTypeInt 32 1 +%_ptr_IncomingRayPayloadKHR_int = OpTypePointer IncomingRayPayloadKHR %int + %void = OpTypeVoid + %6 = OpTypeFunction %void +%_ptr_Function_int = OpTypePointer Function %int + %14 = OpTypeFunction %void %_ptr_Function_int + %a = OpVariable %_ptr_IncomingRayPayloadKHR_int IncomingRayPayloadKHR +%MyAHitMain2 = OpFunction %void None %6 + %7 = OpLabel +%param_var_a = OpVariable %_ptr_Function_int Function + %10 = OpLoad %int %a + OpStore %param_var_a %10 + %11 = OpFunctionCall %void %src_MyAHitMain2 %param_var_a + %13 = OpLoad %int %param_var_a + OpStore %a %13 + OpReturn + OpFunctionEnd +%src_MyAHitMain2 = OpFunction %void None %14 + %a_0 = OpFunctionParameter %_ptr_Function_int + %bb_entry = OpLabel + %17 = OpLoad %int %a_0 + OpStore %a %17 + OpTerminateRayKHR + OpFunctionEnd + +; CHECK: %MyAHitMain2 = OpFunction %void None +; CHECK-NEXT: OpLabel +; CHECK-NEXT: %param_var_a = OpVariable %_ptr_Function_int Function +; CHECK-NEXT: OpLoad %int %a +; CHECK-NEXT: OpStore %param_var_a {{%\d+}} +; CHECK-NEXT: OpLoad %int %param_var_a +; CHECK-NEXT: OpStore %a {{%\d+}} +; CHECK-NEXT: OpTerminateRayKHR +; CHECK-NEXT: OpLabel +; CHECK-NEXT: OpLoad %int %param_var_a +; CHECK-NEXT: OpStore %a %16 +; CHECK-NEXT: OpReturn +; CHECK-NEXT: OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, false); +} + TEST_F(InlineTest, EarlyReturnFunctionInlined) { // #version 140 // @@ -2801,7 +2849,6 @@ OpFunctionEnd %uint_0 = OpConstant %uint 0 %false = OpConstantFalse %bool %_ptr_Function_bool = OpTypePointer Function %bool -%11 = OpUndef %void %foo_ = OpFunction %void None %4 %7 = OpLabel %18 = OpVariable %_ptr_Function_bool Function %false @@ -3890,35 +3937,6 @@ OpFunctionEnd SinglePassRunAndMatch(text, true); } -TEST_F(InlineTest, UsingVoidFunctionResult) { - const std::string text = R"( -; CHECK: [[undef:%\w+]] = OpUndef %void -; CHECK: OpFunction -; CHECK: OpCopyObject %void [[undef]] -; CHECK: OpFunctionEnd - OpCapability Shader - %1 = OpExtInstImport "GLSL.std.450" - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %4 "main" - OpExecutionMode %4 OriginUpperLeft - OpSource ESSL 320 - %2 = OpTypeVoid - %3 = OpTypeFunction %2 - %4 = OpFunction %2 None %3 - %5 = OpLabel - %8 = OpFunctionCall %2 %6 - %9 = OpCopyObject %2 %8 - OpReturn - OpFunctionEnd - %6 = OpFunction %2 None %3 - %7 = OpLabel - OpReturn - OpFunctionEnd -)"; - - SinglePassRunAndMatch(text, true); -} - // TODO(greg-lunarg): Add tests to verify handling of these cases: // // Empty modules diff --git a/third_party/spirv-tools/test/opt/inst_bindless_check_test.cpp b/third_party/spirv-tools/test/opt/inst_bindless_check_test.cpp index 67a4968c1c..1a42329b04 100644 --- a/third_party/spirv-tools/test/opt/inst_bindless_check_test.cpp +++ b/third_party/spirv-tools/test/opt/inst_bindless_check_test.cpp @@ -105,8 +105,8 @@ OpFunctionEnd )"; SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); - SinglePassRunAndCheck(before, before, true, true, 7u, - 23u, false, false); + SinglePassRunAndCheck( + before, before, true, true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, NoInstrumentNonBindless) { @@ -183,7 +183,8 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck(whole_file, whole_file, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, + false, false, false); } TEST_F(InstBindlessTest, Simple) { @@ -412,7 +413,7 @@ OpFunctionEnd func_pt2_before, entry_after + names_annots + new_annots + consts_types_vars + new_consts_types_vars + func_pt1 + func_pt2_after + output_func, - true, true, 7u, 23u, false, false); + true, true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, InstrumentMultipleInstructions) { @@ -707,7 +708,7 @@ OpFunctionEnd SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + output_func, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, InstrumentOpImage) { @@ -935,7 +936,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + output_func, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, InstrumentSampledImage) { @@ -1158,7 +1159,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + output_func, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, InstrumentImageWrite) { @@ -1383,7 +1384,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + output_func, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, InstrumentVertexSimple) { @@ -1657,7 +1658,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + output_func, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, InstrumentTeseSimple) { @@ -1933,7 +1934,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + output_func, true, - true, 7u, 23u, false, false); + true, 7u, 23u, false, false, false, false, false); } TEST_F(InstBindlessTest, MultipleDebugFunctions) { @@ -2261,7 +2262,7 @@ OpFunctionEnd SinglePassRunAndCheck( defs_before + func1_before + func2_before, defs_after + func1_after + func2_after + output_func, true, true, 7u, 23u, - false, false); + false, false, false, false, false); } TEST_F(InstBindlessTest, RuntimeArray) { @@ -2557,7 +2558,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstrumentInitCheckOnScalarDescriptor) { @@ -2793,7 +2794,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, SPV14AddToEntryPoint) { @@ -2849,7 +2850,8 @@ OpFunctionEnd )"; SetTargetEnv(SPV_ENV_VULKAN_1_1_SPIRV_1_4); - SinglePassRunAndMatch(text, true, 7u, 23u, true, true); + SinglePassRunAndMatch(text, true, 7u, 23u, true, true, + false, false, false); } TEST_F(InstBindlessTest, SPV14AddToEntryPoints) { @@ -2907,7 +2909,8 @@ OpFunctionEnd )"; SetTargetEnv(SPV_ENV_VULKAN_1_1_SPIRV_1_4); - SinglePassRunAndMatch(text, true, 7u, 23u, true, true); + SinglePassRunAndMatch(text, true, 7u, 23u, true, true, + false, false, false); } TEST_F(InstBindlessTest, InstBoundsAndInitLoadUnsizedUBOArray) { @@ -3188,7 +3191,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstBoundsAndInitLoadUnsizedSSBOArrayDeprecated) { @@ -3469,7 +3472,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstBoundsAndInitLoadUnsizedSSBOArray) { @@ -3739,7 +3742,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstInitLoadUBOScalar) { @@ -3964,7 +3967,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstBoundsInitStoreUnsizedSSBOArray) { @@ -4238,7 +4241,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstBoundsInitLoadSizedUBOArray) { @@ -4507,7 +4510,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -4829,7 +4832,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -5153,7 +5156,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -5477,7 +5480,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -5801,7 +5804,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -6125,7 +6128,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -6449,7 +6452,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, @@ -6773,7 +6776,7 @@ OpFunctionEnd // SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, InstBoundsInitSameBlockOpReplication) { @@ -7182,7 +7185,7 @@ OpFunctionEnd SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndCheck( defs_before + func_before, defs_after + func_after + new_funcs, true, - true, 7u, 23u, true, true); + true, 7u, 23u, true, true, false, false, false); } TEST_F(InstBindlessTest, MultipleUniformNonAggregateRefsNoDescInit) { @@ -7305,15 +7308,15 @@ TEST_F(InstBindlessTest, MultipleUniformNonAggregateRefsNoDescInit) { ;CHECK: %_ptr_StorageBuffer__struct_128 = OpTypePointer StorageBuffer %_struct_128 ;CHECK: %130 = OpVariable %_ptr_StorageBuffer__struct_128 StorageBuffer ;CHECK: %_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint - ;CHECK: %uint_3 = OpConstant %uint 3 + ;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %148 = OpTypeFunction %void %uint %uint %uint %uint %uint ;CHECK: %_struct_155 = OpTypeStruct %uint %_runtimearr_uint ;CHECK: %_ptr_StorageBuffer__struct_155 = OpTypePointer StorageBuffer %_struct_155 ;CHECK: %157 = OpVariable %_ptr_StorageBuffer__struct_155 StorageBuffer ;CHECK: %uint_11 = OpConstant %uint 11 - ;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %uint_23 = OpConstant %uint 23 ;CHECK: %uint_2 = OpConstant %uint 2 + ;CHECK: %uint_3 = OpConstant %uint 3 ;CHECK:%_ptr_Input_v4float = OpTypePointer Input %v4float ;CHECK:%gl_FragCoord = OpVariable %_ptr_Input_v4float Input ;CHECK: %v4uint = OpTypeVector %uint 4 @@ -7349,7 +7352,7 @@ TEST_F(InstBindlessTest, MultipleUniformNonAggregateRefsNoDescInit) { ;CHECK: %146 = OpLoad %v2float %86 ;CHECK: OpBranch %143 ;CHECK: %145 = OpLabel - ;CHECK: %201 = OpFunctionCall %void %147 %uint_71 %uint_3 %uint_0 %119 %140 + ;CHECK: %201 = OpFunctionCall %void %147 %uint_71 %uint_4 %uint_0 %119 %140 ;CHECK: OpBranch %143 ;CHECK: %143 = OpLabel ;CHECK: %203 = OpPhi %v2float %146 %144 %202 %145 @@ -7366,7 +7369,7 @@ TEST_F(InstBindlessTest, MultipleUniformNonAggregateRefsNoDescInit) { ;CHECK: %209 = OpLoad %v2float %89 ;CHECK: OpBranch %206 ;CHECK: %208 = OpLabel - ;CHECK: %211 = OpFunctionCall %void %147 %uint_75 %uint_3 %uint_0 %204 %140 + ;CHECK: %211 = OpFunctionCall %void %147 %uint_75 %uint_4 %uint_0 %204 %140 ;CHECK: OpBranch %206 ;CHECK: %206 = OpLabel ;CHECK: %212 = OpPhi %v2float %209 %207 %202 %208 @@ -7406,49 +7409,49 @@ TEST_F(InstBindlessTest, MultipleUniformNonAggregateRefsNoDescInit) { ;CHECK: %153 = OpFunctionParameter %uint ;CHECK: %154 = OpLabel ;CHECK: %158 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_0 - ;CHECK: %161 = OpAtomicIAdd %uint %158 %uint_4 %uint_0 %uint_11 - ;CHECK: %162 = OpIAdd %uint %161 %uint_11 - ;CHECK: %163 = OpArrayLength %uint %157 1 - ;CHECK: %164 = OpULessThanEqual %bool %162 %163 - ;CHECK: OpSelectionMerge %165 None - ;CHECK: OpBranchConditional %164 %166 %165 - ;CHECK: %166 = OpLabel - ;CHECK: %167 = OpIAdd %uint %161 %uint_0 - ;CHECK: %168 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %167 - ;CHECK: OpStore %168 %uint_11 - ;CHECK: %170 = OpIAdd %uint %161 %uint_1 - ;CHECK: %171 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %170 - ;CHECK: OpStore %171 %uint_23 - ;CHECK: %173 = OpIAdd %uint %161 %uint_2 - ;CHECK: %174 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %173 - ;CHECK: OpStore %174 %149 - ;CHECK: %175 = OpIAdd %uint %161 %uint_3 + ;CHECK: %160 = OpAtomicIAdd %uint %158 %uint_4 %uint_0 %uint_11 + ;CHECK: %161 = OpIAdd %uint %160 %uint_11 + ;CHECK: %162 = OpArrayLength %uint %157 1 + ;CHECK: %163 = OpULessThanEqual %bool %161 %162 + ;CHECK: OpSelectionMerge %164 None + ;CHECK: OpBranchConditional %163 %165 %164 + ;CHECK: %165 = OpLabel + ;CHECK: %166 = OpIAdd %uint %160 %uint_0 + ;CHECK: %167 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %166 + ;CHECK: OpStore %167 %uint_11 + ;CHECK: %169 = OpIAdd %uint %160 %uint_1 + ;CHECK: %170 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %169 + ;CHECK: OpStore %170 %uint_23 + ;CHECK: %172 = OpIAdd %uint %160 %uint_2 + ;CHECK: %173 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %172 + ;CHECK: OpStore %173 %149 + ;CHECK: %175 = OpIAdd %uint %160 %uint_3 ;CHECK: %176 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %175 ;CHECK: OpStore %176 %uint_4 ;CHECK: %179 = OpLoad %v4float %gl_FragCoord ;CHECK: %181 = OpBitcast %v4uint %179 ;CHECK: %182 = OpCompositeExtract %uint %181 0 - ;CHECK: %183 = OpIAdd %uint %161 %uint_4 + ;CHECK: %183 = OpIAdd %uint %160 %uint_4 ;CHECK: %184 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %183 ;CHECK: OpStore %184 %182 ;CHECK: %185 = OpCompositeExtract %uint %181 1 - ;CHECK: %187 = OpIAdd %uint %161 %uint_5 + ;CHECK: %187 = OpIAdd %uint %160 %uint_5 ;CHECK: %188 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %187 ;CHECK: OpStore %188 %185 - ;CHECK: %189 = OpIAdd %uint %161 %uint_7 + ;CHECK: %189 = OpIAdd %uint %160 %uint_7 ;CHECK: %190 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %189 ;CHECK: OpStore %190 %150 - ;CHECK: %192 = OpIAdd %uint %161 %uint_8 + ;CHECK: %192 = OpIAdd %uint %160 %uint_8 ;CHECK: %193 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %192 ;CHECK: OpStore %193 %151 - ;CHECK: %195 = OpIAdd %uint %161 %uint_9 + ;CHECK: %195 = OpIAdd %uint %160 %uint_9 ;CHECK: %196 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %195 ;CHECK: OpStore %196 %152 - ;CHECK: %198 = OpIAdd %uint %161 %uint_10 + ;CHECK: %198 = OpIAdd %uint %160 %uint_10 ;CHECK: %199 = OpAccessChain %_ptr_StorageBuffer_uint %157 %uint_1 %198 ;CHECK: OpStore %199 %153 - ;CHECK: OpBranch %165 - ;CHECK: %165 = OpLabel + ;CHECK: OpBranch %164 + ;CHECK: %164 = OpLabel ;CHECK: OpReturn ;CHECK: OpFunctionEnd )"; @@ -7456,7 +7459,7 @@ TEST_F(InstBindlessTest, MultipleUniformNonAggregateRefsNoDescInit) { SetTargetEnv(SPV_ENV_VULKAN_1_2); SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndMatch(text, true, 7u, 23u, false, - false, true); + false, true, false, true); } TEST_F(InstBindlessTest, UniformArrayRefNoDescInit) { @@ -7593,14 +7596,14 @@ TEST_F(InstBindlessTest, UniformArrayRefNoDescInit) { ;CHECK: %113 = OpVariable %_ptr_StorageBuffer__struct_111 StorageBuffer ;CHECK:%_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint ;CHECK: %bool = OpTypeBool -;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %132 = OpTypeFunction %void %uint %uint %uint %uint %uint ;CHECK:%_struct_139 = OpTypeStruct %uint %_runtimearr_uint ;CHECK:%_ptr_StorageBuffer__struct_139 = OpTypePointer StorageBuffer %_struct_139 ;CHECK: %141 = OpVariable %_ptr_StorageBuffer__struct_139 StorageBuffer ;CHECK: %uint_11 = OpConstant %uint 11 -;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_3 = OpConstant %uint 3 ;CHECK:%_ptr_Input_v4float = OpTypePointer Input %v4float ;CHECK:%gl_FragCoord = OpVariable %_ptr_Input_v4float Input ;CHECK: %v4uint = OpTypeVector %uint 4 @@ -7634,7 +7637,7 @@ TEST_F(InstBindlessTest, UniformArrayRefNoDescInit) { ;CHECK: %130 = OpLoad %v2float %81 ;CHECK: OpBranch %127 ;CHECK: %129 = OpLabel -;CHECK: %184 = OpFunctionCall %void %131 %uint_78 %uint_3 %uint_0 %101 %123 +;CHECK: %184 = OpFunctionCall %void %131 %uint_78 %uint_4 %uint_0 %101 %123 ;CHECK: OpBranch %127 ;CHECK: %127 = OpLabel ;CHECK: %186 = OpPhi %v2float %130 %128 %185 %129 @@ -7671,49 +7674,49 @@ TEST_F(InstBindlessTest, UniformArrayRefNoDescInit) { ;CHECK: %137 = OpFunctionParameter %uint ;CHECK: %138 = OpLabel ;CHECK: %142 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_0 -;CHECK: %145 = OpAtomicIAdd %uint %142 %uint_4 %uint_0 %uint_11 -;CHECK: %146 = OpIAdd %uint %145 %uint_11 -;CHECK: %147 = OpArrayLength %uint %141 1 -;CHECK: %148 = OpULessThanEqual %bool %146 %147 -;CHECK: OpSelectionMerge %149 None -;CHECK: OpBranchConditional %148 %150 %149 -;CHECK: %150 = OpLabel -;CHECK: %151 = OpIAdd %uint %145 %uint_0 -;CHECK: %152 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %151 -;CHECK: OpStore %152 %uint_11 -;CHECK: %154 = OpIAdd %uint %145 %uint_1 -;CHECK: %155 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %154 -;CHECK: OpStore %155 %uint_23 -;CHECK: %156 = OpIAdd %uint %145 %uint_2 -;CHECK: %157 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %156 -;CHECK: OpStore %157 %133 -;CHECK: %158 = OpIAdd %uint %145 %uint_3 +;CHECK: %144 = OpAtomicIAdd %uint %142 %uint_4 %uint_0 %uint_11 +;CHECK: %145 = OpIAdd %uint %144 %uint_11 +;CHECK: %146 = OpArrayLength %uint %141 1 +;CHECK: %147 = OpULessThanEqual %bool %145 %146 +;CHECK: OpSelectionMerge %148 None +;CHECK: OpBranchConditional %147 %149 %148 +;CHECK: %149 = OpLabel +;CHECK: %150 = OpIAdd %uint %144 %uint_0 +;CHECK: %151 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %150 +;CHECK: OpStore %151 %uint_11 +;CHECK: %153 = OpIAdd %uint %144 %uint_1 +;CHECK: %154 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %153 +;CHECK: OpStore %154 %uint_23 +;CHECK: %155 = OpIAdd %uint %144 %uint_2 +;CHECK: %156 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %155 +;CHECK: OpStore %156 %133 +;CHECK: %158 = OpIAdd %uint %144 %uint_3 ;CHECK: %159 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %158 ;CHECK: OpStore %159 %uint_4 ;CHECK: %162 = OpLoad %v4float %gl_FragCoord ;CHECK: %164 = OpBitcast %v4uint %162 ;CHECK: %165 = OpCompositeExtract %uint %164 0 -;CHECK: %166 = OpIAdd %uint %145 %uint_4 +;CHECK: %166 = OpIAdd %uint %144 %uint_4 ;CHECK: %167 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %166 ;CHECK: OpStore %167 %165 ;CHECK: %168 = OpCompositeExtract %uint %164 1 -;CHECK: %170 = OpIAdd %uint %145 %uint_5 +;CHECK: %170 = OpIAdd %uint %144 %uint_5 ;CHECK: %171 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %170 ;CHECK: OpStore %171 %168 -;CHECK: %172 = OpIAdd %uint %145 %uint_7 +;CHECK: %172 = OpIAdd %uint %144 %uint_7 ;CHECK: %173 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %172 ;CHECK: OpStore %173 %134 -;CHECK: %175 = OpIAdd %uint %145 %uint_8 +;CHECK: %175 = OpIAdd %uint %144 %uint_8 ;CHECK: %176 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %175 ;CHECK: OpStore %176 %135 -;CHECK: %178 = OpIAdd %uint %145 %uint_9 +;CHECK: %178 = OpIAdd %uint %144 %uint_9 ;CHECK: %179 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %178 ;CHECK: OpStore %179 %136 -;CHECK: %181 = OpIAdd %uint %145 %uint_10 +;CHECK: %181 = OpIAdd %uint %144 %uint_10 ;CHECK: %182 = OpAccessChain %_ptr_StorageBuffer_uint %141 %uint_1 %181 ;CHECK: OpStore %182 %137 -;CHECK: OpBranch %149 -;CHECK: %149 = OpLabel +;CHECK: OpBranch %148 +;CHECK: %148 = OpLabel ;CHECK: OpReturn ;CHECK: OpFunctionEnd )"; @@ -7721,7 +7724,7 @@ TEST_F(InstBindlessTest, UniformArrayRefNoDescInit) { SetTargetEnv(SPV_ENV_VULKAN_1_2); SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndMatch(text, true, 7u, 23u, false, - false, true); + false, true, false, true); } TEST_F(InstBindlessTest, UniformArrayRefWithDescInit) { @@ -7740,11 +7743,11 @@ TEST_F(InstBindlessTest, UniformArrayRefWithDescInit) { OpExecutionMode %MainPs OriginUpperLeft OpSource HLSL 500 OpName %MainPs "MainPs" - OpName %PerBatchEnvMapConstantBuffer_t -"PerBatchEnvMapConstantBuffer_t" OpMemberName %PerBatchEnvMapConstantBuffer_t 0 -"g_matEnvMapWorldToLocal" OpMemberName %PerBatchEnvMapConstantBuffer_t 1 -"g_vEnvironmentMapBoxMins" OpMemberName %PerBatchEnvMapConstantBuffer_t 2 -"g_TexOff" OpName %_BindlessFastEnvMapCB_PS_t "_BindlessFastEnvMapCB_PS_t" + OpName %PerBatchEnvMapConstantBuffer_t "PerBatchEnvMapConstantBuffer_t" + OpMemberName %PerBatchEnvMapConstantBuffer_t 0 "g_matEnvMapWorldToLocal" + OpMemberName %PerBatchEnvMapConstantBuffer_t 1 "g_vEnvironmentMapBoxMins" + OpMemberName %PerBatchEnvMapConstantBuffer_t 2 "g_TexOff" + OpName %_BindlessFastEnvMapCB_PS_t "_BindlessFastEnvMapCB_PS_t" OpMemberName %_BindlessFastEnvMapCB_PS_t 0 "g_envMapConstants" OpName %_ "" OpName %PerViewPushConst_t "PerViewPushConst_t" @@ -7828,15 +7831,15 @@ TEST_F(InstBindlessTest, UniformArrayRefWithDescInit) { ;CHECK: %113 = OpVariable %_ptr_StorageBuffer__struct_111 StorageBuffer ;CHECK:%_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint ;CHECK: %bool = OpTypeBool -;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %135 = OpTypeFunction %void %uint %uint %uint %uint %uint ;CHECK:%_struct_142 = OpTypeStruct %uint %_runtimearr_uint ;CHECK:%_ptr_StorageBuffer__struct_142 = OpTypePointer StorageBuffer %_struct_142 ;CHECK: %144 = OpVariable %_ptr_StorageBuffer__struct_142 StorageBuffer ;CHECK: %uint_11 = OpConstant %uint 11 -;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %uint_1 = OpConstant %uint 1 ;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_3 = OpConstant %uint 3 ;CHECK:%_ptr_Input_v4float = OpTypePointer Input %v4float ;CHECK:%gl_FragCoord = OpVariable %_ptr_Input_v4float Input ;CHECK: %v4uint = OpTypeVector %uint 4 @@ -7875,13 +7878,15 @@ TEST_F(InstBindlessTest, UniformArrayRefWithDescInit) { ;CHECK: %133 = OpLoad %v2float %81 ;CHECK: OpBranch %130 ;CHECK: %132 = OpLabel -;CHECK: %188 = OpFunctionCall %void %134 %uint_78 %uint_3 %uint_0 %101 %126 +;CHECK: %188 = OpFunctionCall %void %134 %uint_78 %uint_4 %uint_0 %101 %126 ;CHECK: OpBranch %130 ;CHECK: %130 = OpLabel ;CHECK: %190 = OpPhi %v2float %133 %131 %189 %132 ;CHECK: %86 = OpFAdd %v2float %66 %190 - %87 = OpLoad %46 %g_tColor %88 = OpLoad %50 %g_sAniso %89 = - OpSampledImage %54 %87 %88 %91 = OpImageSampleImplicitLod %v4float %89 %86 + %87 = OpLoad %46 %g_tColor + %88 = OpLoad %50 %g_sAniso + %89 = OpSampledImage %54 %87 %88 + %91 = OpImageSampleImplicitLod %v4float %89 %86 OpStore %_entryPointOutput_vColor %91 ;CHECK-NOT: %91 = OpImageSampleImplicitLod %v4float %89 %86 ;CHECK-NOT: OpStore %_entryPointOutput_vColor %91 @@ -7928,49 +7933,49 @@ TEST_F(InstBindlessTest, UniformArrayRefWithDescInit) { ;CHECK: %140 = OpFunctionParameter %uint ;CHECK: %141 = OpLabel ;CHECK: %145 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_0 -;CHECK: %148 = OpAtomicIAdd %uint %145 %uint_4 %uint_0 %uint_11 -;CHECK: %149 = OpIAdd %uint %148 %uint_11 -;CHECK: %150 = OpArrayLength %uint %144 1 -;CHECK: %151 = OpULessThanEqual %bool %149 %150 -;CHECK: OpSelectionMerge %152 None -;CHECK: OpBranchConditional %151 %153 %152 -;CHECK: %153 = OpLabel -;CHECK: %154 = OpIAdd %uint %148 %uint_0 -;CHECK: %156 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %154 -;CHECK: OpStore %156 %uint_11 -;CHECK: %158 = OpIAdd %uint %148 %uint_1 -;CHECK: %159 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %158 -;CHECK: OpStore %159 %uint_23 -;CHECK: %160 = OpIAdd %uint %148 %uint_2 -;CHECK: %161 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %160 -;CHECK: OpStore %161 %136 -;CHECK: %162 = OpIAdd %uint %148 %uint_3 +;CHECK: %147 = OpAtomicIAdd %uint %145 %uint_4 %uint_0 %uint_11 +;CHECK: %148 = OpIAdd %uint %147 %uint_11 +;CHECK: %149 = OpArrayLength %uint %144 1 +;CHECK: %150 = OpULessThanEqual %bool %148 %149 +;CHECK: OpSelectionMerge %151 None +;CHECK: OpBranchConditional %150 %152 %151 +;CHECK: %152 = OpLabel +;CHECK: %153 = OpIAdd %uint %147 %uint_0 +;CHECK: %155 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %153 +;CHECK: OpStore %155 %uint_11 +;CHECK: %157 = OpIAdd %uint %147 %uint_1 +;CHECK: %158 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %157 +;CHECK: OpStore %158 %uint_23 +;CHECK: %159 = OpIAdd %uint %147 %uint_2 +;CHECK: %160 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %159 +;CHECK: OpStore %160 %136 +;CHECK: %162 = OpIAdd %uint %147 %uint_3 ;CHECK: %163 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %162 ;CHECK: OpStore %163 %uint_4 ;CHECK: %166 = OpLoad %v4float %gl_FragCoord ;CHECK: %168 = OpBitcast %v4uint %166 ;CHECK: %169 = OpCompositeExtract %uint %168 0 -;CHECK: %170 = OpIAdd %uint %148 %uint_4 +;CHECK: %170 = OpIAdd %uint %147 %uint_4 ;CHECK: %171 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %170 ;CHECK: OpStore %171 %169 ;CHECK: %172 = OpCompositeExtract %uint %168 1 -;CHECK: %174 = OpIAdd %uint %148 %uint_5 +;CHECK: %174 = OpIAdd %uint %147 %uint_5 ;CHECK: %175 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %174 ;CHECK: OpStore %175 %172 -;CHECK: %176 = OpIAdd %uint %148 %uint_7 +;CHECK: %176 = OpIAdd %uint %147 %uint_7 ;CHECK: %177 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %176 ;CHECK: OpStore %177 %137 -;CHECK: %179 = OpIAdd %uint %148 %uint_8 +;CHECK: %179 = OpIAdd %uint %147 %uint_8 ;CHECK: %180 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %179 ;CHECK: OpStore %180 %138 -;CHECK: %182 = OpIAdd %uint %148 %uint_9 +;CHECK: %182 = OpIAdd %uint %147 %uint_9 ;CHECK: %183 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %182 ;CHECK: OpStore %183 %139 -;CHECK: %185 = OpIAdd %uint %148 %uint_10 +;CHECK: %185 = OpIAdd %uint %147 %uint_10 ;CHECK: %186 = OpAccessChain %_ptr_StorageBuffer_uint %144 %uint_1 %185 ;CHECK: OpStore %186 %140 -;CHECK: OpBranch %152 -;CHECK: %152 = OpLabel +;CHECK: OpBranch %151 +;CHECK: %151 = OpLabel ;CHECK: OpReturn ;CHECK: OpFunctionEnd )"; @@ -7978,7 +7983,7 @@ TEST_F(InstBindlessTest, UniformArrayRefWithDescInit) { SetTargetEnv(SPV_ENV_VULKAN_1_2); SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndMatch(text, true, 7u, 23u, true, true, - true); + true, false, true); } TEST_F(InstBindlessTest, Descriptor16BitIdxRef) { @@ -8201,7 +8206,7 @@ TEST_F(InstBindlessTest, Descriptor16BitIdxRef) { SetTargetEnv(SPV_ENV_VULKAN_1_2); SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndMatch(text, true, 7u, 23u, true, true, - false); + false, false, true); } TEST_F(InstBindlessTest, UniformArray16bitIdxRef) { @@ -8341,15 +8346,15 @@ TEST_F(InstBindlessTest, UniformArray16bitIdxRef) { ;CHECK: %69 = OpVariable %_ptr_StorageBuffer__struct_67 StorageBuffer ;CHECK:%_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint ;CHECK: %bool = OpTypeBool -;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %88 = OpTypeFunction %void %uint %uint %uint %uint %uint ;CHECK: %_struct_95 = OpTypeStruct %uint %_runtimearr_uint ;CHECK:%_ptr_StorageBuffer__struct_95 = OpTypePointer StorageBuffer %_struct_95 ;CHECK: %97 = OpVariable %_ptr_StorageBuffer__struct_95 StorageBuffer ;CHECK: %uint_11 = OpConstant %uint 11 -;CHECK: %uint_4 = OpConstant %uint 4 ;CHECK: %uint_23 = OpConstant %uint 23 ;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK: %uint_3 = OpConstant %uint 3 ;CHECK:%_ptr_Input_v4float = OpTypePointer Input %v4float ;CHECK:%gl_FragCoord = OpVariable %_ptr_Input_v4float Input ;CHECK: %v4uint = OpTypeVector %uint 4 @@ -8386,7 +8391,7 @@ TEST_F(InstBindlessTest, UniformArray16bitIdxRef) { ;CHECK: %86 = OpLoad %v2float %41 ;CHECK: OpBranch %83 ;CHECK: %85 = OpLabel -;CHECK: %141 = OpFunctionCall %void %87 %uint_81 %uint_3 %uint_0 %58 %79 +;CHECK: %141 = OpFunctionCall %void %87 %uint_81 %uint_4 %uint_0 %58 %79 ;CHECK: OpBranch %83 ;CHECK: %83 = OpLabel ;CHECK: %143 = OpPhi %v2float %86 %84 %142 %85 @@ -8421,49 +8426,49 @@ TEST_F(InstBindlessTest, UniformArray16bitIdxRef) { ;CHECK: %93 = OpFunctionParameter %uint ;CHECK: %94 = OpLabel ;CHECK: %98 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_0 -;CHECK: %101 = OpAtomicIAdd %uint %98 %uint_4 %uint_0 %uint_11 -;CHECK: %102 = OpIAdd %uint %101 %uint_11 -;CHECK: %103 = OpArrayLength %uint %97 1 -;CHECK: %104 = OpULessThanEqual %bool %102 %103 -;CHECK: OpSelectionMerge %105 None -;CHECK: OpBranchConditional %104 %106 %105 -;CHECK: %106 = OpLabel -;CHECK: %107 = OpIAdd %uint %101 %uint_0 -;CHECK: %108 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %107 -;CHECK: OpStore %108 %uint_11 -;CHECK: %110 = OpIAdd %uint %101 %uint_1 -;CHECK: %111 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %110 -;CHECK: OpStore %111 %uint_23 -;CHECK: %113 = OpIAdd %uint %101 %uint_2 -;CHECK: %114 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %113 -;CHECK: OpStore %114 %89 -;CHECK: %115 = OpIAdd %uint %101 %uint_3 +;CHECK: %100 = OpAtomicIAdd %uint %98 %uint_4 %uint_0 %uint_11 +;CHECK: %101 = OpIAdd %uint %100 %uint_11 +;CHECK: %102 = OpArrayLength %uint %97 1 +;CHECK: %103 = OpULessThanEqual %bool %101 %102 +;CHECK: OpSelectionMerge %104 None +;CHECK: OpBranchConditional %103 %105 %104 +;CHECK: %105 = OpLabel +;CHECK: %106 = OpIAdd %uint %100 %uint_0 +;CHECK: %107 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %106 +;CHECK: OpStore %107 %uint_11 +;CHECK: %109 = OpIAdd %uint %100 %uint_1 +;CHECK: %110 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %109 +;CHECK: OpStore %110 %uint_23 +;CHECK: %112 = OpIAdd %uint %100 %uint_2 +;CHECK: %113 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %112 +;CHECK: OpStore %113 %89 +;CHECK: %115 = OpIAdd %uint %100 %uint_3 ;CHECK: %116 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %115 ;CHECK: OpStore %116 %uint_4 ;CHECK: %119 = OpLoad %v4float %gl_FragCoord ;CHECK: %121 = OpBitcast %v4uint %119 ;CHECK: %122 = OpCompositeExtract %uint %121 0 -;CHECK: %123 = OpIAdd %uint %101 %uint_4 +;CHECK: %123 = OpIAdd %uint %100 %uint_4 ;CHECK: %124 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %123 ;CHECK: OpStore %124 %122 ;CHECK: %125 = OpCompositeExtract %uint %121 1 -;CHECK: %127 = OpIAdd %uint %101 %uint_5 +;CHECK: %127 = OpIAdd %uint %100 %uint_5 ;CHECK: %128 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %127 ;CHECK: OpStore %128 %125 -;CHECK: %129 = OpIAdd %uint %101 %uint_7 +;CHECK: %129 = OpIAdd %uint %100 %uint_7 ;CHECK: %130 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %129 ;CHECK: OpStore %130 %90 -;CHECK: %132 = OpIAdd %uint %101 %uint_8 +;CHECK: %132 = OpIAdd %uint %100 %uint_8 ;CHECK: %133 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %132 ;CHECK: OpStore %133 %91 -;CHECK: %135 = OpIAdd %uint %101 %uint_9 +;CHECK: %135 = OpIAdd %uint %100 %uint_9 ;CHECK: %136 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %135 ;CHECK: OpStore %136 %92 -;CHECK: %138 = OpIAdd %uint %101 %uint_10 +;CHECK: %138 = OpIAdd %uint %100 %uint_10 ;CHECK: %139 = OpAccessChain %_ptr_StorageBuffer_uint %97 %uint_1 %138 ;CHECK: OpStore %139 %93 -;CHECK: OpBranch %105 -;CHECK: %105 = OpLabel +;CHECK: OpBranch %104 +;CHECK: %104 = OpLabel ;CHECK: OpReturn ;CHECK: OpFunctionEnd )"; @@ -8471,7 +8476,1508 @@ TEST_F(InstBindlessTest, UniformArray16bitIdxRef) { SetTargetEnv(SPV_ENV_VULKAN_1_2); SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); SinglePassRunAndMatch(text, true, 7u, 23u, false, - false, true); + false, true, false, true); +} + +TEST_F(InstBindlessTest, UniformMatrixRefRowMajor) { + // The buffer-oob row major matrix check + // + // #version 450 + // #extension GL_EXT_scalar_block_layout : enable + // + // layout(location = 0) in highp vec4 a_position; + // layout(location = 0) out mediump float v_vtxResult; + // + // layout(set = 0, binding = 0, std430, row_major) uniform Block + // { + // lowp mat4x2 var; + // }; + // + // void main (void) + // { + // v_vtxResult = var[2][1]; + // } + + const std::string text = R"( + OpCapability Shader +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %main "main" %v_vtxResult %_ %a_position +;CHECK: OpEntryPoint Vertex %main "main" %v_vtxResult %_ %a_position %45 %72 %gl_VertexIndex %gl_InstanceIndex + OpSource GLSL 450 + OpSourceExtension "GL_EXT_scalar_block_layout" + OpName %main "main" + OpName %v_vtxResult "v_vtxResult" + OpName %Block "Block" + OpMemberName %Block 0 "var" + OpName %_ "" + OpName %a_position "a_position" + OpDecorate %v_vtxResult RelaxedPrecision + OpDecorate %v_vtxResult Location 0 + OpMemberDecorate %Block 0 RowMajor + OpMemberDecorate %Block 0 RelaxedPrecision + OpMemberDecorate %Block 0 Offset 0 + OpMemberDecorate %Block 0 MatrixStride 16 + OpDecorate %Block Block + OpDecorate %_ DescriptorSet 0 + OpDecorate %_ Binding 0 + OpDecorate %21 RelaxedPrecision +;CHECK-NOT: OpDecorate %21 RelaxedPrecision +;CHECK: OpDecorate %116 RelaxedPrecision + OpDecorate %a_position Location 0 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_43 Block +;CHECK: OpMemberDecorate %_struct_43 0 Offset 0 +;CHECK: OpDecorate %45 DescriptorSet 7 +;CHECK: OpDecorate %45 Binding 1 +;CHECK: OpDecorate %61 RelaxedPrecision +;CHECK: OpDecorate %_struct_70 Block +;CHECK: OpMemberDecorate %_struct_70 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_70 1 Offset 4 +;CHECK: OpDecorate %72 DescriptorSet 7 +;CHECK: OpDecorate %72 Binding 0 +;CHECK: OpDecorate %gl_VertexIndex BuiltIn VertexIndex +;CHECK: OpDecorate %gl_InstanceIndex BuiltIn InstanceIndex + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 +%_ptr_Output_float = OpTypePointer Output %float +%v_vtxResult = OpVariable %_ptr_Output_float Output + %v2float = OpTypeVector %float 2 +%mat4v2float = OpTypeMatrix %v2float 4 + %Block = OpTypeStruct %mat4v2float +%_ptr_Uniform_Block = OpTypePointer Uniform %Block + %_ = OpVariable %_ptr_Uniform_Block Uniform + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 +%_ptr_Uniform_float = OpTypePointer Uniform %float + %v4float = OpTypeVector %float 4 +%_ptr_Input_v4float = OpTypePointer Input %v4float + %a_position = OpVariable %_ptr_Input_v4float Input +;CHECK; %uint_0 = OpConstant %uint 0 +;CHECK; %uint_16 = OpConstant %uint 16 +;CHECK; %uint_4 = OpConstant %uint 4 +;CHECK; %uint_3 = OpConstant %uint 3 +;CHECK; %37 = OpTypeFunction %uint %uint %uint %uint +;CHECK;%_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK; %_struct_43 = OpTypeStruct %_runtimearr_uint +;CHECK;%_ptr_StorageBuffer__struct_43 = OpTypePointer StorageBuffer %_struct_43 +;CHECK; %45 = OpVariable %_ptr_StorageBuffer__struct_43 StorageBuffer +;CHECK;%_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK; %bool = OpTypeBool +;CHECK; %63 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK; %_struct_70 = OpTypeStruct %uint %_runtimearr_uint +;CHECK;%_ptr_StorageBuffer__struct_70 = OpTypePointer StorageBuffer %_struct_70 +;CHECK; %72 = OpVariable %_ptr_StorageBuffer__struct_70 StorageBuffer +;CHECK; %uint_11 = OpConstant %uint 11 +;CHECK; %uint_23 = OpConstant %uint 23 +;CHECK; %uint_2 = OpConstant %uint 2 +;CHECK;%_ptr_Input_uint = OpTypePointer Input %uint +;CHECK;%gl_VertexIndex = OpVariable %_ptr_Input_uint Input +;CHECK;%gl_InstanceIndex = OpVariable %_ptr_Input_uint Input +;CHECK; %uint_5 = OpConstant %uint 5 +;CHECK; %uint_7 = OpConstant %uint 7 +;CHECK; %uint_8 = OpConstant %uint 8 +;CHECK; %uint_9 = OpConstant %uint 9 +;CHECK; %uint_10 = OpConstant %uint 10 +;CHECK; %uint_45 = OpConstant %uint 45 +;CHECK; %115 = OpConstantNull %float + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: %55 = OpFunctionCall %uint %36 %uint_1 %uint_0 %uint_0 +;CHECK: OpBranch %26 +;CHECK: %26 = OpLabel +;CHECK: OpBranch %25 +;CHECK: %25 = OpLabel + %20 = OpAccessChain %_ptr_Uniform_float %_ %int_0 %int_2 %uint_1 + %21 = OpLoad %float %20 +;CHECK-NOT: %21 = OpLoad %float %20 +;CHECK: %30 = OpIMul %uint %uint_4 %int_2 +;CHECK: %31 = OpIAdd %uint %uint_0 %30 +;CHECK: %32 = OpIMul %uint %uint_16 %uint_1 +;CHECK: %33 = OpIAdd %uint %31 %32 +;CHECK: %35 = OpIAdd %uint %33 %uint_3 +;CHECK: %57 = OpULessThan %bool %35 %55 +;CHECK: OpSelectionMerge %58 None +;CHECK: OpBranchConditional %57 %59 %60 +;CHECK: %59 = OpLabel +;CHECK: %61 = OpLoad %float %20 +;CHECK: OpBranch %58 +;CHECK: %60 = OpLabel +;CHECK: %114 = OpFunctionCall %void %62 %uint_45 %uint_4 %uint_0 %35 %55 +;CHECK: OpBranch %58 +;CHECK: %58 = OpLabel +;CHECK: %116 = OpPhi %float %61 %59 %115 %60 + OpStore %v_vtxResult %21 +;CHECK-NOT: OpStore %v_vtxResult %21 +;CHECK: OpStore %v_vtxResult %116 + OpReturn + OpFunctionEnd +;CHECK: %36 = OpFunction %uint None %37 +;CHECK: %38 = OpFunctionParameter %uint +;CHECK: %39 = OpFunctionParameter %uint +;CHECK: %40 = OpFunctionParameter %uint +;CHECK: %41 = OpLabel +;CHECK: %47 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 %38 +;CHECK: %48 = OpLoad %uint %47 +;CHECK: %49 = OpIAdd %uint %48 %39 +;CHECK: %50 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 %49 +;CHECK: %51 = OpLoad %uint %50 +;CHECK: %52 = OpIAdd %uint %51 %40 +;CHECK: %53 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 %52 +;CHECK: %54 = OpLoad %uint %53 +;CHECK: OpReturnValue %54 +;CHECK: OpFunctionEnd +;CHECK: %62 = OpFunction %void None %63 +;CHECK: %64 = OpFunctionParameter %uint +;CHECK: %65 = OpFunctionParameter %uint +;CHECK: %66 = OpFunctionParameter %uint +;CHECK: %67 = OpFunctionParameter %uint +;CHECK: %68 = OpFunctionParameter %uint +;CHECK: %69 = OpLabel +;CHECK: %73 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_0 +;CHECK: %75 = OpAtomicIAdd %uint %73 %uint_4 %uint_0 %uint_11 +;CHECK: %76 = OpIAdd %uint %75 %uint_11 +;CHECK: %77 = OpArrayLength %uint %72 1 +;CHECK: %78 = OpULessThanEqual %bool %76 %77 +;CHECK: OpSelectionMerge %79 None +;CHECK: OpBranchConditional %78 %80 %79 +;CHECK: %80 = OpLabel +;CHECK: %81 = OpIAdd %uint %75 %uint_0 +;CHECK: %82 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %81 +;CHECK: OpStore %82 %uint_11 +;CHECK: %84 = OpIAdd %uint %75 %uint_1 +;CHECK: %85 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %84 +;CHECK: OpStore %85 %uint_23 +;CHECK: %87 = OpIAdd %uint %75 %uint_2 +;CHECK: %88 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %87 +;CHECK: OpStore %88 %64 +;CHECK: %89 = OpIAdd %uint %75 %uint_3 +;CHECK: %90 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %89 +;CHECK: OpStore %90 %uint_0 +;CHECK: %93 = OpLoad %uint %gl_VertexIndex +;CHECK: %94 = OpIAdd %uint %75 %uint_4 +;CHECK: %95 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %94 +;CHECK: OpStore %95 %93 +;CHECK: %97 = OpLoad %uint %gl_InstanceIndex +;CHECK: %99 = OpIAdd %uint %75 %uint_5 +;CHECK: %100 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %99 +;CHECK: OpStore %100 %97 +;CHECK: %102 = OpIAdd %uint %75 %uint_7 +;CHECK: %103 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %102 +;CHECK: OpStore %103 %65 +;CHECK: %105 = OpIAdd %uint %75 %uint_8 +;CHECK: %106 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %105 +;CHECK: OpStore %106 %66 +;CHECK: %108 = OpIAdd %uint %75 %uint_9 +;CHECK: %109 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %108 +;CHECK: OpStore %109 %67 +;CHECK: %111 = OpIAdd %uint %75 %uint_10 +;CHECK: %112 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %111 +;CHECK: OpStore %112 %68 +;CHECK: OpBranch %79 +;CHECK: %79 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, false, true); +} + +TEST_F(InstBindlessTest, UniformMatrixRefColumnMajor) { + // The buffer-oob column major matrix check + // + // #version 450 + // #extension GL_EXT_scalar_block_layout : enable + // + // layout(location = 0) in highp vec4 a_position; + // layout(location = 0) out mediump float v_vtxResult; + // + // layout(set = 0, binding = 0, std430, column_major) uniform Block + // { + // lowp mat4x2 var; + // }; + // + // void main (void) + // { + // v_vtxResult = var[2][1]; + // } + + const std::string text = R"( + OpCapability Shader +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %main "main" %v_vtxResult %_ %a_position +;CHECK: OpEntryPoint Vertex %main "main" %v_vtxResult %_ %a_position %45 %72 %gl_VertexIndex %gl_InstanceIndex + OpSource GLSL 450 + OpSourceExtension "GL_EXT_scalar_block_layout" + OpName %main "main" + OpName %v_vtxResult "v_vtxResult" + OpName %Block "Block" + OpMemberName %Block 0 "var" + OpName %_ "" + OpName %a_position "a_position" + OpDecorate %v_vtxResult RelaxedPrecision + OpDecorate %v_vtxResult Location 0 + OpMemberDecorate %Block 0 ColMajor + OpMemberDecorate %Block 0 RelaxedPrecision + OpMemberDecorate %Block 0 Offset 0 + OpMemberDecorate %Block 0 MatrixStride 8 + OpDecorate %Block Block + OpDecorate %_ DescriptorSet 0 + OpDecorate %_ Binding 0 + OpDecorate %21 RelaxedPrecision +;CHECK-NOT: OpDecorate %21 RelaxedPrecision +;CHECK: OpDecorate %115 RelaxedPrecision + OpDecorate %a_position Location 0 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_43 Block +;CHECK: OpMemberDecorate %_struct_43 0 Offset 0 +;CHECK: OpDecorate %45 DescriptorSet 7 +;CHECK: OpDecorate %45 Binding 1 +;CHECK: OpDecorate %61 RelaxedPrecision +;CHECK: OpDecorate %_struct_70 Block +;CHECK: OpMemberDecorate %_struct_70 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_70 1 Offset 4 +;CHECK: OpDecorate %72 DescriptorSet 7 +;CHECK: OpDecorate %72 Binding 0 +;CHECK: OpDecorate %gl_VertexIndex BuiltIn VertexIndex +;CHECK: OpDecorate %gl_InstanceIndex BuiltIn InstanceIndex + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 +%_ptr_Output_float = OpTypePointer Output %float +%v_vtxResult = OpVariable %_ptr_Output_float Output + %v2float = OpTypeVector %float 2 +%mat4v2float = OpTypeMatrix %v2float 4 + %Block = OpTypeStruct %mat4v2float +%_ptr_Uniform_Block = OpTypePointer Uniform %Block + %_ = OpVariable %_ptr_Uniform_Block Uniform + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 +%_ptr_Uniform_float = OpTypePointer Uniform %float + %v4float = OpTypeVector %float 4 +%_ptr_Input_v4float = OpTypePointer Input %v4float + %a_position = OpVariable %_ptr_Input_v4float Input +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_4 = OpConstant %uint 4 +;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %37 = OpTypeFunction %uint %uint %uint %uint +;CHECK:%_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_43 = OpTypeStruct %_runtimearr_uint +;CHECK:%_ptr_StorageBuffer__struct_43 = OpTypePointer StorageBuffer %_struct_43 +;CHECK: %45 = OpVariable %_ptr_StorageBuffer__struct_43 StorageBuffer +;CHECK:%_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %bool = OpTypeBool +;CHECK: %63 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_struct_70 = OpTypeStruct %uint %_runtimearr_uint +;CHECK:%_ptr_StorageBuffer__struct_70 = OpTypePointer StorageBuffer %_struct_70 +;CHECK: %72 = OpVariable %_ptr_StorageBuffer__struct_70 StorageBuffer +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK:%_ptr_Input_uint = OpTypePointer Input %uint +;CHECK:%gl_VertexIndex = OpVariable %_ptr_Input_uint Input +;CHECK:%gl_InstanceIndex = OpVariable %_ptr_Input_uint Input +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_45 = OpConstant %uint 45 +;CHECK: %114 = OpConstantNull %float +%main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: %55 = OpFunctionCall %uint %36 %uint_1 %uint_0 %uint_0 +;CHECK: OpBranch %26 +;CHECK: %26 = OpLabel +;CHECK: OpBranch %25 +;CHECK: %25 = OpLabel + %20 = OpAccessChain %_ptr_Uniform_float %_ %int_0 %int_2 %uint_1 + %21 = OpLoad %float %20 +;CHECK-NOT: %21 = OpLoad %float %20 +;CHECK: %29 = OpIMul %uint %uint_8 %int_2 +;CHECK: %30 = OpIAdd %uint %uint_0 %29 +;CHECK: %32 = OpIMul %uint %uint_4 %uint_1 +;CHECK: %33 = OpIAdd %uint %30 %32 +;CHECK: %35 = OpIAdd %uint %33 %uint_3 +;CHECK: %57 = OpULessThan %bool %35 %55 +;CHECK: OpSelectionMerge %58 None +;CHECK: OpBranchConditional %57 %59 %60 +;CHECK: %59 = OpLabel +;CHECK: %61 = OpLoad %float %20 +;CHECK: OpBranch %58 +;CHECK: %60 = OpLabel +;CHECK: %113 = OpFunctionCall %void %62 %uint_45 %uint_4 %uint_0 %35 %55 +;CHECK: OpBranch %58 +;CHECK: %58 = OpLabel +;CHECK: %115 = OpPhi %float %61 %59 %114 %60 + OpStore %v_vtxResult %21 +;CHECK-NOT: OpStore %v_vtxResult %21 +;CHECK: OpStore %v_vtxResult %115 + OpReturn + OpFunctionEnd +;CHECK: %36 = OpFunction %uint None %37 +;CHECK: %38 = OpFunctionParameter %uint +;CHECK: %39 = OpFunctionParameter %uint +;CHECK: %40 = OpFunctionParameter %uint +;CHECK: %41 = OpLabel +;CHECK: %47 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 %38 +;CHECK: %48 = OpLoad %uint %47 +;CHECK: %49 = OpIAdd %uint %48 %39 +;CHECK: %50 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 %49 +;CHECK: %51 = OpLoad %uint %50 +;CHECK: %52 = OpIAdd %uint %51 %40 +;CHECK: %53 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 %52 +;CHECK: %54 = OpLoad %uint %53 +;CHECK: OpReturnValue %54 +;CHECK: OpFunctionEnd +;CHECK: %62 = OpFunction %void None %63 +;CHECK: %64 = OpFunctionParameter %uint +;CHECK: %65 = OpFunctionParameter %uint +;CHECK: %66 = OpFunctionParameter %uint +;CHECK: %67 = OpFunctionParameter %uint +;CHECK: %68 = OpFunctionParameter %uint +;CHECK: %69 = OpLabel +;CHECK: %73 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_0 +;CHECK: %75 = OpAtomicIAdd %uint %73 %uint_4 %uint_0 %uint_11 +;CHECK: %76 = OpIAdd %uint %75 %uint_11 +;CHECK: %77 = OpArrayLength %uint %72 1 +;CHECK: %78 = OpULessThanEqual %bool %76 %77 +;CHECK: OpSelectionMerge %79 None +;CHECK: OpBranchConditional %78 %80 %79 +;CHECK: %80 = OpLabel +;CHECK: %81 = OpIAdd %uint %75 %uint_0 +;CHECK: %82 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %81 +;CHECK: OpStore %82 %uint_11 +;CHECK: %84 = OpIAdd %uint %75 %uint_1 +;CHECK: %85 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %84 +;CHECK: OpStore %85 %uint_23 +;CHECK: %87 = OpIAdd %uint %75 %uint_2 +;CHECK: %88 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %87 +;CHECK: OpStore %88 %64 +;CHECK: %89 = OpIAdd %uint %75 %uint_3 +;CHECK: %90 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %89 +;CHECK: OpStore %90 %uint_0 +;CHECK: %93 = OpLoad %uint %gl_VertexIndex +;CHECK: %94 = OpIAdd %uint %75 %uint_4 +;CHECK: %95 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %94 +;CHECK: OpStore %95 %93 +;CHECK: %97 = OpLoad %uint %gl_InstanceIndex +;CHECK: %99 = OpIAdd %uint %75 %uint_5 +;CHECK: %100 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %99 +;CHECK: OpStore %100 %97 +;CHECK: %102 = OpIAdd %uint %75 %uint_7 +;CHECK: %103 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %102 +;CHECK: OpStore %103 %65 +;CHECK: %104 = OpIAdd %uint %75 %uint_8 +;CHECK: %105 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %104 +;CHECK: OpStore %105 %66 +;CHECK: %107 = OpIAdd %uint %75 %uint_9 +;CHECK: %108 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %107 +;CHECK: OpStore %108 %67 +;CHECK: %110 = OpIAdd %uint %75 %uint_10 +;CHECK: %111 = OpAccessChain %_ptr_StorageBuffer_uint %72 %uint_1 %110 +;CHECK: OpStore %111 %68 +;CHECK: OpBranch %79 +;CHECK: %79 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, false, true); +} + +TEST_F(InstBindlessTest, UniformMatrixVecRefRowMajor) { + // The buffer-oob row major matrix vector ref check + // + // #version 450 + // #extension GL_EXT_scalar_block_layout : enable + // + // layout(location = 0) in highp vec4 a_position; + // layout(location = 0) out highp vec2 v_vtxResult; + // + // layout(set = 0, binding = 0, std430, row_major) uniform Block + // { + // lowp mat2 var[3][4]; + // }; + // + // void main (void) + // { + // v_vtxResult = var[2][3][1]; + // } + + const std::string text = R"( + OpCapability Shader +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %main "main" %v_vtxResult %_ %a_position +;CHECK: OpEntryPoint Vertex %main "main" %v_vtxResult %_ %a_position %54 %81 %gl_VertexIndex %gl_InstanceIndex + OpSource GLSL 450 + OpSourceExtension "GL_EXT_scalar_block_layout" + OpName %main "main" + OpName %v_vtxResult "v_vtxResult" + OpName %Block "Block" + OpMemberName %Block 0 "var" + OpName %_ "" + OpName %a_position "a_position" + OpDecorate %v_vtxResult Location 0 + OpDecorate %_arr_mat2v2float_uint_4 ArrayStride 32 + OpDecorate %_arr__arr_mat2v2float_uint_4_uint_3 ArrayStride 128 + OpMemberDecorate %Block 0 RowMajor + OpMemberDecorate %Block 0 RelaxedPrecision + OpMemberDecorate %Block 0 Offset 0 + OpMemberDecorate %Block 0 MatrixStride 16 + OpDecorate %Block Block + OpDecorate %_ DescriptorSet 0 + OpDecorate %_ Binding 0 + OpDecorate %26 RelaxedPrecision +;CHECK-NOT: OpDecorate %26 RelaxedPrecision +;CHECK: OpDecorate %125 RelaxedPrecision + OpDecorate %a_position Location 0 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_52 Block +;CHECK: OpMemberDecorate %_struct_52 0 Offset 0 +;CHECK: OpDecorate %54 DescriptorSet 7 +;CHECK: OpDecorate %54 Binding 1 +;CHECK: OpDecorate %70 RelaxedPrecision +;CHECK: OpDecorate %_struct_79 Block +;CHECK: OpMemberDecorate %_struct_79 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_79 1 Offset 4 +;CHECK: OpDecorate %81 DescriptorSet 7 +;CHECK: OpDecorate %81 Binding 0 +;CHECK: OpDecorate %gl_VertexIndex BuiltIn VertexIndex +;CHECK: OpDecorate %gl_InstanceIndex BuiltIn InstanceIndex + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v2float = OpTypeVector %float 2 +%_ptr_Output_v2float = OpTypePointer Output %v2float +%v_vtxResult = OpVariable %_ptr_Output_v2float Output +%mat2v2float = OpTypeMatrix %v2float 2 + %uint = OpTypeInt 32 0 + %uint_4 = OpConstant %uint 4 +%_arr_mat2v2float_uint_4 = OpTypeArray %mat2v2float %uint_4 + %uint_3 = OpConstant %uint 3 +%_arr__arr_mat2v2float_uint_4_uint_3 = OpTypeArray %_arr_mat2v2float_uint_4 %uint_3 + %Block = OpTypeStruct %_arr__arr_mat2v2float_uint_4_uint_3 +%_ptr_Uniform_Block = OpTypePointer Uniform %Block + %_ = OpVariable %_ptr_Uniform_Block Uniform + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 + %int_3 = OpConstant %int 3 + %int_1 = OpConstant %int 1 +%_ptr_Uniform_v2float = OpTypePointer Uniform %v2float + %v4float = OpTypeVector %float 4 +%_ptr_Input_v4float = OpTypePointer Input %v4float + %a_position = OpVariable %_ptr_Input_v4float Input +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %uint_128 = OpConstant %uint 128 +;CHECK: %uint_32 = OpConstant %uint 32 +;CHECK: %uint_16 = OpConstant %uint 16 +;CHECK: %uint_19 = OpConstant %uint 19 +;CHECK: %uint_1 = OpConstant %uint 1 +;CHECK: %46 = OpTypeFunction %uint %uint %uint %uint +;CHECK:%_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_52 = OpTypeStruct %_runtimearr_uint +;CHECK:%_ptr_StorageBuffer__struct_52 = OpTypePointer StorageBuffer %_struct_52 +;CHECK: %54 = OpVariable %_ptr_StorageBuffer__struct_52 StorageBuffer +;CHECK:%_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %bool = OpTypeBool +;CHECK: %72 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_struct_79 = OpTypeStruct %uint %_runtimearr_uint +;CHECK:%_ptr_StorageBuffer__struct_79 = OpTypePointer StorageBuffer %_struct_79 +;CHECK: %81 = OpVariable %_ptr_StorageBuffer__struct_79 StorageBuffer +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK:%_ptr_Input_uint = OpTypePointer Input %uint +;CHECK:%gl_VertexIndex = OpVariable %_ptr_Input_uint Input +;CHECK:%gl_InstanceIndex = OpVariable %_ptr_Input_uint Input +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_51 = OpConstant %uint 51 +;CHECK: %124 = OpConstantNull %v2float + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: %64 = OpFunctionCall %uint %45 %uint_1 %uint_0 %uint_0 +;CHECK: OpBranch %31 +;CHECK: %31 = OpLabel +;CHECK: OpBranch %30 +;CHECK: %30 = OpLabel + %25 = OpAccessChain %_ptr_Uniform_v2float %_ %int_0 %int_2 %int_3 %int_1 + %26 = OpLoad %v2float %25 + OpStore %v_vtxResult %26 +;CHECK-NOT: %26 = OpLoad %v2float %25 +;CHECK-NOT: OpStore %v_vtxResult %26 +;CHECK: %34 = OpIMul %uint %uint_128 %int_2 +;CHECK: %35 = OpIAdd %uint %uint_0 %34 +;CHECK: %37 = OpIMul %uint %uint_32 %int_3 +;CHECK: %38 = OpIAdd %uint %35 %37 +;CHECK: %40 = OpIMul %uint %uint_4 %int_1 +;CHECK: %41 = OpIAdd %uint %38 %40 +;CHECK: %43 = OpIAdd %uint %41 %uint_19 +;CHECK: %66 = OpULessThan %bool %43 %64 +;CHECK: OpSelectionMerge %67 None +;CHECK: OpBranchConditional %66 %68 %69 +;CHECK: %68 = OpLabel +;CHECK: %70 = OpLoad %v2float %25 +;CHECK: OpBranch %67 +;CHECK: %69 = OpLabel +;CHECK: %123 = OpFunctionCall %void %71 %uint_51 %uint_4 %uint_0 %43 %64 +;CHECK: OpBranch %67 +;CHECK: %67 = OpLabel +;CHECK: %125 = OpPhi %v2float %70 %68 %124 %69 +;CHECK: OpStore %v_vtxResult %125 + OpReturn + OpFunctionEnd +;CHECK: %45 = OpFunction %uint None %46 +;CHECK: %47 = OpFunctionParameter %uint +;CHECK: %48 = OpFunctionParameter %uint +;CHECK: %49 = OpFunctionParameter %uint +;CHECK: %50 = OpLabel +;CHECK: %56 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_0 %47 +;CHECK: %57 = OpLoad %uint %56 +;CHECK: %58 = OpIAdd %uint %57 %48 +;CHECK: %59 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_0 %58 +;CHECK: %60 = OpLoad %uint %59 +;CHECK: %61 = OpIAdd %uint %60 %49 +;CHECK: %62 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_0 %61 +;CHECK: %63 = OpLoad %uint %62 +;CHECK: OpReturnValue %63 +;CHECK: OpFunctionEnd +;CHECK: %71 = OpFunction %void None %72 +;CHECK: %73 = OpFunctionParameter %uint +;CHECK: %74 = OpFunctionParameter %uint +;CHECK: %75 = OpFunctionParameter %uint +;CHECK: %76 = OpFunctionParameter %uint +;CHECK: %77 = OpFunctionParameter %uint +;CHECK: %78 = OpLabel +;CHECK: %82 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_0 +;CHECK: %84 = OpAtomicIAdd %uint %82 %uint_4 %uint_0 %uint_11 +;CHECK: %85 = OpIAdd %uint %84 %uint_11 +;CHECK: %86 = OpArrayLength %uint %81 1 +;CHECK: %87 = OpULessThanEqual %bool %85 %86 +;CHECK: OpSelectionMerge %88 None +;CHECK: OpBranchConditional %87 %89 %88 +;CHECK: %89 = OpLabel +;CHECK: %90 = OpIAdd %uint %84 %uint_0 +;CHECK: %91 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %90 +;CHECK: OpStore %91 %uint_11 +;CHECK: %93 = OpIAdd %uint %84 %uint_1 +;CHECK: %94 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %93 +;CHECK: OpStore %94 %uint_23 +;CHECK: %96 = OpIAdd %uint %84 %uint_2 +;CHECK: %97 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %96 +;CHECK: OpStore %97 %73 +;CHECK: %98 = OpIAdd %uint %84 %uint_3 +;CHECK: %99 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %98 +;CHECK: OpStore %99 %uint_0 +;CHECK: %102 = OpLoad %uint %gl_VertexIndex +;CHECK: %103 = OpIAdd %uint %84 %uint_4 +;CHECK: %104 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %103 +;CHECK: OpStore %104 %102 +;CHECK: %106 = OpLoad %uint %gl_InstanceIndex +;CHECK: %108 = OpIAdd %uint %84 %uint_5 +;CHECK: %109 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %108 +;CHECK: OpStore %109 %106 +;CHECK: %111 = OpIAdd %uint %84 %uint_7 +;CHECK: %112 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %111 +;CHECK: OpStore %112 %74 +;CHECK: %114 = OpIAdd %uint %84 %uint_8 +;CHECK: %115 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %114 +;CHECK: OpStore %115 %75 +;CHECK: %117 = OpIAdd %uint %84 %uint_9 +;CHECK: %118 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %117 +;CHECK: OpStore %118 %76 +;CHECK: %120 = OpIAdd %uint %84 %uint_10 +;CHECK: %121 = OpAccessChain %_ptr_StorageBuffer_uint %81 %uint_1 %120 +;CHECK: OpStore %121 %77 +;CHECK: OpBranch %88 +;CHECK: %88 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, false, true); +} + +TEST_F(InstBindlessTest, ImageBufferOOBRead) { + // Texel buffer (imagebuffer) oob check for ImageRead + // + // #version 450 + // layout(set=3, binding=7, r32f) uniform readonly imageBuffer s; + // layout(location=11) out vec4 x; + // layout(location=13) in flat int ii; + // + // void main(){ + // x = imageLoad(s, ii); + // } + + const std::string text = R"( + OpCapability Shader + OpCapability ImageBuffer +;CHECK: OpCapability ImageQuery +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %x %s %ii + OpExecutionMode %main OriginUpperLeft + OpSource GLSL 450 + OpName %main "main" + OpName %x "x" + OpName %s "s" + OpName %ii "ii" + OpDecorate %x Location 11 + OpDecorate %s DescriptorSet 3 + OpDecorate %s Binding 7 + OpDecorate %s NonWritable + OpDecorate %ii Flat + OpDecorate %ii Location 13 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_43 Block +;CHECK: OpMemberDecorate %_struct_43 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_43 1 Offset 4 +;CHECK: OpDecorate %45 DescriptorSet 7 +;CHECK: OpDecorate %45 Binding 0 +;CHECK: OpDecorate %gl_FragCoord BuiltIn FragCoord + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %_ptr_Output_v4float = OpTypePointer Output %v4float + %x = OpVariable %_ptr_Output_v4float Output + %10 = OpTypeImage %float Buffer 0 0 0 2 R32f + %_ptr_UniformConstant_10 = OpTypePointer UniformConstant %10 + %s = OpVariable %_ptr_UniformConstant_10 UniformConstant + %int = OpTypeInt 32 1 + %_ptr_Input_int = OpTypePointer Input %int + %ii = OpVariable %_ptr_Input_int Input +;CHECK: %uint = OpTypeInt 32 0 +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %bool = OpTypeBool +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %35 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_43 = OpTypeStruct %uint %_runtimearr_uint +;CHECK: %_ptr_StorageBuffer__struct_43 = OpTypePointer StorageBuffer %_struct_43 +;CHECK: %45 = OpVariable %_ptr_StorageBuffer__struct_43 StorageBuffer +;CHECK: %_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_4 = OpConstant %uint 4 +;CHECK: %uint_1 = OpConstant %uint 1 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %_ptr_Input_v4float = OpTypePointer Input %v4float +;CHECK: %gl_FragCoord = OpVariable %_ptr_Input_v4float Input +;CHECK: %v4uint = OpTypeVector %uint 4 +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_33 = OpConstant %uint 33 +;CHECK: %93 = OpConstantNull %v4float + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: OpBranch %21 +;CHECK: %21 = OpLabel +;CHECK: OpBranch %20 +;CHECK: %20 = OpLabel +;CHECK: OpBranch %19 +;CHECK: %19 = OpLabel + %13 = OpLoad %10 %s + %17 = OpLoad %int %ii + %18 = OpImageRead %v4float %13 %17 + OpStore %x %18 +;CHECK-NOT: %18 = OpImageRead %v4float %13 %17 +;CHECK-NOT: OpStore %x %18 +;CHECK: %23 = OpBitcast %uint %17 +;CHECK: %25 = OpImageQuerySize %uint %13 +;CHECK: %27 = OpULessThan %bool %23 %25 +;CHECK: OpSelectionMerge %29 None +;CHECK: OpBranchConditional %27 %30 %31 +;CHECK: %30 = OpLabel +;CHECK: %32 = OpLoad %10 %s +;CHECK: %33 = OpImageRead %v4float %32 %17 +;CHECK: OpBranch %29 +;CHECK: %31 = OpLabel +;CHECK: %92 = OpFunctionCall %void %34 %uint_33 %uint_7 %uint_0 %23 %25 +;CHECK: OpBranch %29 +;CHECK: %29 = OpLabel +;CHECK: %94 = OpPhi %v4float %33 %30 %93 %31 +;CHECK: OpStore %x %94 + OpReturn + OpFunctionEnd +;CHECK: %34 = OpFunction %void None %35 +;CHECK: %36 = OpFunctionParameter %uint +;CHECK: %37 = OpFunctionParameter %uint +;CHECK: %38 = OpFunctionParameter %uint +;CHECK: %39 = OpFunctionParameter %uint +;CHECK: %40 = OpFunctionParameter %uint +;CHECK: %41 = OpLabel +;CHECK: %47 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 +;CHECK: %50 = OpAtomicIAdd %uint %47 %uint_4 %uint_0 %uint_11 +;CHECK: %51 = OpIAdd %uint %50 %uint_11 +;CHECK: %52 = OpArrayLength %uint %45 1 +;CHECK: %53 = OpULessThanEqual %bool %51 %52 +;CHECK: OpSelectionMerge %54 None +;CHECK: OpBranchConditional %53 %55 %54 +;CHECK: %55 = OpLabel +;CHECK: %56 = OpIAdd %uint %50 %uint_0 +;CHECK: %58 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %56 +;CHECK: OpStore %58 %uint_11 +;CHECK: %60 = OpIAdd %uint %50 %uint_1 +;CHECK: %61 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %60 +;CHECK: OpStore %61 %uint_23 +;CHECK: %63 = OpIAdd %uint %50 %uint_2 +;CHECK: %64 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %63 +;CHECK: OpStore %64 %36 +;CHECK: %66 = OpIAdd %uint %50 %uint_3 +;CHECK: %67 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %66 +;CHECK: OpStore %67 %uint_4 +;CHECK: %70 = OpLoad %v4float %gl_FragCoord +;CHECK: %72 = OpBitcast %v4uint %70 +;CHECK: %73 = OpCompositeExtract %uint %72 0 +;CHECK: %74 = OpIAdd %uint %50 %uint_4 +;CHECK: %75 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %74 +;CHECK: OpStore %75 %73 +;CHECK: %76 = OpCompositeExtract %uint %72 1 +;CHECK: %78 = OpIAdd %uint %50 %uint_5 +;CHECK: %79 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %78 +;CHECK: OpStore %79 %76 +;CHECK: %80 = OpIAdd %uint %50 %uint_7 +;CHECK: %81 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %80 +;CHECK: OpStore %81 %37 +;CHECK: %83 = OpIAdd %uint %50 %uint_8 +;CHECK: %84 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %83 +;CHECK: OpStore %84 %38 +;CHECK: %86 = OpIAdd %uint %50 %uint_9 +;CHECK: %87 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %86 +;CHECK: OpStore %87 %39 +;CHECK: %89 = OpIAdd %uint %50 %uint_10 +;CHECK: %90 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %89 +;CHECK: OpStore %90 %40 +;CHECK: OpBranch %54 +;CHECK: %54 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, true, true); +} + +TEST_F(InstBindlessTest, ImageBufferOOBWrite) { + // Texel buffer (imagebuffer) oob check for ImageWrite + // + // #version 450 + // layout(set=3, binding=7, r32f) uniform readonly imageBuffer s; + // layout(location=11) out vec4 x; + // layout(location=13) in flat int ii; + // + // void main(){ + // imageStore(s, ii, x); + // } + + const std::string text = R"( + OpCapability Shader + OpCapability ImageBuffer +;CHECK: OpCapability ImageQuery +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %s %ii %x +;CHECK: OpEntryPoint Fragment %main "main" %s %ii %x %44 %gl_FragCoord + OpExecutionMode %main OriginUpperLeft + OpSource GLSL 450 + OpName %main "main" + OpName %s "s" + OpName %ii "ii" + OpName %x "x" + OpDecorate %s DescriptorSet 3 + OpDecorate %s Binding 7 + OpDecorate %s NonReadable + OpDecorate %ii Flat + OpDecorate %ii Location 13 + OpDecorate %x Location 11 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_42 Block +;CHECK: OpMemberDecorate %_struct_42 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_42 1 Offset 4 +;CHECK: OpDecorate %44 DescriptorSet 7 +;CHECK: OpDecorate %44 Binding 0 +;CHECK: OpDecorate %gl_FragCoord BuiltIn FragCoord + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %7 = OpTypeImage %float Buffer 0 0 0 2 R32f + %_ptr_UniformConstant_7 = OpTypePointer UniformConstant %7 + %s = OpVariable %_ptr_UniformConstant_7 UniformConstant + %int = OpTypeInt 32 1 + %_ptr_Input_int = OpTypePointer Input %int + %ii = OpVariable %_ptr_Input_int Input + %v4float = OpTypeVector %float 4 + %_ptr_Output_v4float = OpTypePointer Output %v4float + %x = OpVariable %_ptr_Output_v4float Output +;CHECK: %uint = OpTypeInt 32 0 +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %bool = OpTypeBool +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %34 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_42 = OpTypeStruct %uint %_runtimearr_uint +;CHECK: %_ptr_StorageBuffer__struct_42 = OpTypePointer StorageBuffer %_struct_42 +;CHECK: %44 = OpVariable %_ptr_StorageBuffer__struct_42 StorageBuffer +;CHECK: %_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_4 = OpConstant %uint 4 +;CHECK: %uint_1 = OpConstant %uint 1 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %_ptr_Input_v4float = OpTypePointer Input %v4float +;CHECK: %gl_FragCoord = OpVariable %_ptr_Input_v4float Input +;CHECK: %v4uint = OpTypeVector %uint 4 +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_34 = OpConstant %uint 34 + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: OpBranch %21 +;CHECK: %21 = OpLabel +;CHECK: OpBranch %20 +;CHECK: %20 = OpLabel +;CHECK: OpBranch %19 +;CHECK: %19 = OpLabel + %10 = OpLoad %7 %s + %14 = OpLoad %int %ii + %18 = OpLoad %v4float %x + OpImageWrite %10 %14 %18 +;CHECK-NOT: OpImageWrite %10 %14 %18 +;CHECK: %23 = OpBitcast %uint %14 +;CHECK: %25 = OpImageQuerySize %uint %10 +;CHECK: %27 = OpULessThan %bool %23 %25 +;CHECK: OpSelectionMerge %29 None +;CHECK: OpBranchConditional %27 %30 %31 +;CHECK: %30 = OpLabel +;CHECK: %32 = OpLoad %7 %s +;CHECK: OpImageWrite %32 %14 %18 +;CHECK: OpBranch %29 +;CHECK: %31 = OpLabel +;CHECK: %91 = OpFunctionCall %void %33 %uint_34 %uint_7 %uint_0 %23 %25 +;CHECK: OpBranch %29 +;CHECK: %29 = OpLabel + OpReturn + OpFunctionEnd +;CHECK: %33 = OpFunction %void None %34 +;CHECK: %35 = OpFunctionParameter %uint +;CHECK: %36 = OpFunctionParameter %uint +;CHECK: %37 = OpFunctionParameter %uint +;CHECK: %38 = OpFunctionParameter %uint +;CHECK: %39 = OpFunctionParameter %uint +;CHECK: %40 = OpLabel +;CHECK: %46 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_0 +;CHECK: %49 = OpAtomicIAdd %uint %46 %uint_4 %uint_0 %uint_11 +;CHECK: %50 = OpIAdd %uint %49 %uint_11 +;CHECK: %51 = OpArrayLength %uint %44 1 +;CHECK: %52 = OpULessThanEqual %bool %50 %51 +;CHECK: OpSelectionMerge %53 None +;CHECK: OpBranchConditional %52 %54 %53 +;CHECK: %54 = OpLabel +;CHECK: %55 = OpIAdd %uint %49 %uint_0 +;CHECK: %57 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %55 +;CHECK: OpStore %57 %uint_11 +;CHECK: %59 = OpIAdd %uint %49 %uint_1 +;CHECK: %60 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %59 +;CHECK: OpStore %60 %uint_23 +;CHECK: %62 = OpIAdd %uint %49 %uint_2 +;CHECK: %63 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %62 +;CHECK: OpStore %63 %35 +;CHECK: %65 = OpIAdd %uint %49 %uint_3 +;CHECK: %66 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %65 +;CHECK: OpStore %66 %uint_4 +;CHECK: %69 = OpLoad %v4float %gl_FragCoord +;CHECK: %71 = OpBitcast %v4uint %69 +;CHECK: %72 = OpCompositeExtract %uint %71 0 +;CHECK: %73 = OpIAdd %uint %49 %uint_4 +;CHECK: %74 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %73 +;CHECK: OpStore %74 %72 +;CHECK: %75 = OpCompositeExtract %uint %71 1 +;CHECK: %77 = OpIAdd %uint %49 %uint_5 +;CHECK: %78 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %77 +;CHECK: OpStore %78 %75 +;CHECK: %79 = OpIAdd %uint %49 %uint_7 +;CHECK: %80 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %79 +;CHECK: OpStore %80 %36 +;CHECK: %82 = OpIAdd %uint %49 %uint_8 +;CHECK: %83 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %82 +;CHECK: OpStore %83 %37 +;CHECK: %85 = OpIAdd %uint %49 %uint_9 +;CHECK: %86 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %85 +;CHECK: OpStore %86 %38 +;CHECK: %88 = OpIAdd %uint %49 %uint_10 +;CHECK: %89 = OpAccessChain %_ptr_StorageBuffer_uint %44 %uint_1 %88 +;CHECK: OpStore %89 %39 +;CHECK: OpBranch %53 +;CHECK: %53 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, true, true); +} + +TEST_F(InstBindlessTest, TextureBufferOOBFetch) { + // Texel buffer (texturebuffer) oob check for ImageFetch + // + // #version 450 + // layout(set=3, binding=7) uniform textureBuffer s; + // layout(location=11) out vec4 x; + // layout(location=13) in flat int ii; + // + // void main(){ + // x = texelFetch(s, ii); + // } + + const std::string text = R"( + OpCapability Shader + OpCapability SampledBuffer +;CHECK: OpCapability ImageQuery +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %x %s %ii +;CHECK: OpEntryPoint Fragment %main "main" %x %s %ii %45 %gl_FragCoord + OpExecutionMode %main OriginUpperLeft + OpSource GLSL 450 + OpName %main "main" + OpName %x "x" + OpName %s "s" + OpName %ii "ii" + OpDecorate %x Location 11 + OpDecorate %s DescriptorSet 3 + OpDecorate %s Binding 7 + OpDecorate %ii Flat + OpDecorate %ii Location 13 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_43 Block +;CHECK: OpMemberDecorate %_struct_43 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_43 1 Offset 4 +;CHECK: OpDecorate %45 DescriptorSet 7 +;CHECK: OpDecorate %45 Binding 0 +;CHECK: OpDecorate %gl_FragCoord BuiltIn FragCoord + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %_ptr_Output_v4float = OpTypePointer Output %v4float + %x = OpVariable %_ptr_Output_v4float Output + %10 = OpTypeImage %float Buffer 0 0 0 1 Unknown + %_ptr_UniformConstant_10 = OpTypePointer UniformConstant %10 + %s = OpVariable %_ptr_UniformConstant_10 UniformConstant + %int = OpTypeInt 32 1 + %_ptr_Input_int = OpTypePointer Input %int + %ii = OpVariable %_ptr_Input_int Input +;CHECK: %uint = OpTypeInt 32 0 +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %bool = OpTypeBool +;CHECK: %uint_6 = OpConstant %uint 6 +;CHECK: %35 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_43 = OpTypeStruct %uint %_runtimearr_uint +;CHECK: %_ptr_StorageBuffer__struct_43 = OpTypePointer StorageBuffer %_struct_43 +;CHECK: %45 = OpVariable %_ptr_StorageBuffer__struct_43 StorageBuffer +;CHECK: %_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_4 = OpConstant %uint 4 +;CHECK: %uint_1 = OpConstant %uint 1 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %_ptr_Input_v4float = OpTypePointer Input %v4float +;CHECK: %gl_FragCoord = OpVariable %_ptr_Input_v4float Input +;CHECK: %v4uint = OpTypeVector %uint 4 +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_32 = OpConstant %uint 32 +;CHECK: %94 = OpConstantNull %v4float + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: OpBranch %21 +;CHECK: %21 = OpLabel +;CHECK: OpBranch %20 +;CHECK: %20 = OpLabel +;CHECK: OpBranch %19 +;CHECK: %19 = OpLabel + %13 = OpLoad %10 %s + %17 = OpLoad %int %ii + %18 = OpImageFetch %v4float %13 %17 + OpStore %x %18 +;CHECK-NOT: %18 = OpImageFetch %v4float %13 %17 +;CHECK-NOT: OpStore %x %18 +;CHECK: %23 = OpBitcast %uint %17 +;CHECK: %25 = OpImageQuerySize %uint %13 +;CHECK: %27 = OpULessThan %bool %23 %25 +;CHECK: OpSelectionMerge %29 None +;CHECK: OpBranchConditional %27 %30 %31 +;CHECK: %30 = OpLabel +;CHECK: %32 = OpLoad %10 %s +;CHECK: %33 = OpImageFetch %v4float %32 %17 +;CHECK: OpBranch %29 +;CHECK: %31 = OpLabel +;CHECK: %93 = OpFunctionCall %void %34 %uint_32 %uint_6 %uint_0 %23 %25 +;CHECK: OpBranch %29 +;CHECK: %29 = OpLabel +;CHECK: %95 = OpPhi %v4float %33 %30 %94 %31 +;CHECK: OpStore %x %95 + OpReturn + OpFunctionEnd +;CHECK: %34 = OpFunction %void None %35 +;CHECK: %36 = OpFunctionParameter %uint +;CHECK: %37 = OpFunctionParameter %uint +;CHECK: %38 = OpFunctionParameter %uint +;CHECK: %39 = OpFunctionParameter %uint +;CHECK: %40 = OpFunctionParameter %uint +;CHECK: %41 = OpLabel +;CHECK: %47 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_0 +;CHECK: %50 = OpAtomicIAdd %uint %47 %uint_4 %uint_0 %uint_11 +;CHECK: %51 = OpIAdd %uint %50 %uint_11 +;CHECK: %52 = OpArrayLength %uint %45 1 +;CHECK: %53 = OpULessThanEqual %bool %51 %52 +;CHECK: OpSelectionMerge %54 None +;CHECK: OpBranchConditional %53 %55 %54 +;CHECK: %55 = OpLabel +;CHECK: %56 = OpIAdd %uint %50 %uint_0 +;CHECK: %58 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %56 +;CHECK: OpStore %58 %uint_11 +;CHECK: %60 = OpIAdd %uint %50 %uint_1 +;CHECK: %61 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %60 +;CHECK: OpStore %61 %uint_23 +;CHECK: %63 = OpIAdd %uint %50 %uint_2 +;CHECK: %64 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %63 +;CHECK: OpStore %64 %36 +;CHECK: %66 = OpIAdd %uint %50 %uint_3 +;CHECK: %67 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %66 +;CHECK: OpStore %67 %uint_4 +;CHECK: %70 = OpLoad %v4float %gl_FragCoord +;CHECK: %72 = OpBitcast %v4uint %70 +;CHECK: %73 = OpCompositeExtract %uint %72 0 +;CHECK: %74 = OpIAdd %uint %50 %uint_4 +;CHECK: %75 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %74 +;CHECK: OpStore %75 %73 +;CHECK: %76 = OpCompositeExtract %uint %72 1 +;CHECK: %78 = OpIAdd %uint %50 %uint_5 +;CHECK: %79 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %78 +;CHECK: OpStore %79 %76 +;CHECK: %81 = OpIAdd %uint %50 %uint_7 +;CHECK: %82 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %81 +;CHECK: OpStore %82 %37 +;CHECK: %84 = OpIAdd %uint %50 %uint_8 +;CHECK: %85 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %84 +;CHECK: OpStore %85 %38 +;CHECK: %87 = OpIAdd %uint %50 %uint_9 +;CHECK: %88 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %87 +;CHECK: OpStore %88 %39 +;CHECK: %90 = OpIAdd %uint %50 %uint_10 +;CHECK: %91 = OpAccessChain %_ptr_StorageBuffer_uint %45 %uint_1 %90 +;CHECK: OpStore %91 %40 +;CHECK: OpBranch %54 +;CHECK: %54 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, true, true); +} + +TEST_F(InstBindlessTest, SamplerBufferOOBFetch) { + // Texel buffer (samplerbuffer) oob check for ImageFetch + // + // #version 450 + // layout(set=3, binding=7) uniform samplerBuffer s; + // layout(location=11) out vec4 x; + // layout(location=13) in flat int ii; + // + // void main(){ + // x = texelFetch(s, ii); + // } + + const std::string text = R"( + OpCapability Shader + OpCapability SampledBuffer +;CHECK: OpCapability ImageQuery +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %x %s %ii +;CHECK: OpEntryPoint Fragment %main "main" %x %s %ii %48 %gl_FragCoord + OpExecutionMode %main OriginUpperLeft + OpSource GLSL 450 + OpName %main "main" + OpName %x "x" + OpName %s "s" + OpName %ii "ii" + OpDecorate %x Location 11 + OpDecorate %s DescriptorSet 3 + OpDecorate %s Binding 7 + OpDecorate %ii Flat + OpDecorate %ii Location 13 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_46 Block +;CHECK: OpMemberDecorate %_struct_46 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_46 1 Offset 4 +;CHECK: OpDecorate %48 DescriptorSet 7 +;CHECK: OpDecorate %48 Binding 0 +;CHECK: OpDecorate %gl_FragCoord BuiltIn FragCoord + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %_ptr_Output_v4float = OpTypePointer Output %v4float + %x = OpVariable %_ptr_Output_v4float Output + %10 = OpTypeImage %float Buffer 0 0 0 1 Unknown + %11 = OpTypeSampledImage %10 + %_ptr_UniformConstant_11 = OpTypePointer UniformConstant %11 + %s = OpVariable %_ptr_UniformConstant_11 UniformConstant + %int = OpTypeInt 32 1 + %_ptr_Input_int = OpTypePointer Input %int + %ii = OpVariable %_ptr_Input_int Input +;CHECK: %uint = OpTypeInt 32 0 +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %bool = OpTypeBool +;CHECK: %uint_6 = OpConstant %uint 6 +;CHECK: %38 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_46 = OpTypeStruct %uint %_runtimearr_uint +;CHECK: %_ptr_StorageBuffer__struct_46 = OpTypePointer StorageBuffer %_struct_46 +;CHECK: %48 = OpVariable %_ptr_StorageBuffer__struct_46 StorageBuffer +;CHECK: %_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_4 = OpConstant %uint 4 +;CHECK: %uint_1 = OpConstant %uint 1 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %_ptr_Input_v4float = OpTypePointer Input %v4float +;CHECK: %gl_FragCoord = OpVariable %_ptr_Input_v4float Input +;CHECK: %v4uint = OpTypeVector %uint 4 +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_34 = OpConstant %uint 34 +;CHECK: %97 = OpConstantNull %v4float + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: OpBranch %23 +;CHECK: %23 = OpLabel +;CHECK: OpBranch %22 +;CHECK: %22 = OpLabel +;CHECK: OpBranch %21 +;CHECK: %21 = OpLabel + %14 = OpLoad %11 %s + %18 = OpLoad %int %ii + %19 = OpImage %10 %14 + %20 = OpImageFetch %v4float %19 %18 + OpStore %x %20 +;CHECK-NOT: %20 = OpImageFetch %v4float %19 %18 +;CHECK-NOT: OpStore %x %20 +;CHECK: %25 = OpBitcast %uint %18 +;CHECK: %27 = OpImageQuerySize %uint %19 +;CHECK: %29 = OpULessThan %bool %25 %27 +;CHECK: OpSelectionMerge %31 None +;CHECK: OpBranchConditional %29 %32 %33 +;CHECK: %32 = OpLabel +;CHECK: %34 = OpLoad %11 %s +;CHECK: %35 = OpImage %10 %34 +;CHECK: %36 = OpImageFetch %v4float %35 %18 +;CHECK: OpBranch %31 +;CHECK: %33 = OpLabel +;CHECK: %96 = OpFunctionCall %void %37 %uint_34 %uint_6 %uint_0 %25 %27 +;CHECK: OpBranch %31 +;CHECK: %31 = OpLabel +;CHECK: %98 = OpPhi %v4float %36 %32 %97 %33 +;CHECK: OpStore %x %98 + OpReturn + OpFunctionEnd +;CHECK: %37 = OpFunction %void None %38 +;CHECK: %39 = OpFunctionParameter %uint +;CHECK: %40 = OpFunctionParameter %uint +;CHECK: %41 = OpFunctionParameter %uint +;CHECK: %42 = OpFunctionParameter %uint +;CHECK: %43 = OpFunctionParameter %uint +;CHECK: %44 = OpLabel +;CHECK: %50 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_0 +;CHECK: %53 = OpAtomicIAdd %uint %50 %uint_4 %uint_0 %uint_11 +;CHECK: %54 = OpIAdd %uint %53 %uint_11 +;CHECK: %55 = OpArrayLength %uint %48 1 +;CHECK: %56 = OpULessThanEqual %bool %54 %55 +;CHECK: OpSelectionMerge %57 None +;CHECK: OpBranchConditional %56 %58 %57 +;CHECK: %58 = OpLabel +;CHECK: %59 = OpIAdd %uint %53 %uint_0 +;CHECK: %61 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %59 +;CHECK: OpStore %61 %uint_11 +;CHECK: %63 = OpIAdd %uint %53 %uint_1 +;CHECK: %64 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %63 +;CHECK: OpStore %64 %uint_23 +;CHECK: %66 = OpIAdd %uint %53 %uint_2 +;CHECK: %67 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %66 +;CHECK: OpStore %67 %39 +;CHECK: %69 = OpIAdd %uint %53 %uint_3 +;CHECK: %70 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %69 +;CHECK: OpStore %70 %uint_4 +;CHECK: %73 = OpLoad %v4float %gl_FragCoord +;CHECK: %75 = OpBitcast %v4uint %73 +;CHECK: %76 = OpCompositeExtract %uint %75 0 +;CHECK: %77 = OpIAdd %uint %53 %uint_4 +;CHECK: %78 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %77 +;CHECK: OpStore %78 %76 +;CHECK: %79 = OpCompositeExtract %uint %75 1 +;CHECK: %81 = OpIAdd %uint %53 %uint_5 +;CHECK: %82 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %81 +;CHECK: OpStore %82 %79 +;CHECK: %84 = OpIAdd %uint %53 %uint_7 +;CHECK: %85 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %84 +;CHECK: OpStore %85 %40 +;CHECK: %87 = OpIAdd %uint %53 %uint_8 +;CHECK: %88 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %87 +;CHECK: OpStore %88 %41 +;CHECK: %90 = OpIAdd %uint %53 %uint_9 +;CHECK: %91 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %90 +;CHECK: OpStore %91 %42 +;CHECK: %93 = OpIAdd %uint %53 %uint_10 +;CHECK: %94 = OpAccessChain %_ptr_StorageBuffer_uint %48 %uint_1 %93 +;CHECK: OpStore %94 %43 +;CHECK: OpBranch %57 +;CHECK: %57 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, true, true); +} + +TEST_F(InstBindlessTest, SamplerBufferConstructorOOBFetch) { + // Texel buffer (samplerbuffer constructor) oob check for ImageFetch + // + // #version 450 + // layout(set=3, binding=7) uniform textureBuffer tBuf; + // layout(set=3, binding=8) uniform sampler s; + // layout(location=11) out vec4 x; + // layout(location=13) in flat int ii; + // + // void main(){ + // x = texelFetch(samplerBuffer(tBuf, s), ii); + // } + + const std::string text = R"( + OpCapability Shader + OpCapability SampledBuffer +;CHECK: OpCapability ImageQuery +;CHECK: OpExtension "SPV_KHR_storage_buffer_storage_class" + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %x %tBuf %s %ii +;CHECK: OpEntryPoint Fragment %main "main" %x %tBuf %s %ii %54 %gl_FragCoord + OpExecutionMode %main OriginUpperLeft + OpSource GLSL 450 + OpName %main "main" + OpName %x "x" + OpName %tBuf "tBuf" + OpName %s "s" + OpName %ii "ii" + OpDecorate %x Location 11 + OpDecorate %tBuf DescriptorSet 3 + OpDecorate %tBuf Binding 7 + OpDecorate %s DescriptorSet 3 + OpDecorate %s Binding 8 + OpDecorate %ii Flat + OpDecorate %ii Location 13 +;CHECK: OpDecorate %_runtimearr_uint ArrayStride 4 +;CHECK: OpDecorate %_struct_52 Block +;CHECK: OpMemberDecorate %_struct_52 0 Offset 0 +;CHECK: OpMemberDecorate %_struct_52 1 Offset 4 +;CHECK: OpDecorate %54 DescriptorSet 7 +;CHECK: OpDecorate %54 Binding 0 +;CHECK: OpDecorate %gl_FragCoord BuiltIn FragCoord + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %_ptr_Output_v4float = OpTypePointer Output %v4float + %x = OpVariable %_ptr_Output_v4float Output + %10 = OpTypeImage %float Buffer 0 0 0 1 Unknown + %_ptr_UniformConstant_10 = OpTypePointer UniformConstant %10 + %tBuf = OpVariable %_ptr_UniformConstant_10 UniformConstant + %14 = OpTypeSampler + %_ptr_UniformConstant_14 = OpTypePointer UniformConstant %14 + %s = OpVariable %_ptr_UniformConstant_14 UniformConstant + %18 = OpTypeSampledImage %10 + %int = OpTypeInt 32 1 + %_ptr_Input_int = OpTypePointer Input %int + %ii = OpVariable %_ptr_Input_int Input +;CHECK: %uint = OpTypeInt 32 0 +;CHECK: %uint_0 = OpConstant %uint 0 +;CHECK: %bool = OpTypeBool +;CHECK: %uint_6 = OpConstant %uint 6 +;CHECK: %44 = OpTypeFunction %void %uint %uint %uint %uint %uint +;CHECK: %_runtimearr_uint = OpTypeRuntimeArray %uint +;CHECK: %_struct_52 = OpTypeStruct %uint %_runtimearr_uint +;CHECK: %_ptr_StorageBuffer__struct_52 = OpTypePointer StorageBuffer %_struct_52 +;CHECK: %54 = OpVariable %_ptr_StorageBuffer__struct_52 StorageBuffer +;CHECK: %_ptr_StorageBuffer_uint = OpTypePointer StorageBuffer %uint +;CHECK: %uint_11 = OpConstant %uint 11 +;CHECK: %uint_4 = OpConstant %uint 4 +;CHECK: %uint_1 = OpConstant %uint 1 +;CHECK: %uint_23 = OpConstant %uint 23 +;CHECK: %uint_2 = OpConstant %uint 2 +;CHECK: %uint_3 = OpConstant %uint 3 +;CHECK: %_ptr_Input_v4float = OpTypePointer Input %v4float +;CHECK: %gl_FragCoord = OpVariable %_ptr_Input_v4float Input +;CHECK: %v4uint = OpTypeVector %uint 4 +;CHECK: %uint_5 = OpConstant %uint 5 +;CHECK: %uint_7 = OpConstant %uint 7 +;CHECK: %uint_8 = OpConstant %uint 8 +;CHECK: %uint_9 = OpConstant %uint 9 +;CHECK: %uint_10 = OpConstant %uint 10 +;CHECK: %uint_42 = OpConstant %uint 42 +;CHECK: %103 = OpConstantNull %v4float + %main = OpFunction %void None %3 + %5 = OpLabel +;CHECK: OpBranch %28 +;CHECK: %28 = OpLabel +;CHECK: OpBranch %27 +;CHECK: %27 = OpLabel +;CHECK: OpBranch %26 +;CHECK: %26 = OpLabel + %13 = OpLoad %10 %tBuf + %17 = OpLoad %14 %s + %19 = OpSampledImage %18 %13 %17 + %23 = OpLoad %int %ii + %24 = OpImage %10 %19 + %25 = OpImageFetch %v4float %24 %23 + OpStore %x %25 +;CHECK-NOT: %25 = OpImageFetch %v4float %24 %23 +;CHECK-NOT: OpStore %x %25 +;CHECK: %30 = OpBitcast %uint %23 +;CHECK: %32 = OpImageQuerySize %uint %24 +;CHECK: %34 = OpULessThan %bool %30 %32 +;CHECK: OpSelectionMerge %36 None +;CHECK: OpBranchConditional %34 %37 %38 +;CHECK: %37 = OpLabel +;CHECK: %39 = OpLoad %10 %tBuf +;CHECK: %40 = OpSampledImage %18 %39 %17 +;CHECK: %41 = OpImage %10 %40 +;CHECK: %42 = OpImageFetch %v4float %41 %23 +;CHECK: OpBranch %36 +;CHECK: %38 = OpLabel +;CHECK: %102 = OpFunctionCall %void %43 %uint_42 %uint_6 %uint_0 %30 %32 +;CHECK: OpBranch %36 +;CHECK: %36 = OpLabel +;CHECK: %104 = OpPhi %v4float %42 %37 %103 %38 +;CHECK: OpStore %x %104 + OpReturn + OpFunctionEnd +;CHECK: %43 = OpFunction %void None %44 +;CHECK: %45 = OpFunctionParameter %uint +;CHECK: %46 = OpFunctionParameter %uint +;CHECK: %47 = OpFunctionParameter %uint +;CHECK: %48 = OpFunctionParameter %uint +;CHECK: %49 = OpFunctionParameter %uint +;CHECK: %50 = OpLabel +;CHECK: %56 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_0 +;CHECK: %59 = OpAtomicIAdd %uint %56 %uint_4 %uint_0 %uint_11 +;CHECK: %60 = OpIAdd %uint %59 %uint_11 +;CHECK: %61 = OpArrayLength %uint %54 1 +;CHECK: %62 = OpULessThanEqual %bool %60 %61 +;CHECK: OpSelectionMerge %63 None +;CHECK: OpBranchConditional %62 %64 %63 +;CHECK: %64 = OpLabel +;CHECK: %65 = OpIAdd %uint %59 %uint_0 +;CHECK: %67 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %65 +;CHECK: OpStore %67 %uint_11 +;CHECK: %69 = OpIAdd %uint %59 %uint_1 +;CHECK: %70 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %69 +;CHECK: OpStore %70 %uint_23 +;CHECK: %72 = OpIAdd %uint %59 %uint_2 +;CHECK: %73 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %72 +;CHECK: OpStore %73 %45 +;CHECK: %75 = OpIAdd %uint %59 %uint_3 +;CHECK: %76 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %75 +;CHECK: OpStore %76 %uint_4 +;CHECK: %79 = OpLoad %v4float %gl_FragCoord +;CHECK: %81 = OpBitcast %v4uint %79 +;CHECK: %82 = OpCompositeExtract %uint %81 0 +;CHECK: %83 = OpIAdd %uint %59 %uint_4 +;CHECK: %84 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %83 +;CHECK: OpStore %84 %82 +;CHECK: %85 = OpCompositeExtract %uint %81 1 +;CHECK: %87 = OpIAdd %uint %59 %uint_5 +;CHECK: %88 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %87 +;CHECK: OpStore %88 %85 +;CHECK: %90 = OpIAdd %uint %59 %uint_7 +;CHECK: %91 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %90 +;CHECK: OpStore %91 %46 +;CHECK: %93 = OpIAdd %uint %59 %uint_8 +;CHECK: %94 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %93 +;CHECK: OpStore %94 %47 +;CHECK: %96 = OpIAdd %uint %59 %uint_9 +;CHECK: %97 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %96 +;CHECK: OpStore %97 %48 +;CHECK: %99 = OpIAdd %uint %59 %uint_10 +;CHECK: %100 = OpAccessChain %_ptr_StorageBuffer_uint %54 %uint_1 %99 +;CHECK: OpStore %100 %49 +;CHECK: OpBranch %63 +;CHECK: %63 = OpLabel +;CHECK: OpReturn +;CHECK: OpFunctionEnd + )"; + + SetTargetEnv(SPV_ENV_VULKAN_1_2); + SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + SinglePassRunAndMatch(text, true, 7u, 23u, false, + false, true, true, true); } // TODO(greg-lunarg): Add tests to verify handling of these cases: diff --git a/third_party/spirv-tools/test/opt/instruction_list_test.cpp b/third_party/spirv-tools/test/opt/instruction_list_test.cpp index e745790a3b..2c3c24290a 100644 --- a/third_party/spirv-tools/test/opt/instruction_list_test.cpp +++ b/third_party/spirv-tools/test/opt/instruction_list_test.cpp @@ -35,7 +35,7 @@ class TestInstruction : public Instruction { public: TestInstruction() : Instruction() { created_instructions_.push_back(this); } - ~TestInstruction() { deleted_instructions_.push_back(this); } + ~TestInstruction() override{ deleted_instructions_.push_back(this); } static std::vector created_instructions_; static std::vector deleted_instructions_; diff --git a/third_party/spirv-tools/test/opt/interp_fixup_test.cpp b/third_party/spirv-tools/test/opt/interp_fixup_test.cpp new file mode 100644 index 0000000000..a43a29c092 --- /dev/null +++ b/third_party/spirv-tools/test/opt/interp_fixup_test.cpp @@ -0,0 +1,172 @@ +// Copyright (c) 2021 The Khronos Group Inc. +// Copyright (c) 2021 Valve Corporation +// Copyright (c) 2021 LunarG Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#include "gmock/gmock.h" +#include "test/opt/pass_fixture.h" +#include "test/opt/pass_utils.h" + +namespace spvtools { +namespace opt { +namespace { + +using InterpFixupTest = PassTest<::testing::Test>; + +using ::testing::HasSubstr; + +TEST_F(InterpFixupTest, FixInterpAtSample) { + const std::string text = R"( + OpCapability Shader + OpCapability InterpolationFunction + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %MainPs "MainPs" %i_vPositionOs %_entryPointOutput + OpExecutionMode %MainPs OriginUpperLeft + OpSource HLSL 500 + OpName %MainPs "MainPs" + OpName %i_vPositionOs "i.vPositionOs" + OpName %_entryPointOutput "@entryPointOutput" + OpDecorate %i_vPositionOs Location 0 + OpDecorate %_entryPointOutput Location 0 + %void = OpTypeVoid + %6 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %float_0 = OpConstant %float 0 + %10 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0 + %uint = OpTypeInt 32 0 + %uint_0 = OpConstant %uint 0 + %uint_4 = OpConstant %uint 4 + %bool = OpTypeBool + %int = OpTypeInt 32 1 + %int_1 = OpConstant %int 1 +%_ptr_Input_v4float = OpTypePointer Input %v4float +%i_vPositionOs = OpVariable %_ptr_Input_v4float Input +%_ptr_Output_v4float = OpTypePointer Output %v4float +%_entryPointOutput = OpVariable %_ptr_Output_v4float Output + %MainPs = OpFunction %void None %6 + %19 = OpLabel + %20 = OpLoad %v4float %i_vPositionOs + OpBranch %21 + %21 = OpLabel + %22 = OpPhi %v4float %10 %19 %23 %24 + %25 = OpPhi %uint %uint_0 %19 %26 %24 + %27 = OpULessThan %bool %25 %uint_4 + OpLoopMerge %28 %24 None + OpBranchConditional %27 %24 %28 + %24 = OpLabel + %29 = OpExtInst %v4float %1 InterpolateAtSample %20 %25 +;CHECK: %29 = OpExtInst %v4float %1 InterpolateAtSample %i_vPositionOs %25 + %30 = OpCompositeExtract %float %29 0 + %31 = OpCompositeExtract %float %22 0 + %32 = OpFAdd %float %31 %30 + %23 = OpCompositeInsert %v4float %32 %22 0 + %26 = OpIAdd %uint %25 %int_1 + OpBranch %21 + %28 = OpLabel + OpStore %_entryPointOutput %22 + OpReturn + OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, false); +} + +TEST_F(InterpFixupTest, FixInterpAtCentroid) { + const std::string text = R"( + OpCapability Shader + OpCapability InterpolationFunction + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %MainPs "MainPs" %i_vPositionOs %_entryPointOutput + OpExecutionMode %MainPs OriginUpperLeft + OpSource HLSL 500 + OpName %MainPs "MainPs" + OpName %i_vPositionOs "i.vPositionOs" + OpName %_entryPointOutput "@entryPointOutput" + OpDecorate %i_vPositionOs Location 0 + OpDecorate %_entryPointOutput Location 0 + %void = OpTypeVoid + %6 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %float_0 = OpConstant %float 0 + %10 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0 +%_ptr_Input_v4float = OpTypePointer Input %v4float +%i_vPositionOs = OpVariable %_ptr_Input_v4float Input +%_ptr_Output_v4float = OpTypePointer Output %v4float +%_entryPointOutput = OpVariable %_ptr_Output_v4float Output + %MainPs = OpFunction %void None %6 + %13 = OpLabel + %14 = OpLoad %v4float %i_vPositionOs + %15 = OpExtInst %v4float %1 InterpolateAtCentroid %14 +;CHECK: %15 = OpExtInst %v4float %1 InterpolateAtCentroid %i_vPositionOs + %16 = OpCompositeExtract %float %15 0 + %17 = OpCompositeInsert %v4float %16 %10 0 + OpStore %_entryPointOutput %17 + OpReturn + OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, false); +} + +TEST_F(InterpFixupTest, FixInterpAtOffset) { + const std::string text = R"( + OpCapability Shader + OpCapability InterpolationFunction + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %MainPs "MainPs" %i_vPositionOs %_entryPointOutput + OpExecutionMode %MainPs OriginUpperLeft + OpSource HLSL 500 + OpName %MainPs "MainPs" + OpName %i_vPositionOs "i.vPositionOs" + OpName %_entryPointOutput "@entryPointOutput" + OpDecorate %i_vPositionOs Location 0 + OpDecorate %_entryPointOutput Location 0 + %void = OpTypeVoid + %6 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %float_0 = OpConstant %float 0 + %10 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0 + %v2float = OpTypeVector %float 2 +%float_0_0625 = OpConstant %float 0.0625 + %13 = OpConstantComposite %v2float %float_0_0625 %float_0_0625 +%_ptr_Input_v4float = OpTypePointer Input %v4float +%i_vPositionOs = OpVariable %_ptr_Input_v4float Input +%_ptr_Output_v4float = OpTypePointer Output %v4float +%_entryPointOutput = OpVariable %_ptr_Output_v4float Output + %MainPs = OpFunction %void None %6 + %16 = OpLabel + %17 = OpLoad %v4float %i_vPositionOs + %18 = OpExtInst %v4float %1 InterpolateAtOffset %17 %13 +;CHECK: %18 = OpExtInst %v4float %1 InterpolateAtOffset %i_vPositionOs %13 + %19 = OpCompositeExtract %float %18 0 + %20 = OpCompositeInsert %v4float %19 %10 0 + OpStore %_entryPointOutput %20 + OpReturn + OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, false); +} + +} // namespace +} // namespace opt +} // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/ir_loader_test.cpp b/third_party/spirv-tools/test/opt/ir_loader_test.cpp index 8b77aa33b0..475dd2351e 100644 --- a/third_party/spirv-tools/test/opt/ir_loader_test.cpp +++ b/third_party/spirv-tools/test/opt/ir_loader_test.cpp @@ -19,7 +19,7 @@ #include #include -#include "gtest/gtest.h" +#include "gmock/gmock.h" #include "source/opt/build_module.h" #include "source/opt/def_use_manager.h" #include "source/opt/ir_context.h" @@ -29,6 +29,8 @@ namespace spvtools { namespace opt { namespace { +using ::testing::ContainerEq; + constexpr uint32_t kOpLineOperandLineIndex = 1; void DoRoundTripCheck(const std::string& text) { @@ -236,6 +238,100 @@ TEST(IrBuilder, DistributeLineDebugInfo) { } } +TEST(IrBuilder, BuildModule_WithoutExtraLines) { + const std::string text = R"(OpCapability Shader +OpMemoryModel Logical Simple +OpEntryPoint Vertex %main "main" +%file = OpString "my file" +%void = OpTypeVoid +%voidfn = OpTypeFunction %void +%float = OpTypeFloat 32 +%float_1 = OpConstant %float 1 +%main = OpFunction %void None %voidfn +%100 = OpLabel +%1 = OpFAdd %float %float_1 %float_1 +OpLine %file 1 0 +%2 = OpFMul %float %1 %1 +%3 = OpFSub %float %2 %2 +OpReturn +OpFunctionEnd +)"; + + std::vector binary; + SpirvTools t(SPV_ENV_UNIVERSAL_1_1); + ASSERT_TRUE(t.Assemble(text, &binary, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS)); + + // This is the function we're testing. + std::unique_ptr context = BuildModule( + SPV_ENV_UNIVERSAL_1_5, nullptr, binary.data(), binary.size(), false); + ASSERT_NE(nullptr, context); + + spvtools::opt::analysis::DefUseManager* def_use_mgr = + context->get_def_use_mgr(); + + std::vector opcodes; + for (auto* inst = def_use_mgr->GetDef(1); + inst && (inst->opcode() != SpvOpFunctionEnd); inst = inst->NextNode()) { + inst->ForEachInst( + [&opcodes](spvtools::opt::Instruction* sub_inst) { + opcodes.push_back(sub_inst->opcode()); + }, + true); + } + + EXPECT_THAT(opcodes, + ContainerEq(std::vector{SpvOpFAdd, SpvOpLine, SpvOpFMul, + SpvOpFSub, SpvOpReturn})); +} + +TEST(IrBuilder, BuildModule_WithExtraLines_IsDefault) { + const std::string text = R"(OpCapability Shader +OpMemoryModel Logical Simple +OpEntryPoint Vertex %main "main" +%file = OpString "my file" +%void = OpTypeVoid +%voidfn = OpTypeFunction %void +%float = OpTypeFloat 32 +%float_1 = OpConstant %float 1 +%main = OpFunction %void None %voidfn +%100 = OpLabel +%1 = OpFAdd %float %float_1 %float_1 +OpLine %file 1 0 +%2 = OpFMul %float %1 %1 +%3 = OpFSub %float %2 %2 +OpReturn +OpFunctionEnd +)"; + + std::vector binary; + + SpirvTools t(SPV_ENV_UNIVERSAL_1_1); + ASSERT_TRUE(t.Assemble(text, &binary, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS)); + + // This is the function we're testing. + std::unique_ptr context = + BuildModule(SPV_ENV_UNIVERSAL_1_5, nullptr, binary.data(), binary.size()); + + spvtools::opt::analysis::DefUseManager* def_use_mgr = + context->get_def_use_mgr(); + + std::vector opcodes; + for (auto* inst = def_use_mgr->GetDef(1); + inst && (inst->opcode() != SpvOpFunctionEnd); inst = inst->NextNode()) { + inst->ForEachInst( + [&opcodes](spvtools::opt::Instruction* sub_inst) { + opcodes.push_back(sub_inst->opcode()); + }, + true); + } + + EXPECT_THAT(opcodes, ContainerEq(std::vector{ + SpvOpFAdd, SpvOpLine, SpvOpFMul, SpvOpLine, + SpvOpFSub, SpvOpLine, SpvOpReturn})); +} + TEST(IrBuilder, ConsumeDebugInfoInst) { // /* HLSL */ // diff --git a/third_party/spirv-tools/test/opt/legalize_vector_shuffle_test.cpp b/third_party/spirv-tools/test/opt/legalize_vector_shuffle_test.cpp deleted file mode 100644 index 07d96eb379..0000000000 --- a/third_party/spirv-tools/test/opt/legalize_vector_shuffle_test.cpp +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include - -#include "test/opt/pass_fixture.h" -#include "test/opt/pass_utils.h" - -namespace spvtools { -namespace opt { -namespace { - -using LegalizeVectorShuffleTest = PassTest<::testing::Test>; - -void operator+=(std::vector& lhs, const char* rhs) { - lhs.push_back(rhs); -} - -void operator+=(std::vector& lhs, - const std::vector rhs) { - for (auto elem : rhs) lhs.push_back(elem); -} - -std::vector header = { - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", - "%v3uint = OpTypeVector %uint 3"}; - -std::string GetTestString(const char* shuffle) { - std::vector result = header; - result += {"%_ptr_Function_v3uint = OpTypePointer Function %v3uint", - "%void = OpTypeVoid", - "%6 = OpTypeFunction %void", - "%1 = OpFunction %void None %6", - "%7 = OpLabel", - "%8 = OpVariable %_ptr_Function_v3uint Function", - "%9 = OpLoad %v3uint %8", - "%10 = OpLoad %v3uint %8"}; - result += shuffle; - result += {"OpReturn", "OpFunctionEnd"}; - return JoinAllInsts(result); -} - -TEST_F(LegalizeVectorShuffleTest, Changed) { - std::string input = - GetTestString("%11 = OpVectorShuffle %v3uint %9 %10 2 1 0xFFFFFFFF"); - std::string expected = - GetTestString("%11 = OpVectorShuffle %v3uint %9 %10 2 1 0"); - - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -TEST_F(LegalizeVectorShuffleTest, FunctionUnchanged) { - std::string input = - GetTestString("%11 = OpVectorShuffle %v3uint %9 %10 2 1 0"); - std::string expected = - GetTestString("%11 = OpVectorShuffle %v3uint %9 %10 2 1 0"); - - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -} // namespace -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/local_single_store_elim_test.cpp b/third_party/spirv-tools/test/opt/local_single_store_elim_test.cpp index d015dfba7c..c94ff372b3 100644 --- a/third_party/spirv-tools/test/opt/local_single_store_elim_test.cpp +++ b/third_party/spirv-tools/test/opt/local_single_store_elim_test.cpp @@ -1403,18 +1403,20 @@ TEST_F(LocalSingleStoreElimTest, AddDebugValueforStoreOutOfDebugDeclareScope) { %param_var_pos = OpVariable %_ptr_Function_v4float Function %param_var_color = OpVariable %_ptr_Function_v4float Function %55 = OpLoad %v4float %in_var_POSITION + OpLine %7 6 23 OpStore %param_var_pos %55 + OpNoLine %56 = OpLoad %v4float %in_var_COLOR ;CHECK: DebugNoScope ;CHECK-NOT: OpLine ;CHECK: [[pos:%\w+]] = OpLoad %v4float %in_var_POSITION ;CHECK: [[color:%\w+]] = OpLoad %v4float %in_var_COLOR - OpStore %param_var_color %56 - %93 = OpExtInst %void %1 DebugScope %48 - OpLine %7 6 23 - %73 = OpExtInst %void %1 DebugDeclare %53 %param_var_pos %52 OpLine %7 7 23 + OpStore %param_var_color %56 + OpNoLine + %93 = OpExtInst %void %1 DebugScope %48 + %73 = OpExtInst %void %1 DebugDeclare %53 %param_var_pos %52 %74 = OpExtInst %void %1 DebugDeclare %51 %param_var_color %52 ;CHECK: OpLine [[file:%\w+]] 6 23 ;CHECK-NEXT: {{%\w+}} = OpExtInst %void {{%\w+}} DebugValue [[dbg_pos]] [[pos]] [[empty_expr:%\w+]] diff --git a/third_party/spirv-tools/test/opt/local_ssa_elim_test.cpp b/third_party/spirv-tools/test/opt/local_ssa_elim_test.cpp index ff42193c5c..ca9aba334c 100644 --- a/third_party/spirv-tools/test/opt/local_ssa_elim_test.cpp +++ b/third_party/spirv-tools/test/opt/local_ssa_elim_test.cpp @@ -2261,9 +2261,13 @@ TEST_F(LocalSSAElimTest, AddDebugValueForFunctionParameterWithPhi) { %69 = OpExtInst %void %1 DebugLexicalBlock %60 7 21 %68 %70 = OpExtInst %void %1 DebugLocalVariable %11 %59 %60 6 26 %67 FlagIsLocal 2 +; CHECK: [[color_name:%\w+]] = OpString "color" +; CHECK: [[pos_name:%\w+]] = OpString "pos" ; CHECK: [[i_name:%\w+]] = OpString "i" ; CHECK: [[null_expr:%\w+]] = OpExtInst %void [[ext:%\w+]] DebugExpression ; CHECK: [[dbg_i:%\w+]] = OpExtInst %void [[ext]] DebugLocalVariable [[i_name]] {{%\w+}} {{%\w+}} 6 16 {{%\w+}} FlagIsLocal 1 +; CHECK: [[dbg_color:%\w+]] = OpExtInst %void [[ext]] DebugLocalVariable [[color_name]] {{%\w+}} {{%\w+}} 15 23 +; CHECK: [[dbg_pos:%\w+]] = OpExtInst %void [[ext]] DebugLocalVariable [[pos_name]] {{%\w+}} {{%\w+}} 14 23 %71 = OpExtInst %void %1 DebugLocalVariable %15 %65 %60 6 16 %67 FlagIsLocal 1 %72 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %62 %59 %59 %73 = OpExtInst %void %1 DebugFunction %16 %72 %60 14 1 %61 %14 FlagIsProtected|FlagIsPrivate 15 %156 @@ -2282,13 +2286,23 @@ TEST_F(LocalSSAElimTest, AddDebugValueForFunctionParameterWithPhi) { %169 = OpExtInst %void %1 DebugNoScope %param_var_pos = OpVariable %_ptr_Function_v4float Function %param_var_color = OpVariable %_ptr_Function_v4float Function + OpLine %7 100 105 %80 = OpLoad %v4float %in_var_POSITION OpStore %param_var_pos %80 + OpNoLine + OpLine %7 200 205 %81 = OpLoad %v4float %in_var_COLOR OpStore %param_var_color %81 + OpNoLine %170 = OpExtInst %void %1 DebugScope %73 + +; CHECK: OpLine {{%\w+}} 100 105 +; CHECK: DebugValue [[dbg_pos]] %124 = OpExtInst %void %1 DebugDeclare %78 %param_var_pos %77 +; CHECK: OpLine {{%\w+}} 200 205 +; CHECK: DebugValue [[dbg_color]] %125 = OpExtInst %void %1 DebugDeclare %76 %param_var_color %77 + %171 = OpExtInst %void %1 DebugScope %74 OpLine %7 17 18 @@ -2371,6 +2385,154 @@ TEST_F(LocalSSAElimTest, AddDebugValueForFunctionParameterWithPhi) { SinglePassRunAndMatch(text, true); } +TEST_F(LocalSSAElimTest, DebugValueWithIndexesInForLoop) { + // #version 140 + // + // in vec4 BC; + // out float fo; + // + // struct T { + // float a; + // float f; + // }; + // + // struct value { + // int x; + // int y; + // T z; + // }; + // + // void main() + // { + // value v; + // v.z.f = 0.0; + // for (int i=0; i<4; i++) { + // v.z.f = v.z.f + BC[i]; + // } + // fo = v.z.f; + // } + + const std::string text = R"( +; CHECK: [[f_name:%\w+]] = OpString "f" +; CHECK: [[dbg_f:%\w+]] = OpExtInst %void [[ext:%\d+]] DebugLocalVariable [[f_name]] + +; CHECK: OpStore %f %float_0 +; CHECK-NEXT: OpExtInst %void [[ext]] DebugValue [[dbg_f]] %float_0 [[null_expr:%\d+]] %int_2 %int_1 + +; CHECK-NOT: DebugDeclare + +; CHECK: [[loop_head:%\w+]] = OpLabel +; CHECK: [[phi0:%\w+]] = OpPhi %float %float_0 +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_f]] [[phi0]] [[null_expr]] %int_2 %int_1 +; CHECK: OpLoopMerge [[loop_merge:%\w+]] [[loop_cont:%\w+]] None +; CHECK-NEXT: OpBranch [[loop_body:%\w+]] + +; CHECK-NEXT: [[loop_body]] = OpLabel +; CHECK: OpBranchConditional {{%\w+}} [[bb:%\w+]] [[loop_merge]] + +; CHECK: [[bb]] = OpLabel +; CHECK: OpStore %f [[f_val:%\w+]] +; CHECK-NEXT: OpExtInst %void [[ext]] DebugValue [[dbg_f]] [[f_val]] [[null_expr]] %int_2 %int_1 +; CHECK-NEXT: OpBranch [[loop_cont]] + +; CHECK: [[loop_cont]] = OpLabel +; CHECK: OpBranch [[loop_head]] + +; CHECK: [[loop_merge]] = OpLabel + +OpCapability Shader +%1 = OpExtInstImport "GLSL.std.450" +%ext = OpExtInstImport "OpenCL.DebugInfo.100" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" %BC %fo +OpExecutionMode %main OriginUpperLeft +%file_name = OpString "test" +OpSource GLSL 140 +%float_name = OpString "float" +%main_name = OpString "main" +%f_name = OpString "f" +%i_name = OpString "i" +OpName %main "main" +OpName %f "f" +OpName %i "i" +OpName %BC "BC" +OpName %fo "fo" +%void = OpTypeVoid +%8 = OpTypeFunction %void +%float = OpTypeFloat 32 +%_ptr_Function_float = OpTypePointer Function %float +%float_0 = OpConstant %float 0 +%int = OpTypeInt 32 1 +%uint = OpTypeInt 32 0 +%uint_32 = OpConstant %uint 32 +%_ptr_Function_int = OpTypePointer Function %int +%int_0 = OpConstant %int 0 +%int_4 = OpConstant %int 4 +%bool = OpTypeBool +%v4float = OpTypeVector %float 4 +%_ptr_Input_v4float = OpTypePointer Input %v4float +%BC = OpVariable %_ptr_Input_v4float Input +%_ptr_Input_float = OpTypePointer Input %float +%int_1 = OpConstant %int 1 +%int_2 = OpConstant %int 2 +%_ptr_Output_float = OpTypePointer Output %float +%fo = OpVariable %_ptr_Output_float Output +%deref = OpExtInst %void %ext DebugOperation Deref +%null_expr = OpExtInst %void %ext DebugExpression +%deref_expr = OpExtInst %void %ext DebugExpression %deref +%src = OpExtInst %void %ext DebugSource %file_name +%cu = OpExtInst %void %ext DebugCompilationUnit 1 4 %src HLSL +%dbg_tf = OpExtInst %void %ext DebugTypeBasic %float_name %uint_32 Float +%dbg_v4f = OpExtInst %void %ext DebugTypeVector %dbg_tf 4 +%main_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f +%dbg_main = OpExtInst %void %ext DebugFunction %main_name %main_ty %src 0 0 %cu %main_name FlagIsProtected|FlagIsPrivate 10 %main +%dbg_f = OpExtInst %void %ext DebugLocalVariable %f_name %dbg_v4f %src 0 0 %dbg_main FlagIsLocal +%dbg_i = OpExtInst %void %ext DebugLocalVariable %i_name %dbg_v4f %src 0 0 %dbg_main FlagIsLocal +%main = OpFunction %void None %8 +%22 = OpLabel +%s0 = OpExtInst %void %ext DebugScope %dbg_main +%f = OpVariable %_ptr_Function_float Function +%i = OpVariable %_ptr_Function_int Function +OpStore %f %float_0 +OpStore %i %int_0 +%decl0 = OpExtInst %void %ext DebugValue %dbg_f %f %deref_expr %int_2 %int_1 +%decl1 = OpExtInst %void %ext DebugDeclare %dbg_i %i %null_expr +OpBranch %23 +%23 = OpLabel +%s1 = OpExtInst %void %ext DebugScope %dbg_main +OpLoopMerge %24 %25 None +OpBranch %26 +%26 = OpLabel +%s2 = OpExtInst %void %ext DebugScope %dbg_main +%27 = OpLoad %int %i +%28 = OpSLessThan %bool %27 %int_4 +OpBranchConditional %28 %29 %24 +%29 = OpLabel +%s3 = OpExtInst %void %ext DebugScope %dbg_main +%30 = OpLoad %float %f +%31 = OpLoad %int %i +%32 = OpAccessChain %_ptr_Input_float %BC %31 +%33 = OpLoad %float %32 +%34 = OpFAdd %float %30 %33 +OpStore %f %34 +OpBranch %25 +%25 = OpLabel +%s4 = OpExtInst %void %ext DebugScope %dbg_main +%35 = OpLoad %int %i +%36 = OpIAdd %int %35 %int_1 +OpStore %i %36 +OpBranch %23 +%24 = OpLabel +%s5 = OpExtInst %void %ext DebugScope %dbg_main +%37 = OpLoad %float %f +OpStore %fo %37 +OpReturn +OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, true); +} + TEST_F(LocalSSAElimTest, PartiallyKillDebugDeclare) { // For a reference variable e.g., int i in the following example, // we do not propagate DebugValue for a store or phi instruction diff --git a/third_party/spirv-tools/test/opt/loop_optimizations/unroll_simple.cpp b/third_party/spirv-tools/test/opt/loop_optimizations/unroll_simple.cpp index 016316aea9..6a3cb6ee52 100644 --- a/third_party/spirv-tools/test/opt/loop_optimizations/unroll_simple.cpp +++ b/third_party/spirv-tools/test/opt/loop_optimizations/unroll_simple.cpp @@ -3401,6 +3401,215 @@ OpFunctionEnd SinglePassRunAndCheck(shader, output, false); } +TEST_F(PassClassTest, UnrollWithPhiReferencesPhi) { + const std::string text = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %color + OpExecutionMode %main OriginUpperLeft + OpSource HLSL 600 + OpName %main "main" + OpName %color "color" + OpDecorate %color Location 0 + %uint = OpTypeInt 32 0 + %float = OpTypeFloat 32 + %float_0 = OpConstant %float 0 + %float_1 = OpConstant %float 1 + %uint_1 = OpConstant %uint 1 + %uint_3 = OpConstant %uint 3 + %void = OpTypeVoid + %11 = OpTypeFunction %void + %bool = OpTypeBool + %v4float = OpTypeVector %float 4 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %color = OpVariable %_ptr_Output_v4float Output + %main = OpFunction %void None %11 + %15 = OpLabel + OpBranch %16 + %16 = OpLabel + %17 = OpPhi %float %float_0 %15 %18 %19 + %18 = OpPhi %float %float_1 %15 %20 %19 + %21 = OpPhi %uint %uint_1 %15 %22 %19 + %23 = OpULessThanEqual %bool %21 %uint_3 + OpLoopMerge %24 %19 Unroll + OpBranchConditional %23 %25 %24 + %25 = OpLabel + +; First loop iteration +; CHECK: [[next_phi1_0:%\w+]] = OpFSub %float %float_1 %float_0 + +; Second loop iteration +; CHECK: [[next_phi1_1:%\w+]] = OpFSub %float [[next_phi1_0]] %float_1 + +; Third loop iteration +; CHECK: OpFSub %float [[next_phi1_1]] [[next_phi1_0]] + + %20 = OpFSub %float %18 %17 + OpBranch %19 + %19 = OpLabel + %22 = OpIAdd %uint %21 %uint_1 + OpBranch %16 + %24 = OpLabel + OpReturn + OpFunctionEnd +)"; + + std::unique_ptr context = + BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + Module* module = context->module(); + EXPECT_NE(nullptr, module) << "Assembling failed for ushader:\n" + << text << std::endl; + + LoopUnroller loop_unroller; + SetDisassembleOptions(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER | + SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES); + SinglePassRunAndMatch(text, true); +} + +TEST_F(PassClassTest, UnrollWithDoublePhiReferencesPhi) { + const std::string text = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %color + OpExecutionMode %main OriginUpperLeft + OpSource HLSL 600 + OpName %main "main" + OpName %color "color" + OpDecorate %color Location 0 + %uint = OpTypeInt 32 0 + %float = OpTypeFloat 32 + %float_0 = OpConstant %float 0 + %float_1 = OpConstant %float 1 + %uint_1 = OpConstant %uint 1 + %uint_3 = OpConstant %uint 3 + %void = OpTypeVoid + %11 = OpTypeFunction %void + %bool = OpTypeBool + %v4float = OpTypeVector %float 4 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %color = OpVariable %_ptr_Output_v4float Output + %main = OpFunction %void None %11 + %15 = OpLabel + OpBranch %16 + %16 = OpLabel + %17 = OpPhi %float %float_1 %15 %18 %19 + %18 = OpPhi %float %float_0 %15 %20 %19 + %20 = OpPhi %float %float_1 %15 %21 %19 + %22 = OpPhi %uint %uint_1 %15 %23 %19 + %24 = OpULessThanEqual %bool %22 %uint_3 + OpLoopMerge %25 %19 Unroll + OpBranchConditional %24 %26 %25 + %26 = OpLabel + +; First loop iteration +; CHECK: [[next_phi1_0:%\w+]] = OpFSub %float %float_1 %float_0 +; CHECK: OpFMul %float %float_1 + +; Second loop iteration +; CHECK: [[next_phi1_1:%\w+]] = OpFSub %float [[next_phi1_0]] %float_1 +; CHECK: OpFMul %float %float_0 + +; Third loop iteration +; CHECK: OpFSub %float [[next_phi1_1]] [[next_phi1_0]] +; CHECK: OpFMul %float %float_1 + + %21 = OpFSub %float %20 %18 + %27 = OpFMul %float %17 %21 + OpBranch %19 + %19 = OpLabel + %23 = OpIAdd %uint %22 %uint_1 + OpBranch %16 + %25 = OpLabel + OpReturn + OpFunctionEnd +)"; + + std::unique_ptr context = + BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + Module* module = context->module(); + EXPECT_NE(nullptr, module) << "Assembling failed for ushader:\n" + << text << std::endl; + + LoopUnroller loop_unroller; + SetDisassembleOptions(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER | + SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES); + SinglePassRunAndMatch(text, true); +} + +TEST_F(PassClassTest, PartialUnrollWithPhiReferencesPhi) { + // With LocalMultiStoreElimPass + const std::string text = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %main "main" %color + OpExecutionMode %main OriginUpperLeft + OpSource HLSL 600 + OpName %main "main" + OpName %color "color" + OpDecorate %color Location 0 + %uint = OpTypeInt 32 0 + %float = OpTypeFloat 32 + %float_0 = OpConstant %float 0 + %float_1 = OpConstant %float 1 + %uint_1 = OpConstant %uint 1 + %uint_3 = OpConstant %uint 3 + %void = OpTypeVoid + %11 = OpTypeFunction %void + %bool = OpTypeBool + %v4float = OpTypeVector %float 4 +%_ptr_Output_v4float = OpTypePointer Output %v4float + %color = OpVariable %_ptr_Output_v4float Output + %main = OpFunction %void None %11 + %15 = OpLabel + OpBranch %16 + %16 = OpLabel + %17 = OpPhi %float %float_0 %15 %18 %19 + %18 = OpPhi %float %float_1 %15 %20 %19 + %21 = OpPhi %uint %uint_1 %15 %22 %19 + %23 = OpULessThanEqual %bool %21 %uint_3 + OpLoopMerge %24 %19 Unroll + OpBranchConditional %23 %25 %24 + %25 = OpLabel + +; CHECK: [[phi0_0:%\w+]] = OpPhi {{%\w+}} {{%\w+}} {{%\w+}} [[phi1_0:%\w+]] +; CHECK: [[phi1_0]] = OpPhi {{%\w+}} {{%\w+}} {{%\w+}} [[sub:%\w+]] + +; CHECK: [[sub]] = OpFSub {{%\w+}} [[phi1_0]] [[phi0_0]] + +; CHECK: [[phi0_1:%\w+]] = OpPhi {{%\w+}} [[phi0_0]] +; CHECK: [[phi1_1:%\w+]] = OpPhi {{%\w+}} [[phi1_0]] + +; CHECK: [[sub:%\w+]] = OpFSub {{%\w+}} [[phi1_1]] [[phi0_1]] + +; CHECK: OpFSub {{%\w+}} [[sub]] [[phi1_1]] + + %20 = OpFSub %float %18 %17 + OpBranch %19 + %19 = OpLabel + %22 = OpIAdd %uint %21 %uint_1 + OpBranch %16 + %24 = OpLabel + OpReturn + OpFunctionEnd + )"; + + std::unique_ptr context = + BuildModule(SPV_ENV_UNIVERSAL_1_1, nullptr, text, + SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS); + Module* module = context->module(); + EXPECT_NE(nullptr, module) << "Assembling failed for ushader:\n" + << text << std::endl; + + LoopUnroller loop_unroller; + SetDisassembleOptions(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER); + SinglePassRunAndMatch>(text, true); +} + } // namespace } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/optimizer_test.cpp b/third_party/spirv-tools/test/opt/optimizer_test.cpp index 945aa78265..a51638a1ea 100644 --- a/third_party/spirv-tools/test/opt/optimizer_test.cpp +++ b/third_party/spirv-tools/test/opt/optimizer_test.cpp @@ -221,498 +221,6 @@ TEST(Optimizer, CanRegisterPassesFromFlags) { EXPECT_EQ(msg_level, SPV_MSG_ERROR); } -TEST(Optimizer, VulkanToWebGPUSetsCorrectPasses) { - Optimizer opt(SPV_ENV_VULKAN_1_1); - opt.RegisterVulkanToWebGPUPasses(); - std::vector pass_names = opt.GetPassNames(); - - std::vector registered_passes; - for (auto name = pass_names.begin(); name != pass_names.end(); ++name) - registered_passes.push_back(*name); - - std::vector expected_passes = {"eliminate-dead-branches", - "eliminate-dead-code-aggressive", - "eliminate-dead-const", - "flatten-decorations", - "strip-atomic-counter-memory", - "generate-webgpu-initializers", - "legalize-vector-shuffle", - "split-invalid-unreachable", - "compact-ids"}; - std::sort(registered_passes.begin(), registered_passes.end()); - std::sort(expected_passes.begin(), expected_passes.end()); - - ASSERT_EQ(registered_passes.size(), expected_passes.size()); - for (size_t i = 0; i < registered_passes.size(); i++) - EXPECT_EQ(registered_passes[i], expected_passes[i]); -} - -struct VulkanToWebGPUPassCase { - // Input SPIR-V - std::string input; - // Expected result SPIR-V - std::string expected; - // Specific pass under test, used for logging messages. - std::string pass; -}; - -using VulkanToWebGPUPassTest = - PassTest<::testing::TestWithParam>; - -TEST_P(VulkanToWebGPUPassTest, Ran) { - std::vector binary; - { - SpirvTools tools(SPV_ENV_VULKAN_1_1); - tools.Assemble(GetParam().input, &binary); - } - - Optimizer opt(SPV_ENV_VULKAN_1_1); - opt.RegisterVulkanToWebGPUPasses(); - - std::vector optimized; - class ValidatorOptions validator_options; - ASSERT_TRUE(opt.Run(binary.data(), binary.size(), &optimized, - validator_options, true)) - << GetParam().input << "\n"; - std::string disassembly; - { - SpirvTools tools(SPV_ENV_WEBGPU_0); - tools.Disassemble(optimized.data(), optimized.size(), &disassembly); - } - - EXPECT_EQ(GetParam().expected, disassembly) - << "Was expecting pass '" << GetParam().pass << "' to have been run.\n"; -} - -INSTANTIATE_TEST_SUITE_P( - Optimizer, VulkanToWebGPUPassTest, - ::testing::ValuesIn(std::vector{ - // FlattenDecorations - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Fragment %main \"main\" %hue %saturation %value\n" - "OpExecutionMode %main OriginUpperLeft\n" - "OpDecorate %group Flat\n" - "OpDecorate %group NoPerspective\n" - "%group = OpDecorationGroup\n" - "%void = OpTypeVoid\n" - "%void_fn = OpTypeFunction %void\n" - "%float = OpTypeFloat 32\n" - "%_ptr_Input_float = OpTypePointer Input %float\n" - "%hue = OpVariable %_ptr_Input_float Input\n" - "%saturation = OpVariable %_ptr_Input_float Input\n" - "%value = OpVariable %_ptr_Input_float Input\n" - "%main = OpFunction %void None %void_fn\n" - "%entry = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Fragment %1 \"main\" %2 %3 %4\n" - "OpExecutionMode %1 OriginUpperLeft\n" - "%void = OpTypeVoid\n" - "%6 = OpTypeFunction %void\n" - "%float = OpTypeFloat 32\n" - "%_ptr_Input_float = OpTypePointer Input %float\n" - "%2 = OpVariable %_ptr_Input_float Input\n" - "%3 = OpVariable %_ptr_Input_float Input\n" - "%4 = OpVariable %_ptr_Input_float Input\n" - "%1 = OpFunction %void None %6\n" - "%9 = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "flatten-decorations"}, - // Eliminate Dead Constants - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %func \"shader\"\n" - "%u32 = OpTypeInt 32 0\n" - "%u32_ptr = OpTypePointer Workgroup %u32\n" - "%u32_var = OpVariable %u32_ptr Workgroup\n" - "%u32_1 = OpConstant %u32 1\n" - "%cross_device = OpConstant %u32 0\n" - "%relaxed = OpConstant %u32 0\n" - "%acquire_release_atomic_counter_workgroup = OpConstant %u32 1288\n" - "%void = OpTypeVoid\n" - "%void_f = OpTypeFunction %void\n" - "%func = OpFunction %void None %void_f\n" - "%label = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%_ptr_Workgroup_uint = OpTypePointer Workgroup %uint\n" - "%4 = OpVariable %_ptr_Workgroup_uint Workgroup\n" - "%void = OpTypeVoid\n" - "%6 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %6\n" - "%7 = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - "eliminate-dead-const"}, - // Strip Atomic Counter Memory - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %func \"shader\"\n" - "%u32 = OpTypeInt 32 0\n" - "%u32_ptr = OpTypePointer Workgroup %u32\n" - "%u32_var = OpVariable %u32_ptr Workgroup\n" - "%u32_0 = OpConstant %u32 0\n" - "%u32_1 = OpConstant %u32 1\n" - "%cross_device = OpConstant %u32 0\n" - "%acquire_release_atomic_counter_workgroup = OpConstant %u32 1288\n" - "%void = OpTypeVoid\n" - "%void_f = OpTypeFunction %void\n" - "%func = OpFunction %void None %void_f\n" - "%label = OpLabel\n" - " OpAtomicStore %u32_var %cross_device " - "%acquire_release_atomic_counter_workgroup %u32_1\n" - "%val1 = OpAtomicIIncrement %u32 %u32_var %cross_device " - "%acquire_release_atomic_counter_workgroup\n" - "%val2 = OpAtomicCompareExchange %u32 %u32_var %cross_device " - "%acquire_release_atomic_counter_workgroup " - "%acquire_release_atomic_counter_workgroup %u32_0 %u32_0\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%_ptr_Workgroup_uint = OpTypePointer Workgroup %uint\n" - "%4 = OpVariable %_ptr_Workgroup_uint Workgroup\n" - "%uint_0 = OpConstant %uint 0\n" - "%uint_1 = OpConstant %uint 1\n" - "%uint_0_0 = OpConstant %uint 0\n" - "%void = OpTypeVoid\n" - "%9 = OpTypeFunction %void\n" - "%uint_264 = OpConstant %uint 264\n" - "%1 = OpFunction %void None %9\n" - "%11 = OpLabel\n" - "OpAtomicStore %4 %uint_0_0 %uint_264 %uint_1\n" - "%12 = OpAtomicIIncrement %uint %4 %uint_0_0 %uint_264\n" - "%13 = OpAtomicCompareExchange %uint %4 %uint_0_0 %uint_264 %uint_264 " - "%uint_0 %uint_0\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "strip-atomic-counter-memory"}, - // Generate WebGPU Initializers - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %func \"shader\"\n" - "%u32 = OpTypeInt 32 0\n" - "%u32_ptr = OpTypePointer Private %u32\n" - "%u32_var = OpVariable %u32_ptr Private\n" - "%u32_0 = OpConstant %u32 0\n" - "%void = OpTypeVoid\n" - "%void_f = OpTypeFunction %void\n" - "%func = OpFunction %void None %void_f\n" - "%label = OpLabel\n" - "OpStore %u32_var %u32_0\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%_ptr_Private_uint = OpTypePointer Private %uint\n" - "%4 = OpConstantNull %uint\n" - "%5 = OpVariable %_ptr_Private_uint Private %4\n" - "%uint_0 = OpConstant %uint 0\n" - "%void = OpTypeVoid\n" - "%8 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %8\n" - "%9 = OpLabel\n" - "OpStore %5 %uint_0\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "generate-webgpu-initializers"}, - // Legalize Vector Shuffle - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%v3uint = OpTypeVector %uint 3\n" - "%_ptr_Function_v3uint = OpTypePointer Function %v3uint\n" - "%void = OpTypeVoid\n" - "%6 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %6\n" - "%7 = OpLabel\n" - "%8 = OpVariable %_ptr_Function_v3uint Function\n" - "%9 = OpLoad %v3uint %8\n" - "%10 = OpLoad %v3uint %8\n" - "%11 = OpVectorShuffle %v3uint %9 %10 2 1 0xFFFFFFFF\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%v3uint = OpTypeVector %uint 3\n" - "%_ptr_Function_v3uint = OpTypePointer Function %v3uint\n" - "%void = OpTypeVoid\n" - "%6 = OpTypeFunction %void\n" - "%7 = OpConstantNull %v3uint\n" - "%1 = OpFunction %void None %6\n" - "%8 = OpLabel\n" - "%9 = OpVariable %_ptr_Function_v3uint Function %7\n" - "%10 = OpLoad %v3uint %9\n" - "%11 = OpLoad %v3uint %9\n" - "%12 = OpVectorShuffle %v3uint %10 %11 2 1 0\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "legalize-vector-shuffle"}, - // Split Invalid Unreachable - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%uint_1 = OpConstant %uint 1\n" - "%uint_2 = OpConstant %uint 2\n" - "%void = OpTypeVoid\n" - "%bool = OpTypeBool\n" - "%7 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %7\n" - "%8 = OpLabel\n" - "OpBranch %9\n" - "%9 = OpLabel\n" - "OpLoopMerge %10 %11 None\n" - "OpBranch %12\n" - "%12 = OpLabel\n" - "%13 = OpSLessThan %bool %uint_1 %uint_2\n" - "OpSelectionMerge %11 None\n" - "OpBranchConditional %13 %14 %15\n" - "%14 = OpLabel\n" - "OpReturn\n" - "%15 = OpLabel\n" - "OpReturn\n" - "%10 = OpLabel\n" - "OpUnreachable\n" - "%11 = OpLabel\n" - "OpBranch %9\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%uint_1 = OpConstant %uint 1\n" - "%uint_2 = OpConstant %uint 2\n" - "%void = OpTypeVoid\n" - "%bool = OpTypeBool\n" - "%7 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %7\n" - "%8 = OpLabel\n" - "OpBranch %9\n" - "%9 = OpLabel\n" - "OpLoopMerge %10 %11 None\n" - "OpBranch %12\n" - "%12 = OpLabel\n" - "%13 = OpSLessThan %bool %uint_1 %uint_2\n" - "OpSelectionMerge %14 None\n" - "OpBranchConditional %13 %15 %16\n" - "%15 = OpLabel\n" - "OpReturn\n" - "%16 = OpLabel\n" - "OpReturn\n" - "%10 = OpLabel\n" - "OpUnreachable\n" - "%14 = OpLabel\n" - "OpUnreachable\n" - "%11 = OpLabel\n" - "OpBranch %9\n" - "OpFunctionEnd\n", - // pass - "split-invalid-unreachable"}, - // Compact IDs - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1000 \"shader\"\n" - "%10 = OpTypeVoid\n" - "%100 = OpTypeFunction %10\n" - "%1000 = OpFunction %10 None %100\n" - "%10000 = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%void = OpTypeVoid\n" - "%3 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %3\n" - "%4 = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "compact-ids"}})); - -TEST(Optimizer, WebGPUToVulkanSetsCorrectPasses) { - Optimizer opt(SPV_ENV_WEBGPU_0); - opt.RegisterWebGPUToVulkanPasses(); - std::vector pass_names = opt.GetPassNames(); - - std::vector registered_passes; - for (auto name = pass_names.begin(); name != pass_names.end(); ++name) - registered_passes.push_back(*name); - - std::vector expected_passes = {"decompose-initialized-variables", - "compact-ids"}; - std::sort(registered_passes.begin(), registered_passes.end()); - std::sort(expected_passes.begin(), expected_passes.end()); - - ASSERT_EQ(registered_passes.size(), expected_passes.size()); - for (size_t i = 0; i < registered_passes.size(); i++) - EXPECT_EQ(registered_passes[i], expected_passes[i]); -} - -struct WebGPUToVulkanPassCase { - // Input SPIR-V - std::string input; - // Expected result SPIR-V - std::string expected; - // Specific pass under test, used for logging messages. - std::string pass; -}; - -using WebGPUToVulkanPassTest = - PassTest<::testing::TestWithParam>; - -TEST_P(WebGPUToVulkanPassTest, Ran) { - std::vector binary; - { - SpirvTools tools(SPV_ENV_WEBGPU_0); - tools.Assemble(GetParam().input, &binary); - } - - Optimizer opt(SPV_ENV_WEBGPU_0); - opt.RegisterWebGPUToVulkanPasses(); - - std::vector optimized; - class ValidatorOptions validator_options; - ASSERT_TRUE(opt.Run(binary.data(), binary.size(), &optimized, - validator_options, true)); - std::string disassembly; - { - SpirvTools tools(SPV_ENV_VULKAN_1_1); - tools.Disassemble(optimized.data(), optimized.size(), &disassembly); - } - - EXPECT_EQ(GetParam().expected, disassembly) - << "Was expecting pass '" << GetParam().pass << "' to have been run.\n"; -} - -INSTANTIATE_TEST_SUITE_P( - Optimizer, WebGPUToVulkanPassTest, - ::testing::ValuesIn(std::vector{ - // Decompose Initialized Variables - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%_ptr_Function_uint = OpTypePointer Function %uint\n" - "%4 = OpConstantNull %uint\n" - "%void = OpTypeVoid\n" - "%6 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %6\n" - "%7 = OpLabel\n" - "%8 = OpVariable %_ptr_Function_uint Function %4\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%uint = OpTypeInt 32 0\n" - "%_ptr_Function_uint = OpTypePointer Function %uint\n" - "%4 = OpConstantNull %uint\n" - "%void = OpTypeVoid\n" - "%6 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %6\n" - "%7 = OpLabel\n" - "%8 = OpVariable %_ptr_Function_uint Function\n" - "OpStore %8 %4\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "decompose-initialized-variables"}, - // Compact IDs - {// input - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1000 \"shader\"\n" - "%10 = OpTypeVoid\n" - "%100 = OpTypeFunction %10\n" - "%1000 = OpFunction %10 None %100\n" - "%10000 = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // expected - "OpCapability Shader\n" - "OpCapability VulkanMemoryModel\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical Vulkan\n" - "OpEntryPoint Vertex %1 \"shader\"\n" - "%void = OpTypeVoid\n" - "%3 = OpTypeFunction %void\n" - "%1 = OpFunction %void None %3\n" - "%4 = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n", - // pass - "compact-ids"}})); TEST(Optimizer, RemoveNop) { // Test that OpNops are removed even if no optimizations are run. @@ -754,7 +262,7 @@ OpFunctionEnd << before << "\n"; std::string disassembly; { - SpirvTools tools(SPV_ENV_WEBGPU_0); + SpirvTools tools(SPV_ENV_VULKAN_1_1); tools.Disassemble(optimized.data(), optimized.size(), &disassembly); } @@ -762,6 +270,124 @@ OpFunctionEnd << "Was expecting the OpNop to have been removed."; } +TEST(Optimizer, AvoidIntegrityCheckForExtraLineInfo) { + // Test that it avoids the integrity check when no optimizations are run and + // OpLines are propagated. + const std::string before = R"(OpCapability Shader +OpCapability Linkage +OpMemoryModel Logical GLSL450 +%1 = OpString "Test" +%void = OpTypeVoid +%3 = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%_ptr_Function_uint = OpTypePointer Function %uint +%6 = OpFunction %void None %3 +%7 = OpLabel +OpLine %1 10 0 +%8 = OpVariable %_ptr_Function_uint Function +OpLine %1 10 0 +%9 = OpVariable %_ptr_Function_uint Function +OpLine %1 20 0 +OpReturn +OpFunctionEnd +)"; + + const std::string after = R"(OpCapability Shader +OpCapability Linkage +OpMemoryModel Logical GLSL450 +%1 = OpString "Test" +%void = OpTypeVoid +%3 = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%_ptr_Function_uint = OpTypePointer Function %uint +%6 = OpFunction %void None %3 +%7 = OpLabel +OpLine %1 10 0 +%8 = OpVariable %_ptr_Function_uint Function +%9 = OpVariable %_ptr_Function_uint Function +OpLine %1 20 0 +OpReturn +OpFunctionEnd +)"; + + std::vector binary; + SpirvTools tools(SPV_ENV_VULKAN_1_1); + tools.Assemble(before, &binary); + + Optimizer opt(SPV_ENV_VULKAN_1_1); + + std::vector optimized; + class ValidatorOptions validator_options; + ASSERT_TRUE(opt.Run(binary.data(), binary.size(), &optimized, + validator_options, true)) + << before << "\n"; + + std::string disassembly; + tools.Disassemble(optimized.data(), optimized.size(), &disassembly); + + EXPECT_EQ(after, disassembly) + << "Was expecting the OpLine to have been propagated."; +} + +TEST(Optimizer, AvoidIntegrityCheckForDebugScope) { + // Test that it avoids the integrity check when the code contains DebugScope. + const std::string before = R"(OpCapability Shader +%1 = OpExtInstImport "OpenCL.DebugInfo.100" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +%3 = OpString "simple_vs.hlsl" +OpSource HLSL 600 %3 +OpName %main "main" +%void = OpTypeVoid +%5 = OpTypeFunction %void +%6 = OpExtInst %void %1 DebugSource %3 +%7 = OpExtInst %void %1 DebugCompilationUnit 2 4 %6 HLSL +%main = OpFunction %void None %5 +%14 = OpLabel +%26 = OpExtInst %void %1 DebugScope %7 +OpReturn +%27 = OpExtInst %void %1 DebugNoScope +OpFunctionEnd +)"; + + const std::string after = R"(OpCapability Shader +%1 = OpExtInstImport "OpenCL.DebugInfo.100" +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +%3 = OpString "simple_vs.hlsl" +OpSource HLSL 600 %3 +OpName %main "main" +%void = OpTypeVoid +%5 = OpTypeFunction %void +%6 = OpExtInst %void %1 DebugSource %3 +%7 = OpExtInst %void %1 DebugCompilationUnit 2 4 %6 HLSL +%main = OpFunction %void None %5 +%8 = OpLabel +%11 = OpExtInst %void %1 DebugScope %7 +OpReturn +%12 = OpExtInst %void %1 DebugNoScope +OpFunctionEnd +)"; + + std::vector binary; + SpirvTools tools(SPV_ENV_VULKAN_1_1); + tools.Assemble(before, &binary); + + Optimizer opt(SPV_ENV_VULKAN_1_1); + + std::vector optimized; + ASSERT_TRUE(opt.Run(binary.data(), binary.size(), &optimized)) + << before << "\n"; + + std::string disassembly; + tools.Disassemble(optimized.data(), optimized.size(), &disassembly); + + EXPECT_EQ(after, disassembly) + << "Was expecting the result id of DebugScope to have been changed."; +} + } // namespace } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/remove_unused_interface_variables_test.cpp b/third_party/spirv-tools/test/opt/remove_unused_interface_variables_test.cpp new file mode 100644 index 0000000000..ddf027f1ba --- /dev/null +++ b/third_party/spirv-tools/test/opt/remove_unused_interface_variables_test.cpp @@ -0,0 +1,185 @@ +// Copyright (c) 2021 ZHOU He +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "gmock/gmock.h" +#include "test/opt/assembly_builder.h" +#include "test/opt/pass_fixture.h" +#include "test/opt/pass_utils.h" + +namespace spvtools { +namespace opt { +namespace { + +using RemoveUnusedInterfaceVariablesTest = PassTest<::testing::Test>; + +static const std::string expected = R"(OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %_Z5func1v "_Z5func1v" %out_var_SV_TARGET +OpEntryPoint Fragment %_Z5func2v "_Z5func2v" %out_var_SV_TARGET_0 +OpExecutionMode %_Z5func1v OriginUpperLeft +OpExecutionMode %_Z5func2v OriginUpperLeft +OpSource HLSL 630 +OpName %type_cba "type.cba" +OpMemberName %type_cba 0 "color" +OpName %cba "cba" +OpName %out_var_SV_TARGET "out.var.SV_TARGET" +OpName %out_var_SV_TARGET_0 "out.var.SV_TARGET" +OpName %_Z5func1v "_Z5func1v" +OpName %_Z5func2v "_Z5func2v" +OpDecorate %out_var_SV_TARGET Location 0 +OpDecorate %out_var_SV_TARGET_0 Location 0 +OpDecorate %cba DescriptorSet 0 +OpDecorate %cba Binding 0 +OpMemberDecorate %type_cba 0 Offset 0 +OpDecorate %type_cba Block +%int = OpTypeInt 32 1 +%int_0 = OpConstant %int 0 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%type_cba = OpTypeStruct %v4float +%_ptr_Uniform_type_cba = OpTypePointer Uniform %type_cba +%_ptr_Output_v4float = OpTypePointer Output %v4float +%void = OpTypeVoid +%14 = OpTypeFunction %void +%_ptr_Uniform_v4float = OpTypePointer Uniform %v4float +%cba = OpVariable %_ptr_Uniform_type_cba Uniform +%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output +%out_var_SV_TARGET_0 = OpVariable %_ptr_Output_v4float Output +%_Z5func1v = OpFunction %void None %14 +%16 = OpLabel +%17 = OpAccessChain %_ptr_Uniform_v4float %cba %int_0 +%18 = OpLoad %v4float %17 +OpStore %out_var_SV_TARGET %18 +OpReturn +OpFunctionEnd +%_Z5func2v = OpFunction %void None %14 +%19 = OpLabel +%20 = OpAccessChain %_ptr_Uniform_v4float %cba %int_0 +%21 = OpLoad %v4float %20 +OpStore %out_var_SV_TARGET_0 %21 +OpReturn +OpFunctionEnd +)"; + +TEST_F(RemoveUnusedInterfaceVariablesTest, RemoveUnusedVariable) { + const std::string text = R"(OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %_Z5func1v "_Z5func1v" %out_var_SV_TARGET %out_var_SV_TARGET_0 +OpEntryPoint Fragment %_Z5func2v "_Z5func2v" %out_var_SV_TARGET %out_var_SV_TARGET_0 +OpExecutionMode %_Z5func1v OriginUpperLeft +OpExecutionMode %_Z5func2v OriginUpperLeft +OpSource HLSL 630 +OpName %type_cba "type.cba" +OpMemberName %type_cba 0 "color" +OpName %cba "cba" +OpName %out_var_SV_TARGET "out.var.SV_TARGET" +OpName %out_var_SV_TARGET_0 "out.var.SV_TARGET" +OpName %_Z5func1v "_Z5func1v" +OpName %_Z5func2v "_Z5func2v" +OpDecorate %out_var_SV_TARGET Location 0 +OpDecorate %out_var_SV_TARGET_0 Location 0 +OpDecorate %cba DescriptorSet 0 +OpDecorate %cba Binding 0 +OpMemberDecorate %type_cba 0 Offset 0 +OpDecorate %type_cba Block +%int = OpTypeInt 32 1 +%int_0 = OpConstant %int 0 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%type_cba = OpTypeStruct %v4float +%_ptr_Uniform_type_cba = OpTypePointer Uniform %type_cba +%_ptr_Output_v4float = OpTypePointer Output %v4float +%void = OpTypeVoid +%14 = OpTypeFunction %void +%_ptr_Uniform_v4float = OpTypePointer Uniform %v4float +%cba = OpVariable %_ptr_Uniform_type_cba Uniform +%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output +%out_var_SV_TARGET_0 = OpVariable %_ptr_Output_v4float Output +%_Z5func1v = OpFunction %void None %14 +%16 = OpLabel +%17 = OpAccessChain %_ptr_Uniform_v4float %cba %int_0 +%18 = OpLoad %v4float %17 +OpStore %out_var_SV_TARGET %18 +OpReturn +OpFunctionEnd +%_Z5func2v = OpFunction %void None %14 +%19 = OpLabel +%20 = OpAccessChain %_ptr_Uniform_v4float %cba %int_0 +%21 = OpLoad %v4float %20 +OpStore %out_var_SV_TARGET_0 %21 +OpReturn +OpFunctionEnd +)"; + + SinglePassRunAndCheck(text, expected, + true, true); +} + +TEST_F(RemoveUnusedInterfaceVariablesTest, FixMissingVariable) { + const std::string text = R"(OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %_Z5func1v "_Z5func1v" +OpEntryPoint Fragment %_Z5func2v "_Z5func2v" +OpExecutionMode %_Z5func1v OriginUpperLeft +OpExecutionMode %_Z5func2v OriginUpperLeft +OpSource HLSL 630 +OpName %type_cba "type.cba" +OpMemberName %type_cba 0 "color" +OpName %cba "cba" +OpName %out_var_SV_TARGET "out.var.SV_TARGET" +OpName %out_var_SV_TARGET_0 "out.var.SV_TARGET" +OpName %_Z5func1v "_Z5func1v" +OpName %_Z5func2v "_Z5func2v" +OpDecorate %out_var_SV_TARGET Location 0 +OpDecorate %out_var_SV_TARGET_0 Location 0 +OpDecorate %cba DescriptorSet 0 +OpDecorate %cba Binding 0 +OpMemberDecorate %type_cba 0 Offset 0 +OpDecorate %type_cba Block +%int = OpTypeInt 32 1 +%int_0 = OpConstant %int 0 +%float = OpTypeFloat 32 +%v4float = OpTypeVector %float 4 +%type_cba = OpTypeStruct %v4float +%_ptr_Uniform_type_cba = OpTypePointer Uniform %type_cba +%_ptr_Output_v4float = OpTypePointer Output %v4float +%void = OpTypeVoid +%14 = OpTypeFunction %void +%_ptr_Uniform_v4float = OpTypePointer Uniform %v4float +%cba = OpVariable %_ptr_Uniform_type_cba Uniform +%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output +%out_var_SV_TARGET_0 = OpVariable %_ptr_Output_v4float Output +%_Z5func1v = OpFunction %void None %14 +%16 = OpLabel +%17 = OpAccessChain %_ptr_Uniform_v4float %cba %int_0 +%18 = OpLoad %v4float %17 +OpStore %out_var_SV_TARGET %18 +OpReturn +OpFunctionEnd +%_Z5func2v = OpFunction %void None %14 +%19 = OpLabel +%20 = OpAccessChain %_ptr_Uniform_v4float %cba %int_0 +%21 = OpLoad %v4float %20 +OpStore %out_var_SV_TARGET_0 %21 +OpReturn +OpFunctionEnd +)"; + + SinglePassRunAndCheck(text, expected, + true, true); +} + +} // namespace +} // namespace opt +} // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/scalar_replacement_test.cpp b/third_party/spirv-tools/test/opt/scalar_replacement_test.cpp index 2130f6959c..8115f5fb57 100644 --- a/third_party/spirv-tools/test/opt/scalar_replacement_test.cpp +++ b/third_party/spirv-tools/test/opt/scalar_replacement_test.cpp @@ -2079,6 +2079,164 @@ OpFunctionEnd SinglePassRunAndMatch(text, true); } +TEST_F(ScalarReplacementTest, DebugValueWithIndex) { + const std::string text = R"( +OpCapability Shader +OpCapability Linkage +%ext = OpExtInstImport "OpenCL.DebugInfo.100" +OpMemoryModel Logical GLSL450 +%test = OpString "test" +OpName %6 "simple_struct" +%1 = OpTypeVoid +%2 = OpTypeInt 32 0 +%uint_32 = OpConstant %2 32 +%3 = OpTypeStruct %2 %2 %2 %2 +%4 = OpTypePointer Function %3 +%5 = OpTypePointer Function %2 +%6 = OpTypeFunction %2 +%7 = OpConstantNull %3 +%8 = OpConstant %2 0 +%9 = OpConstant %2 1 +%10 = OpConstant %2 2 +%11 = OpConstant %2 3 +%deref = OpExtInst %1 %ext DebugOperation Deref +%deref_expr = OpExtInst %1 %ext DebugExpression %deref +%null_expr = OpExtInst %1 %ext DebugExpression +%src = OpExtInst %1 %ext DebugSource %test +%cu = OpExtInst %1 %ext DebugCompilationUnit 1 4 %src HLSL +%dbg_tf = OpExtInst %1 %ext DebugTypeBasic %test %uint_32 Float +%main_ty = OpExtInst %1 %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %1 +%dbg_main = OpExtInst %1 %ext DebugFunction %test %main_ty %src 0 0 %cu %test FlagIsProtected|FlagIsPrivate 0 %12 +%dbg_foo = OpExtInst %1 %ext DebugLocalVariable %test %dbg_tf %src 0 0 %dbg_main FlagIsLocal +%12 = OpFunction %2 None %6 +%13 = OpLabel +%scope = OpExtInst %1 %ext DebugScope %dbg_main +%14 = OpVariable %4 Function %7 + +; CHECK: [[deref:%\w+]] = OpExtInst %void [[ext:%\w+]] DebugOperation Deref +; CHECK: [[deref_expr:%\w+]] = OpExtInst %void [[ext]] DebugExpression [[deref]] +; CHECK: [[dbg_local_var:%\w+]] = OpExtInst %void [[ext]] DebugLocalVariable +; CHECK: [[repl3:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: [[repl2:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: [[repl1:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: [[repl0:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl0]] [[deref_expr]] %uint_0 %uint_1 %uint_2 %int_0 +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl1]] [[deref_expr]] %uint_0 %uint_1 %uint_2 %int_1 +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl2]] [[deref_expr]] %uint_0 %uint_1 %uint_2 %int_2 +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl3]] [[deref_expr]] %uint_0 %uint_1 %uint_2 %int_3 +%value = OpExtInst %1 %ext DebugValue %dbg_foo %14 %deref_expr %8 %9 %10 + +%15 = OpInBoundsAccessChain %5 %14 %8 +%16 = OpLoad %2 %15 +%17 = OpAccessChain %5 %14 %10 +%18 = OpLoad %2 %17 +%19 = OpIAdd %2 %16 %18 +OpReturnValue %19 +OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, true); +} + +TEST_F(ScalarReplacementTest, DebugDeclareForVariableInOtherBB) { + const std::string text = R"( +OpCapability Shader +OpCapability Linkage +%ext = OpExtInstImport "OpenCL.DebugInfo.100" +OpMemoryModel Logical GLSL450 +%test = OpString "test" +OpName %6 "simple_struct" +%1 = OpTypeVoid +%2 = OpTypeInt 32 0 +%uint_32 = OpConstant %2 32 +%3 = OpTypeStruct %2 %2 %2 %2 +%4 = OpTypePointer Function %3 +%5 = OpTypePointer Function %2 +%6 = OpTypeFunction %2 +%7 = OpConstantNull %3 +%8 = OpConstant %2 0 +%9 = OpConstant %2 1 +%10 = OpConstant %2 2 +%11 = OpConstant %2 3 +%deref = OpExtInst %1 %ext DebugOperation Deref +%deref_expr = OpExtInst %1 %ext DebugExpression %deref +%null_expr = OpExtInst %1 %ext DebugExpression +%src = OpExtInst %1 %ext DebugSource %test +%cu = OpExtInst %1 %ext DebugCompilationUnit 1 4 %src HLSL +%dbg_tf = OpExtInst %1 %ext DebugTypeBasic %test %uint_32 Float +%main_ty = OpExtInst %1 %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %1 +%dbg_main = OpExtInst %1 %ext DebugFunction %test %main_ty %src 0 0 %cu %test FlagIsProtected|FlagIsPrivate 0 %12 +%dbg_foo = OpExtInst %1 %ext DebugLocalVariable %test %dbg_tf %src 0 0 %dbg_main FlagIsLocal +%12 = OpFunction %2 None %6 +%13 = OpLabel +%scope = OpExtInst %1 %ext DebugScope %dbg_main +%14 = OpVariable %4 Function %7 + +; CHECK: [[dbg_local_var:%\w+]] = OpExtInst %void [[ext:%\w+]] DebugLocalVariable +; CHECK: [[repl3:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl3]] [[deref_expr:%\w+]] %int_3 +; CHECK: [[repl2:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl2]] [[deref_expr]] %int_2 +; CHECK: [[repl1:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl1]] [[deref_expr]] %int_1 +; CHECK: [[repl0:%\w+]] = OpVariable %_ptr_Function_uint Function +; CHECK: OpExtInst %void [[ext]] DebugValue [[dbg_local_var]] [[repl0]] [[deref_expr]] %int_0 + +OpBranch %20 +%20 = OpLabel +%value = OpExtInst %1 %ext DebugDeclare %dbg_foo %14 %null_expr +%15 = OpInBoundsAccessChain %5 %14 %8 +%16 = OpLoad %2 %15 +%17 = OpAccessChain %5 %14 %10 +%18 = OpLoad %2 %17 +%19 = OpIAdd %2 %16 %18 +OpReturnValue %19 +OpFunctionEnd +)"; + + SinglePassRunAndMatch(text, true); +} + +TEST_F(ScalarReplacementTest, ImageTexelPointer) { + // Test whether the scalar replacement correctly checks the + // OpImageTexelPointer user of an aggregate with an image type. + const std::string text = R"( +; +; CHECK: [[imgTy:%\w+]] = OpTypeImage %uint Buffer 2 0 0 2 R32ui +; CHECK: [[ptrImgTy:%\w+]] = OpTypePointer Function [[imgTy]] +; CHECK: [[img:%\w+]] = OpVariable [[ptrImgTy]] Function +; CHECK: [[imgTexelPtr:%\w+]] = OpImageTexelPointer {{%\w+}} [[img]] %uint_0 %uint_0 +; CHECK: OpAtomicIAdd %uint [[imgTexelPtr]] %uint_1 %uint_0 %uint_1 +; +OpCapability Shader +OpCapability SampledBuffer +OpCapability ImageBuffer +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %1 "main" +OpExecutionMode %1 LocalSize 64 1 1 +%void = OpTypeVoid +%uint = OpTypeInt 32 0 +%uint_0 = OpConstant %uint 0 +%uint_1 = OpConstant %uint 1 +%_ptr_Image_uint = OpTypePointer Image %uint +%type_buffer_image = OpTypeImage %uint Buffer 2 0 0 2 R32ui +%_ptr_Function_type_buffer_image = OpTypePointer Function %type_buffer_image +%image_struct = OpTypeStruct %type_buffer_image %type_buffer_image +%_ptr_Function_image_struct = OpTypePointer Function %image_struct +%func = OpTypeFunction %void +%1 = OpFunction %void None %func +%2 = OpLabel +%3 = OpVariable %_ptr_Function_image_struct Function +%4 = OpAccessChain %_ptr_Function_type_buffer_image %3 %uint_1 +%5 = OpImageTexelPointer %_ptr_Image_uint %4 %uint_0 %uint_0 +%6 = OpAtomicIAdd %uint %5 %uint_1 %uint_0 %uint_1 +OpReturn +OpFunctionEnd + )"; + + SinglePassRunAndMatch(text, false); +} + } // namespace } // namespace opt } // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/split_invalid_unreachable_test.cpp b/third_party/spirv-tools/test/opt/split_invalid_unreachable_test.cpp deleted file mode 100644 index 520af0154b..0000000000 --- a/third_party/spirv-tools/test/opt/split_invalid_unreachable_test.cpp +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include - -#include "test/opt/pass_fixture.h" -#include "test/opt/pass_utils.h" - -namespace spvtools { -namespace opt { -namespace { - -using SplitInvalidUnreachableTest = PassTest<::testing::Test>; - -std::string spirv_header = R"(OpCapability Shader -OpCapability VulkanMemoryModel -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical Vulkan -OpEntryPoint Vertex %1 "shader" -%uint = OpTypeInt 32 0 -%uint_1 = OpConstant %uint 1 -%uint_2 = OpConstant %uint 2 -%void = OpTypeVoid -%bool = OpTypeBool -%7 = OpTypeFunction %void -)"; - -std::string function_head = R"(%1 = OpFunction %void None %7 -%8 = OpLabel -OpBranch %9 -)"; - -std::string function_tail = "OpFunctionEnd\n"; - -std::string GetLoopMergeBlock(std::string block_id, std::string merge_id, - std::string continue_id, std::string body_id) { - std::string result; - result += block_id + " = OpLabel\n"; - result += "OpLoopMerge " + merge_id + " " + continue_id + " None\n"; - result += "OpBranch " + body_id + "\n"; - return result; -} - -std::string GetSelectionMergeBlock(std::string block_id, - std::string condition_id, - std::string merge_id, std::string true_id, - std::string false_id) { - std::string result; - result += block_id + " = OpLabel\n"; - result += condition_id + " = OpSLessThan %bool %uint_1 %uint_2\n"; - result += "OpSelectionMerge " + merge_id + " None\n"; - result += "OpBranchConditional " + condition_id + " " + true_id + " " + - false_id + "\n"; - - return result; -} - -std::string GetReturnBlock(std::string block_id) { - std::string result; - result += block_id + " = OpLabel\n"; - result += "OpReturn\n"; - return result; -} - -std::string GetUnreachableBlock(std::string block_id) { - std::string result; - result += block_id + " = OpLabel\n"; - result += "OpUnreachable\n"; - return result; -} - -std::string GetBranchBlock(std::string block_id, std::string target_id) { - std::string result; - result += block_id + " = OpLabel\n"; - result += "OpBranch " + target_id + "\n"; - return result; -} - -TEST_F(SplitInvalidUnreachableTest, NoInvalidBlocks) { - std::string input = spirv_header + function_head; - input += GetLoopMergeBlock("%9", "%10", "%11", "%12"); - input += GetSelectionMergeBlock("%12", "%13", "%14", "%15", "%16"); - input += GetReturnBlock("%15"); - input += GetReturnBlock("%16"); - input += GetUnreachableBlock("%10"); - input += GetBranchBlock("%11", "%9"); - input += GetUnreachableBlock("%14"); - input += function_tail; - - SinglePassRunAndCheck(input, input, - /* skip_nop = */ false); -} - -TEST_F(SplitInvalidUnreachableTest, SelectionInLoop) { - std::string input = spirv_header + function_head; - input += GetLoopMergeBlock("%9", "%10", "%11", "%12"); - input += GetSelectionMergeBlock("%12", "%13", "%11", "%15", "%16"); - input += GetReturnBlock("%15"); - input += GetReturnBlock("%16"); - input += GetUnreachableBlock("%10"); - input += GetBranchBlock("%11", "%9"); - input += function_tail; - - std::string expected = spirv_header + function_head; - expected += GetLoopMergeBlock("%9", "%10", "%11", "%12"); - expected += GetSelectionMergeBlock("%12", "%13", "%16", "%14", "%15"); - expected += GetReturnBlock("%14"); - expected += GetReturnBlock("%15"); - expected += GetUnreachableBlock("%10"); - expected += GetUnreachableBlock("%16"); - expected += GetBranchBlock("%11", "%9"); - expected += function_tail; - - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -TEST_F(SplitInvalidUnreachableTest, LoopInSelection) { - std::string input = spirv_header + function_head; - input += GetSelectionMergeBlock("%9", "%10", "%11", "%12", "%13"); - input += GetLoopMergeBlock("%12", "%14", "%11", "%15"); - input += GetReturnBlock("%13"); - input += GetUnreachableBlock("%14"); - input += GetBranchBlock("%11", "%12"); - input += GetReturnBlock("%15"); - input += function_tail; - - std::string expected = spirv_header + function_head; - expected += GetSelectionMergeBlock("%9", "%10", "%16", "%12", "%13"); - expected += GetLoopMergeBlock("%12", "%14", "%11", "%15"); - expected += GetReturnBlock("%13"); - expected += GetUnreachableBlock("%14"); - expected += GetUnreachableBlock("%16"); - expected += GetBranchBlock("%11", "%12"); - expected += GetReturnBlock("%15"); - expected += function_tail; - - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -} // namespace -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/test/opt/strip_atomic_counter_memory_test.cpp b/third_party/spirv-tools/test/opt/strip_atomic_counter_memory_test.cpp deleted file mode 100644 index 90daa59c1d..0000000000 --- a/third_party/spirv-tools/test/opt/strip_atomic_counter_memory_test.cpp +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright (c) 2019 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include - -#include "test/opt/pass_fixture.h" -#include "test/opt/pass_utils.h" - -namespace spvtools { -namespace opt { -namespace { - -typedef std::tuple StripAtomicCounterMemoryParam; - -using MemorySemanticsModified = - PassTest<::testing::TestWithParam>; -using NonMemorySemanticsUnmodifiedTest = PassTest<::testing::Test>; - -void operator+=(std::vector& lhs, const char* rhs) { - lhs.push_back(rhs); -} - -std::string GetConstDecl(std::string val) { - std::string decl; - decl += "%uint_" + val + " = OpConstant %uint " + val; - return decl; -} - -std::string GetUnchangedString(std::string(generate_inst)(std::string), - std::string val) { - std::string decl = GetConstDecl(val); - std::string inst = generate_inst(val); - - std::vector result = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", -"%_ptr_Workgroup_uint = OpTypePointer Workgroup %uint", - "%4 = OpVariable %_ptr_Workgroup_uint Workgroup", - "%uint_0 = OpConstant %uint 0", - "%uint_1 = OpConstant %uint 1", - "%void = OpTypeVoid", - "%8 = OpTypeFunction %void", - decl.c_str(), - "%1 = OpFunction %void None %8", - "%10 = OpLabel", - inst.c_str(), - "OpReturn", - "OpFunctionEnd" - // clang-format on - }; - return JoinAllInsts(result); -} - -std::string GetChangedString(std::string(generate_inst)(std::string), - std::string orig, std::string changed) { - std::string orig_decl = GetConstDecl(orig); - std::string changed_decl = GetConstDecl(changed); - std::string inst = generate_inst(changed); - - std::vector result = { - // clang-format off - "OpCapability Shader", - "OpCapability VulkanMemoryModel", - "OpExtension \"SPV_KHR_vulkan_memory_model\"", - "OpMemoryModel Logical Vulkan", - "OpEntryPoint Vertex %1 \"shader\"", - "%uint = OpTypeInt 32 0", -"%_ptr_Workgroup_uint = OpTypePointer Workgroup %uint", - "%4 = OpVariable %_ptr_Workgroup_uint Workgroup", - "%uint_0 = OpConstant %uint 0", - "%uint_1 = OpConstant %uint 1", - "%void = OpTypeVoid", - "%8 = OpTypeFunction %void", - orig_decl.c_str() }; - // clang-format on - if (changed != "0") result += changed_decl.c_str(); - result += "%1 = OpFunction %void None %8"; - result += "%10 = OpLabel"; - result += inst.c_str(); - result += "OpReturn"; - result += "OpFunctionEnd"; - return JoinAllInsts(result); -} - -std::tuple GetInputAndExpected( - std::string(generate_inst)(std::string), - StripAtomicCounterMemoryParam param) { - std::string orig = std::get<0>(param); - std::string changed = std::get<1>(param); - std::string input = GetUnchangedString(generate_inst, orig); - std::string expected = orig == changed - ? GetUnchangedString(generate_inst, changed) - : GetChangedString(generate_inst, orig, changed); - return std::make_tuple(input, expected); -} - -std::string GetOpControlBarrierInst(std::string val) { - return "OpControlBarrier %uint_1 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpControlBarrier) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpControlBarrierInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpMemoryBarrierInst(std::string val) { - return "OpMemoryBarrier %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpMemoryBarrier) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpMemoryBarrierInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicLoadInst(std::string val) { - return "%11 = OpAtomicLoad %uint %4 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpAtomicLoad) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicLoadInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicStoreInst(std::string val) { - return "OpAtomicStore %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicStore) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicStoreInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicExchangeInst(std::string val) { - return "%11 = OpAtomicExchange %uint %4 %uint_1 %uint_" + val + " %uint_0"; -} - -TEST_P(MemorySemanticsModified, OpAtomicExchange) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicExchangeInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicCompareExchangeInst(std::string val) { - return "%11 = OpAtomicCompareExchange %uint %4 %uint_1 %uint_" + val + - " %uint_" + val + " %uint_0 %uint_0"; -} - -TEST_P(MemorySemanticsModified, OpAtomicCompareExchange) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicCompareExchangeInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicCompareExchangeWeakInst(std::string val) { - return "%11 = OpAtomicCompareExchangeWeak %uint %4 %uint_1 %uint_" + val + - " %uint_" + val + " %uint_0 %uint_0"; -} - -TEST_P(MemorySemanticsModified, OpAtomicCompareExchangeWeak) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicCompareExchangeWeakInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicIIncrementInst(std::string val) { - return "%11 = OpAtomicIIncrement %uint %4 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpAtomicIIncrement) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicIIncrementInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicIDecrementInst(std::string val) { - return "%11 = OpAtomicIDecrement %uint %4 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpAtomicIDecrement) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicIDecrementInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicIAddInst(std::string val) { - return "%11 = OpAtomicIAdd %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicIAdd) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicIAddInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicISubInst(std::string val) { - return "%11 = OpAtomicISub %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicISub) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicISubInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicSMinInst(std::string val) { - return "%11 = OpAtomicSMin %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicSMin) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicSMinInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicUMinInst(std::string val) { - return "%11 = OpAtomicUMin %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicUMin) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicUMinInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicSMaxInst(std::string val) { - return "%11 = OpAtomicSMax %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicSMax) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicSMaxInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicUMaxInst(std::string val) { - return "%11 = OpAtomicUMax %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicUMax) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicUMaxInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicAndInst(std::string val) { - return "%11 = OpAtomicAnd %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicAnd) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicAndInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicOrInst(std::string val) { - return "%11 = OpAtomicOr %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicOr) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicOrInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicXorInst(std::string val) { - return "%11 = OpAtomicXor %uint %4 %uint_1 %uint_" + val + " %uint_1"; -} - -TEST_P(MemorySemanticsModified, OpAtomicXor) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicXorInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicFlagTestAndSetInst(std::string val) { - return "%11 = OpAtomicFlagTestAndSet %uint %4 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpAtomicFlagTestAndSet) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicFlagTestAndSetInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpAtomicFlagClearInst(std::string val) { - return "OpAtomicFlagClear %4 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpAtomicFlagClear) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpAtomicFlagClearInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetOpMemoryNamedBarrierInst(std::string val) { - return "OpMemoryNamedBarrier %4 %uint_1 %uint_" + val; -} - -TEST_P(MemorySemanticsModified, OpMemoryNamedBarrier) { - std::string input, expected; - std::tie(input, expected) = - GetInputAndExpected(GetOpMemoryNamedBarrierInst, GetParam()); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -// clang-format off -INSTANTIATE_TEST_SUITE_P( - StripAtomicCounterMemoryTest, MemorySemanticsModified, - ::testing::ValuesIn(std::vector({ - std::make_tuple("1024", "0"), - std::make_tuple("5", "5"), - std::make_tuple("1288", "264"), - std::make_tuple("264", "264") - }))); -// clang-format on - -std::string GetNoMemorySemanticsPresentInst(std::string val) { - return "%11 = OpVariable %_ptr_Workgroup_uint Workgroup %uint_" + val; -} - -TEST_F(NonMemorySemanticsUnmodifiedTest, NoMemorySemanticsPresent) { - std::string input, expected; - StripAtomicCounterMemoryParam param = std::make_tuple("1288", "1288"); - std::tie(input, expected) = - GetInputAndExpected(GetNoMemorySemanticsPresentInst, param); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -std::string GetMemorySemanticsPresentInst(std::string val) { - return "%11 = OpAtomicIAdd %uint %4 %uint_1 %uint_" + val + " %uint_1288"; -} - -TEST_F(NonMemorySemanticsUnmodifiedTest, MemorySemanticsPresent) { - std::string input, expected; - StripAtomicCounterMemoryParam param = std::make_tuple("1288", "264"); - std::tie(input, expected) = - GetInputAndExpected(GetMemorySemanticsPresentInst, param); - SinglePassRunAndCheck(input, expected, - /* skip_nop = */ false); -} - -} // namespace -} // namespace opt -} // namespace spvtools diff --git a/third_party/spirv-tools/test/reduce/CMakeLists.txt b/third_party/spirv-tools/test/reduce/CMakeLists.txt index 652f0ab5b9..121cd4f08a 100644 --- a/third_party/spirv-tools/test/reduce/CMakeLists.txt +++ b/third_party/spirv-tools/test/reduce/CMakeLists.txt @@ -14,6 +14,7 @@ add_spvtools_unittest(TARGET reduce SRCS + conditional_branch_to_simple_conditional_branch_test.cpp merge_blocks_test.cpp operand_to_constant_test.cpp operand_to_undef_test.cpp @@ -26,10 +27,10 @@ add_spvtools_unittest(TARGET reduce remove_selection_test.cpp remove_unused_instruction_test.cpp remove_unused_struct_member_test.cpp + simple_conditional_branch_to_branch_test.cpp + structured_construct_to_block_test.cpp structured_loop_to_selection_test.cpp validation_during_reduction_test.cpp - conditional_branch_to_simple_conditional_branch_test.cpp - simple_conditional_branch_to_branch_test.cpp LIBS SPIRV-Tools-reduce ) diff --git a/third_party/spirv-tools/test/reduce/merge_blocks_test.cpp b/third_party/spirv-tools/test/reduce/merge_blocks_test.cpp index 8506ee08a1..c472301f0a 100644 --- a/third_party/spirv-tools/test/reduce/merge_blocks_test.cpp +++ b/third_party/spirv-tools/test/reduce/merge_blocks_test.cpp @@ -647,6 +647,64 @@ TEST(MergeBlocksReductionPassTest, LoopReturnReverse) { MergeBlocksReductionPassTest_LoopReturn_Helper(true); } +TEST(MergeBlocksReductionPassTest, MergeUnreachable) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %4 "main" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %11 = OpTypeBool + %12 = OpConstantFalse %11 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpReturn + %9 = OpLabel + OpBranch %100 + %100 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto consumer = nullptr; + const auto context = + BuildModule(env, consumer, shader, kReduceAssembleOption); + const auto ops = + MergeBlocksReductionOpportunityFinder().GetAvailableOpportunities( + context.get(), 0); + ASSERT_EQ(1, ops.size()); + + ASSERT_TRUE(ops[0]->PreconditionHolds()); + ops[0]->TryToApply(); + + std::string after = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %4 "main" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %11 = OpTypeBool + %12 = OpConstantFalse %11 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpReturn + %9 = OpLabel + OpReturn + OpFunctionEnd + )"; + + CheckEqual(env, after, context.get()); +} + } // namespace } // namespace reduce } // namespace spvtools diff --git a/third_party/spirv-tools/test/reduce/reduce_test_util.cpp b/third_party/spirv-tools/test/reduce/reduce_test_util.cpp index 0c2341112c..4271660074 100644 --- a/third_party/spirv-tools/test/reduce/reduce_test_util.cpp +++ b/third_party/spirv-tools/test/reduce/reduce_test_util.cpp @@ -21,6 +21,29 @@ namespace spvtools { namespace reduce { +const spvtools::MessageConsumer kConsoleMessageConsumer = + [](spv_message_level_t level, const char*, const spv_position_t& position, + const char* message) -> void { + switch (level) { + case SPV_MSG_FATAL: + case SPV_MSG_INTERNAL_ERROR: + case SPV_MSG_ERROR: + std::cerr << "error: line " << position.index << ": " << message + << std::endl; + break; + case SPV_MSG_WARNING: + std::cout << "warning: line " << position.index << ": " << message + << std::endl; + break; + case SPV_MSG_INFO: + std::cout << "info: line " << position.index << ": " << message + << std::endl; + break; + default: + break; + } +}; + void CheckEqual(const spv_target_env env, const std::vector& expected_binary, const std::vector& actual_binary) { @@ -55,8 +78,9 @@ void CheckEqual(const spv_target_env env, const std::string& expected_text, void CheckValid(spv_target_env env, const opt::IRContext* ir) { std::vector binary; ir->module()->ToBinary(&binary, false); - SpirvTools t(env); - ASSERT_TRUE(t.Validate(binary)); + SpirvTools tools(env); + tools.SetMessageConsumer(kConsoleMessageConsumer); + ASSERT_TRUE(tools.Validate(binary)); } std::string ToString(spv_target_env env, const opt::IRContext* ir) { diff --git a/third_party/spirv-tools/test/reduce/structured_construct_to_block_test.cpp b/third_party/spirv-tools/test/reduce/structured_construct_to_block_test.cpp new file mode 100644 index 0000000000..95009660d4 --- /dev/null +++ b/third_party/spirv-tools/test/reduce/structured_construct_to_block_test.cpp @@ -0,0 +1,245 @@ +// Copyright (c) 2021 Alastair F. Donaldson +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "source/reduce/structured_construct_to_block_reduction_opportunity_finder.h" + +#include "source/opt/build_module.h" +#include "source/reduce/reduction_opportunity.h" +#include "test/reduce/reduce_test_util.h" + +namespace spvtools { +namespace reduce { +namespace { + +TEST(StructuredConstructToBlockReductionPassTest, SimpleTest) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpConstant %6 0 + %10 = OpTypeBool + %11 = OpConstantTrue %10 + %19 = OpConstant %6 3 + %29 = OpConstant %6 1 + %31 = OpConstant %6 2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + OpStore %8 %9 + OpSelectionMerge %13 None + OpBranchConditional %11 %12 %13 + %12 = OpLabel + OpBranch %13 + %13 = OpLabel + OpBranch %14 + %14 = OpLabel + OpLoopMerge %16 %17 None + OpBranch %15 + %15 = OpLabel + %18 = OpLoad %6 %8 + %20 = OpSGreaterThan %10 %18 %19 + OpSelectionMerge %22 None + OpBranchConditional %20 %21 %22 + %21 = OpLabel + OpBranch %16 + %22 = OpLabel + OpBranch %17 + %17 = OpLabel + OpBranch %14 + %16 = OpLabel + %24 = OpLoad %6 %8 + OpSelectionMerge %28 None + OpSwitch %24 %27 1 %25 2 %26 + %27 = OpLabel + OpStore %8 %19 + OpBranch %28 + %25 = OpLabel + OpStore %8 %29 + OpBranch %28 + %26 = OpLabel + OpStore %8 %31 + OpBranch %28 + %28 = OpLabel + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto context = BuildModule(env, nullptr, shader, kReduceAssembleOption); + const auto ops = StructuredConstructToBlockReductionOpportunityFinder() + .GetAvailableOpportunities(context.get(), 0); + ASSERT_EQ(3, ops.size()); + + ASSERT_TRUE(ops[0]->PreconditionHolds()); + ops[0]->TryToApply(); + CheckValid(env, context.get()); + + ASSERT_TRUE(ops[1]->PreconditionHolds()); + ops[1]->TryToApply(); + CheckValid(env, context.get()); + + ASSERT_TRUE(ops[2]->PreconditionHolds()); + ops[2]->TryToApply(); + CheckValid(env, context.get()); + + std::string expected = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpConstant %6 0 + %10 = OpTypeBool + %11 = OpConstantTrue %10 + %19 = OpConstant %6 3 + %29 = OpConstant %6 1 + %31 = OpConstant %6 2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + OpStore %8 %9 + OpBranch %13 + %13 = OpLabel + OpBranch %14 + %14 = OpLabel + OpBranch %16 + %16 = OpLabel + %24 = OpLoad %6 %8 + OpBranch %28 + %28 = OpLabel + OpReturn + OpFunctionEnd + )"; + CheckEqual(env, expected, context.get()); +} + +TEST(StructuredConstructToBlockReductionPassTest, CannotBeRemovedDueToUses) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %100 "temp" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %6 = OpTypeInt 32 1 + %7 = OpTypePointer Function %6 + %9 = OpConstant %6 0 + %10 = OpTypeBool + %11 = OpConstantTrue %10 + %19 = OpConstant %6 3 + %29 = OpConstant %6 1 + %31 = OpConstant %6 2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpVariable %7 Function + OpStore %8 %9 + OpSelectionMerge %13 None + OpBranchConditional %11 %12 %13 + %12 = OpLabel + %100 = OpCopyObject %10 %11 + OpBranch %13 + %13 = OpLabel + OpBranch %14 + %14 = OpLabel + OpLoopMerge %16 %17 None + OpBranch %15 + %15 = OpLabel + %18 = OpLoad %6 %8 + %20 = OpSGreaterThan %10 %18 %19 + OpSelectionMerge %22 None + OpBranchConditional %20 %21 %22 + %21 = OpLabel + OpBranch %16 + %22 = OpLabel + OpBranch %17 + %17 = OpLabel + OpBranch %14 + %16 = OpLabel + %101 = OpCopyObject %6 %18 + %24 = OpLoad %6 %8 + OpSelectionMerge %28 None + OpSwitch %24 %27 1 %25 2 %26 + %27 = OpLabel + OpStore %8 %19 + %102 = OpCopyObject %10 %11 + OpBranch %28 + %25 = OpLabel + OpStore %8 %29 + OpBranch %28 + %26 = OpLabel + OpStore %8 %31 + OpBranch %28 + %28 = OpLabel + %103 = OpPhi %10 %102 %27 %11 %25 %11 %26 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto context = BuildModule(env, nullptr, shader, kReduceAssembleOption); + const auto ops = StructuredConstructToBlockReductionOpportunityFinder() + .GetAvailableOpportunities(context.get(), 0); + ASSERT_TRUE(ops.empty()); +} + +TEST(StructuredConstructToBlockReductionPassTest, + CannotBeRemovedDueToOpPhiAtMerge) { + std::string shader = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %10 = OpTypeBool + %11 = OpConstantTrue %10 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpSelectionMerge %13 None + OpBranchConditional %11 %12 %13 + %12 = OpLabel + OpBranch %13 + %13 = OpLabel + %101 = OpPhi %10 %11 %5 %11 %12 + OpReturn + OpFunctionEnd + )"; + + const auto env = SPV_ENV_UNIVERSAL_1_3; + const auto context = BuildModule(env, nullptr, shader, kReduceAssembleOption); + const auto ops = StructuredConstructToBlockReductionOpportunityFinder() + .GetAvailableOpportunities(context.get(), 0); + ASSERT_TRUE(ops.empty()); +} + +} // namespace +} // namespace reduce +} // namespace spvtools diff --git a/third_party/spirv-tools/test/target_env_test.cpp b/third_party/spirv-tools/test/target_env_test.cpp index 9c86e2da6c..4acb8ff295 100644 --- a/third_party/spirv-tools/test/target_env_test.cpp +++ b/third_party/spirv-tools/test/target_env_test.cpp @@ -95,7 +95,6 @@ INSTANTIATE_TEST_SUITE_P( {"opencl2.0embedded", true, SPV_ENV_OPENCL_EMBEDDED_2_0}, {"opencl2.1embedded", true, SPV_ENV_OPENCL_EMBEDDED_2_1}, {"opencl2.2embedded", true, SPV_ENV_OPENCL_EMBEDDED_2_2}, - {"webgpu0", true, SPV_ENV_WEBGPU_0}, {"opencl2.3", false, SPV_ENV_UNIVERSAL_1_0}, {"opencl3.0", false, SPV_ENV_UNIVERSAL_1_0}, {"vulkan1.9", false, SPV_ENV_UNIVERSAL_1_0}, diff --git a/third_party/spirv-tools/test/test_fixture.h b/third_party/spirv-tools/test/test_fixture.h index 436993e213..0c5bfc9c3b 100644 --- a/third_party/spirv-tools/test/test_fixture.h +++ b/third_party/spirv-tools/test/test_fixture.h @@ -46,7 +46,7 @@ class TextToBinaryTestBase : public T { text = {textStr, strlen(textStr)}; } - virtual ~TextToBinaryTestBase() { + ~TextToBinaryTestBase() override { DestroyBinary(); if (diagnostic) spvDiagnosticDestroy(diagnostic); } diff --git a/third_party/spirv-tools/test/text_to_binary.extension_test.cpp b/third_party/spirv-tools/test/text_to_binary.extension_test.cpp index 023763b769..1324206c79 100644 --- a/third_party/spirv-tools/test/text_to_binary.extension_test.cpp +++ b/third_party/spirv-tools/test/text_to_binary.extension_test.cpp @@ -905,5 +905,133 @@ INSTANTIATE_TEST_SUITE_P( MakeInstruction(SpvOpDecorate, {1, 5300})}, }))); +// SPV_KHR_linkonce_odr + +INSTANTIATE_TEST_SUITE_P( + SPV_KHR_linkonce_odr, ExtensionRoundTripTest, + Combine( + Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_3, SPV_ENV_VULKAN_1_0, + SPV_ENV_VULKAN_1_1, SPV_ENV_VULKAN_1_2), + ValuesIn(std::vector{ + {"OpExtension \"SPV_KHR_linkonce_odr\"\n", + MakeInstruction(SpvOpExtension, + MakeVector("SPV_KHR_linkonce_odr"))}, + {"OpDecorate %1 LinkageAttributes \"foobar\" LinkOnceODR\n", + MakeInstruction(SpvOpDecorate, + Concatenate({{1, SpvDecorationLinkageAttributes}, + MakeVector("foobar"), + {SpvLinkageTypeLinkOnceODR}}))}, + }))); + +// SPV_KHR_expect_assume + +INSTANTIATE_TEST_SUITE_P( + SPV_KHR_expect_assume, ExtensionRoundTripTest, + Combine(Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_3, + SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1, SPV_ENV_VULKAN_1_2), + ValuesIn(std::vector{ + {"OpExtension \"SPV_KHR_expect_assume\"\n", + MakeInstruction(SpvOpExtension, + MakeVector("SPV_KHR_expect_assume"))}, + {"OpAssumeTrueKHR %1\n", + MakeInstruction(SpvOpAssumeTrueKHR, {1})}}))); +// SPV_KHR_subgroup_uniform_control_flow + +INSTANTIATE_TEST_SUITE_P( + SPV_KHR_subgroup_uniform_control_flow, ExtensionRoundTripTest, + Combine(Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_3, + SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1, SPV_ENV_VULKAN_1_2), + ValuesIn(std::vector{ + {"OpExtension \"SPV_KHR_subgroup_uniform_control_flow\"\n", + MakeInstruction( + SpvOpExtension, + MakeVector("SPV_KHR_subgroup_uniform_control_flow"))}, + {"OpExecutionMode %1 SubgroupUniformControlFlowKHR\n", + MakeInstruction( + SpvOpExecutionMode, + {1, SpvExecutionModeSubgroupUniformControlFlowKHR})}, + }))); + +// SPV_KHR_integer_dot_product + +INSTANTIATE_TEST_SUITE_P( + SPV_KHR_integer_dot_product, ExtensionRoundTripTest, + Combine( + Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_5, SPV_ENV_VULKAN_1_0, + SPV_ENV_VULKAN_1_1, SPV_ENV_VULKAN_1_2), + ValuesIn(std::vector{ + {"OpExtension \"SPV_KHR_integer_dot_product\"\n", + MakeInstruction(SpvOpExtension, + MakeVector("SPV_KHR_integer_dot_product"))}, + {"OpCapability DotProductInputAllKHR\n", + MakeInstruction(SpvOpCapability, + {SpvCapabilityDotProductInputAllKHR})}, + {"OpCapability DotProductInput4x8BitKHR\n", + MakeInstruction(SpvOpCapability, + {SpvCapabilityDotProductInput4x8BitKHR})}, + {"OpCapability DotProductInput4x8BitPackedKHR\n", + MakeInstruction(SpvOpCapability, + {SpvCapabilityDotProductInput4x8BitPackedKHR})}, + {"OpCapability DotProductKHR\n", + MakeInstruction(SpvOpCapability, {SpvCapabilityDotProductKHR})}, + {"%2 = OpSDotKHR %1 %3 %4\n", + MakeInstruction(SpvOpSDotKHR, {1, 2, 3, 4})}, + {"%2 = OpSDotKHR %1 %3 %4 PackedVectorFormat4x8BitKHR\n", + MakeInstruction( + SpvOpSDotKHR, + {1, 2, 3, 4, + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR})}, + {"%2 = OpUDotKHR %1 %3 %4\n", + MakeInstruction(SpvOpUDotKHR, {1, 2, 3, 4})}, + {"%2 = OpUDotKHR %1 %3 %4 PackedVectorFormat4x8BitKHR\n", + MakeInstruction( + SpvOpUDotKHR, + {1, 2, 3, 4, + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR})}, + {"%2 = OpSUDotKHR %1 %3 %4\n", + MakeInstruction(SpvOpSUDotKHR, {1, 2, 3, 4})}, + {"%2 = OpSUDotKHR %1 %3 %4 PackedVectorFormat4x8BitKHR\n", + MakeInstruction( + SpvOpSUDotKHR, + {1, 2, 3, 4, + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR})}, + {"%2 = OpSDotAccSatKHR %1 %3 %4 %5\n", + MakeInstruction(SpvOpSDotAccSatKHR, {1, 2, 3, 4, 5})}, + {"%2 = OpSDotAccSatKHR %1 %3 %4 %5 PackedVectorFormat4x8BitKHR\n", + MakeInstruction( + SpvOpSDotAccSatKHR, + {1, 2, 3, 4, 5, + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR})}, + {"%2 = OpUDotAccSatKHR %1 %3 %4 %5\n", + MakeInstruction(SpvOpUDotAccSatKHR, {1, 2, 3, 4, 5})}, + {"%2 = OpUDotAccSatKHR %1 %3 %4 %5 PackedVectorFormat4x8BitKHR\n", + MakeInstruction( + SpvOpUDotAccSatKHR, + {1, 2, 3, 4, 5, + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR})}, + {"%2 = OpSUDotAccSatKHR %1 %3 %4 %5\n", + MakeInstruction(SpvOpSUDotAccSatKHR, {1, 2, 3, 4, 5})}, + {"%2 = OpSUDotAccSatKHR %1 %3 %4 %5 PackedVectorFormat4x8BitKHR\n", + MakeInstruction( + SpvOpSUDotAccSatKHR, + {1, 2, 3, 4, 5, + SpvPackedVectorFormatPackedVectorFormat4x8BitKHR})}, + }))); + +// SPV_KHR_bit_instructions + +INSTANTIATE_TEST_SUITE_P( + SPV_KHR_bit_instructions, ExtensionRoundTripTest, + Combine(Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_5, + SPV_ENV_VULKAN_1_0, SPV_ENV_VULKAN_1_1, SPV_ENV_VULKAN_1_2), + ValuesIn(std::vector{ + {"OpExtension \"SPV_KHR_bit_instructions\"\n", + MakeInstruction(SpvOpExtension, + MakeVector("SPV_KHR_bit_instructions"))}, + {"OpCapability BitInstructions\n", + MakeInstruction(SpvOpCapability, + {SpvCapabilityBitInstructions})}, + }))); + } // namespace } // namespace spvtools diff --git a/third_party/spirv-tools/test/text_to_binary.mode_setting_test.cpp b/third_party/spirv-tools/test/text_to_binary.mode_setting_test.cpp index 8ddf42196b..647bb3d933 100644 --- a/third_party/spirv-tools/test/text_to_binary.mode_setting_test.cpp +++ b/third_party/spirv-tools/test/text_to_binary.mode_setting_test.cpp @@ -189,6 +189,7 @@ INSTANTIATE_TEST_SUITE_P( {CASE(OutputTriangleStrip), {}}, {CASE(VecTypeHint), {96}}, {CASE(ContractionOff), {}}, + {CASE(SubgroupUniformControlFlowKHR), {}}, }))); INSTANTIATE_TEST_SUITE_P( diff --git a/third_party/spirv-tools/test/tools/opt/flags.py b/third_party/spirv-tools/test/tools/opt/flags.py index f8117d9dcc..c79f68073f 100644 --- a/third_party/spirv-tools/test/tools/opt/flags.py +++ b/third_party/spirv-tools/test/tools/opt/flags.py @@ -73,10 +73,7 @@ class TestValidPassFlags(expect.ValidObjectFile1_5, '--remove-duplicates', '--replace-invalid-opcode', '--ssa-rewrite', '--scalar-replacement', '--scalar-replacement=42', '--strength-reduction', '--strip-debug', '--strip-reflect', '--vector-dce', '--workaround-1209', - '--unify-const', '--legalize-vector-shuffle', - '--split-invalid-unreachable', '--generate-webgpu-initializers', - '--decompose-initialized-variables', '--graphics-robust-access', - '--wrap-opkill', '--amd-ext-to-khr' + '--unify-const', '--graphics-robust-access', '--wrap-opkill', '--amd-ext-to-khr' ] expected_passes = [ 'wrap-opkill', @@ -124,10 +121,6 @@ class TestValidPassFlags(expect.ValidObjectFile1_5, 'vector-dce', 'workaround-1209', 'unify-const', - 'legalize-vector-shuffle', - 'split-invalid-unreachable', - 'generate-webgpu-initializers', - 'decompose-initialized-variables', 'graphics-robust-access', 'wrap-opkill', 'amd-ext-to-khr' @@ -362,45 +355,3 @@ class TestLoopPeelingThresholdArgsInvalidNumber(expect.ErrorMessageSubstr): spirv_args = ['--loop-peeling-threshold=a10f'] expected_error_substr = 'must have a positive integer argument' - -@inside_spirv_testsuite('SpirvOptFlags') -class TestWebGPUToVulkanThenVulkanToWebGPUIsInvalid(expect.ReturnCodeIsNonZero, expect.ErrorMessageSubstr): - """Tests Vulkan->WebGPU flag cannot be used after WebGPU->Vulkan flag.""" - - spirv_args = ['--webgpu-to-vulkan', '--vulkan-to-webgpu'] - expected_error_substr = 'Cannot use both' - -@inside_spirv_testsuite('SpirvOptFlags') -class TestVulkanToWebGPUThenWebGPUToVulkanIsInvalid(expect.ReturnCodeIsNonZero, expect.ErrorMessageSubstr): - """Tests WebGPU->Vulkan flag cannot be used after Vulkan->WebGPU flag.""" - - spirv_args = ['--vulkan-to-webgpu', '--webgpu-to-vulkan'] - expected_error_substr = 'Cannot use both' - -@inside_spirv_testsuite('SpirvOptFlags') -class TestTargetEnvThenVulkanToWebGPUIsInvalid(expect.ReturnCodeIsNonZero, expect.ErrorMessageSubstr): - """Tests Vulkan->WebGPU flag cannot be used after target env flag.""" - - spirv_args = ['--target-env=opengl4.0', '--vulkan-to-webgpu'] - expected_error_substr = 'defines the target environment' - -@inside_spirv_testsuite('SpirvOptFlags') -class TestVulkanToWebGPUThenTargetEnvIsInvalid(expect.ReturnCodeIsNonZero, expect.ErrorMessageSubstr): - """Tests target env flag cannot be used after Vulkan->WebGPU flag.""" - - spirv_args = ['--vulkan-to-webgpu', '--target-env=opengl4.0'] - expected_error_substr = 'defines the target environment' - -@inside_spirv_testsuite('SpirvOptFlags') -class TestTargetEnvThenWebGPUToVulkanIsInvalid(expect.ReturnCodeIsNonZero, expect.ErrorMessageSubstr): - """Tests WebGPU->Vulkan flag cannot be used after target env flag.""" - - spirv_args = ['--target-env=opengl4.0', '--webgpu-to-vulkan'] - expected_error_substr = 'defines the target environment' - -@inside_spirv_testsuite('SpirvOptFlags') -class TestWebGPUToVulkanThenTargetEnvIsInvalid(expect.ReturnCodeIsNonZero, expect.ErrorMessageSubstr): - """Tests target env flag cannot be used after WebGPU->Vulkan flag.""" - - spirv_args = ['--webgpu-to-vulkan', '--target-env=opengl4.0'] - expected_error_substr = 'defines the target environment' diff --git a/third_party/spirv-tools/test/unit_spirv.h b/third_party/spirv-tools/test/unit_spirv.h index 32646620de..f0a2958db6 100644 --- a/third_party/spirv-tools/test/unit_spirv.h +++ b/third_party/spirv-tools/test/unit_spirv.h @@ -195,7 +195,7 @@ inline std::vector AllTargetEnvironments() { SPV_ENV_OPENGL_4_1, SPV_ENV_OPENGL_4_2, SPV_ENV_OPENGL_4_3, SPV_ENV_OPENGL_4_5, SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_3, - SPV_ENV_VULKAN_1_1, SPV_ENV_WEBGPU_0, + SPV_ENV_VULKAN_1_1, }; } diff --git a/third_party/spirv-tools/test/val/CMakeLists.txt b/third_party/spirv-tools/test/val/CMakeLists.txt index 153a91670c..b1e12ac03c 100644 --- a/third_party/spirv-tools/test/val/CMakeLists.txt +++ b/third_party/spirv-tools/test/val/CMakeLists.txt @@ -38,6 +38,11 @@ add_spvtools_unittest(TARGET val_abcde val_entry_point.cpp val_explicit_reserved_test.cpp val_extensions_test.cpp + val_extension_spv_khr_expect_assume.cpp + val_extension_spv_khr_linkonce_odr.cpp + val_extension_spv_khr_subgroup_uniform_control_flow.cpp + val_extension_spv_khr_integer_dot_product.cpp + val_extension_spv_khr_bit_instructions.cpp val_extension_spv_khr_terminate_invocation.cpp val_ext_inst_test.cpp ${VAL_TEST_COMMON_SRCS} @@ -89,7 +94,6 @@ add_spvtools_unittest(TARGET val_stuvw val_type_unique_test.cpp val_validation_state_test.cpp val_version_test.cpp - val_webgpu_test.cpp ${VAL_TEST_COMMON_SRCS} LIBS ${SPIRV_TOOLS_FULL_VISIBILITY} PCH_FILE pch_test_val diff --git a/third_party/spirv-tools/test/val/val_atomics_test.cpp b/third_party/spirv-tools/test/val/val_atomics_test.cpp index aca0f3c90c..b7f6948efb 100644 --- a/third_party/spirv-tools/test/val/val_atomics_test.cpp +++ b/third_party/spirv-tools/test/val/val_atomics_test.cpp @@ -30,16 +30,16 @@ using ValidateAtomics = spvtest::ValidateBase; std::string GenerateShaderCodeImpl( const std::string& body, const std::string& capabilities_and_extensions, - const std::string& definitions, const std::string& memory_model) { + const std::string& definitions, const std::string& memory_model, + const std::string& execution) { std::ostringstream ss; ss << R"( OpCapability Shader )"; ss << capabilities_and_extensions; ss << "OpMemoryModel Logical " << memory_model << "\n"; + ss << execution; ss << R"( -OpEntryPoint Fragment %main "main" -OpExecutionMode %main OriginUpperLeft %void = OpTypeVoid %func = OpTypeFunction %void %bool = OpTypeBool @@ -95,8 +95,13 @@ OpFunctionEnd)"; std::string GenerateShaderCode( const std::string& body, const std::string& capabilities_and_extensions = "", + const std::string& extra_defs = "", const std::string& memory_model = "GLSL450") { - const std::string defintions = R"( + const std::string execution = R"( +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +)"; + const std::string definitions = R"( %u64 = OpTypeInt 64 0 %s64 = OpTypeInt 64 1 @@ -109,25 +114,34 @@ std::string GenerateShaderCode( %s64_var = OpVariable %s64_ptr Workgroup )"; return GenerateShaderCodeImpl( - body, "OpCapability Int64\n" + capabilities_and_extensions, defintions, - memory_model); + body, "OpCapability Int64\n" + capabilities_and_extensions, + definitions + extra_defs, memory_model, execution); } -std::string GenerateWebGPUShaderCode( +std::string GenerateShaderComputeCode( const std::string& body, - const std::string& capabilities_and_extensions = "") { - const std::string vulkan_memory_capability = R"( -OpCapability VulkanMemoryModelDeviceScopeKHR -OpCapability VulkanMemoryModelKHR + const std::string& capabilities_and_extensions = "", + const std::string& extra_defs = "", + const std::string& memory_model = "GLSL450") { + const std::string execution = R"( +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 32 1 1 )"; - const std::string vulkan_memory_extension = R"( -OpExtension "SPV_KHR_vulkan_memory_model" + const std::string definitions = R"( +%u64 = OpTypeInt 64 0 +%s64 = OpTypeInt 64 1 + +%u64_1 = OpConstant %u64 1 +%s64_1 = OpConstant %s64 1 + +%u64_ptr = OpTypePointer Workgroup %u64 +%s64_ptr = OpTypePointer Workgroup %s64 +%u64_var = OpVariable %u64_ptr Workgroup +%s64_var = OpVariable %s64_ptr Workgroup )"; - return GenerateShaderCodeImpl(body, - vulkan_memory_capability + - capabilities_and_extensions + - vulkan_memory_extension, - "", "VulkanKHR"); + return GenerateShaderCodeImpl( + body, "OpCapability Int64\n" + capabilities_and_extensions, + definitions + extra_defs, memory_model, execution); } std::string GenerateKernelCode( @@ -210,7 +224,6 @@ TEST_F(ValidateAtomics, AtomicLoadShaderSuccess) { const std::string body = R"( %val1 = OpAtomicLoad %u32 %u32_var %device %relaxed %val2 = OpAtomicLoad %u32 %u32_var %workgroup %acquire -%val3 = OpAtomicLoad %u64 %u64_var %subgroup %sequentially_consistent )"; CompileSuccessfully(GenerateShaderCode(body)); @@ -221,21 +234,54 @@ TEST_F(ValidateAtomics, AtomicLoadKernelSuccess) { const std::string body = R"( %val1 = OpAtomicLoad %f32 %f32_var %device %relaxed %val2 = OpAtomicLoad %u32 %u32_var %workgroup %sequentially_consistent -%val3 = OpAtomicLoad %u64 %u64_var %subgroup %acquire )"; CompileSuccessfully(GenerateKernelCode(body)); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } +TEST_F(ValidateAtomics, AtomicLoadInt64ShaderSuccess) { + const std::string body = R"( +%val1 = OpAtomicLoad %u64 %u64_var %subgroup %sequentially_consistent +)"; + + CompileSuccessfully(GenerateShaderCode(body, "OpCapability Int64Atomics\n")); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateAtomics, AtomicLoadInt64KernelSuccess) { + const std::string body = R"( +%val1 = OpAtomicLoad %u64 %u64_var %subgroup %acquire +)"; + + CompileSuccessfully(GenerateKernelCode(body, "OpCapability Int64Atomics\n")); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + TEST_F(ValidateAtomics, AtomicLoadInt32VulkanSuccess) { const std::string body = R"( %val1 = OpAtomicLoad %u32 %u32_var %device %relaxed %val2 = OpAtomicLoad %u32 %u32_var %workgroup %acquire +%val3 = OpAtomicLoad %u32 %u32_var %invocation %relaxed +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicLoadVulkanWrongStorageClass) { + const std::string body = R"( +%val1 = OpAtomicLoad %u32 %u32_var %device %relaxed )"; CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04645")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("in Vulkan evironment, Workgroup Storage Class is limited to " + "MeshNV, TaskNV, and GLCompute execution model")); } TEST_F(ValidateAtomics, AtomicAddIntVulkanWrongType1) { @@ -247,7 +293,7 @@ TEST_F(ValidateAtomics, AtomicAddIntVulkanWrongType1) { ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("AtomicIAdd: " - "expected Result Type to be int scalar type")); + "expected Result Type to be integer scalar type")); } TEST_F(ValidateAtomics, AtomicAddIntVulkanWrongType2) { @@ -272,7 +318,33 @@ TEST_F(ValidateAtomics, AtomicAddFloatVulkan) { EXPECT_THAT( getDiagnosticString(), HasSubstr("Opcode AtomicFAddEXT requires one of these capabilities: " - "AtomicFloat32AddEXT AtomicFloat64AddEXT")); + "AtomicFloat32AddEXT AtomicFloat64AddEXT AtomicFloat16AddEXT")); +} + +TEST_F(ValidateAtomics, AtomicMinFloatVulkan) { + const std::string body = R"( +%val1 = OpAtomicFMinEXT %f32 %f32_var %device %relaxed %f32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body)); + ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Opcode AtomicFMinEXT requires one of these capabilities: " + "AtomicFloat32MinMaxEXT AtomicFloat64MinMaxEXT AtomicFloat16MinMaxEXT")); +} + +TEST_F(ValidateAtomics, AtomicMaxFloatVulkan) { + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %f32 %f32_var %device %relaxed %f32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body)); + ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Opcode AtomicFMaxEXT requires one of these capabilities: " + "AtomicFloat32MinMaxEXT AtomicFloat64MinMaxEXT AtomicFloat16MinMaxEXT")); } TEST_F(ValidateAtomics, AtomicAddFloatVulkanWrongType1) { @@ -291,6 +363,38 @@ OpExtension "SPV_EXT_shader_atomic_float_add" "expected Result Type to be float scalar type")); } +TEST_F(ValidateAtomics, AtomicMinFloatVulkanWrongType1) { + const std::string body = R"( +%val1 = OpAtomicFMinEXT %f32vec4 %f32vec4_var %device %relaxed %f32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMinEXT: " + "expected Result Type to be float scalar type")); +} + +TEST_F(ValidateAtomics, AtomicMaxFloatVulkanWrongType1) { + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %f32vec4 %f32vec4_var %device %relaxed %f32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMaxEXT: " + "expected Result Type to be float scalar type")); +} + TEST_F(ValidateAtomics, AtomicAddFloatVulkanWrongType2) { const std::string body = R"( %val1 = OpAtomicFAddEXT %u32 %u32_var %device %relaxed %u32_1 @@ -307,6 +411,38 @@ OpExtension "SPV_EXT_shader_atomic_float_add" "expected Result Type to be float scalar type")); } +TEST_F(ValidateAtomics, AtomicMinFloatVulkanWrongType2) { + const std::string body = R"( +%val1 = OpAtomicFMinEXT %u32 %u32_var %device %relaxed %u32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMinEXT: " + "expected Result Type to be float scalar type")); +} + +TEST_F(ValidateAtomics, AtomicMaxFloatVulkanWrongType2) { + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %u32 %u32_var %device %relaxed %u32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMaxEXT: " + "expected Result Type to be float scalar type")); +} + TEST_F(ValidateAtomics, AtomicAddFloatVulkanWrongType3) { const std::string body = R"( %val1 = OpAtomicFAddEXT %u64 %u64_var %device %relaxed %u64_1 @@ -323,6 +459,38 @@ OpExtension "SPV_EXT_shader_atomic_float_add" "expected Result Type to be float scalar type")); } +TEST_F(ValidateAtomics, AtomicMinFloatVulkanWrongType3) { + const std::string body = R"( +%val1 = OpAtomicFMinEXT %u64 %u64_var %device %relaxed %u64_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMinEXT: " + "expected Result Type to be float scalar type")); +} + +TEST_F(ValidateAtomics, AtomicMaxFloatVulkanWrongType3) { + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %u64 %u64_var %device %relaxed %u64_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMaxEXT: " + "expected Result Type to be float scalar type")); +} + TEST_F(ValidateAtomics, AtomicAddFloatVulkanWrongCapability) { const std::string body = R"( %val1 = OpAtomicFAddEXT %f32 %f32_var %device %relaxed %f32_1 @@ -339,16 +507,183 @@ OpExtension "SPV_EXT_shader_atomic_float_add" "require the AtomicFloat32AddEXT capability")); } +TEST_F(ValidateAtomics, AtomicMinFloatVulkanWrongCapability) { + const std::string body = R"( +%val1 = OpAtomicFMinEXT %f32 %f32_var %device %relaxed %f32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat64MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMinEXT: float min/max atomics " + "require the AtomicFloat32MinMaxEXT capability")); +} + +TEST_F(ValidateAtomics, AtomicMaxFloatVulkanWrongCapability) { + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %f32 %f32_var %device %relaxed %f32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat64MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("AtomicFMaxEXT: float min/max atomics " + "require the AtomicFloat32MinMaxEXT capability")); +} + +TEST_F(ValidateAtomics, AtomicAddFloat16VulkanSuccess) { + const std::string defs = R"( +%f16 = OpTypeFloat 16 +%f16_1 = OpConstant %f16 1 +%f16_ptr = OpTypePointer Workgroup %f16 +%f16_var = OpVariable %f16_ptr Workgroup +)"; + const std::string body = R"( +%val1 = OpAtomicFAddEXT %f16 %f16_var %device %relaxed %f16_1 +)"; + const std::string extra = R"( +OpCapability Float16 +OpCapability AtomicFloat16AddEXT +OpExtension "SPV_EXT_shader_atomic_float16_add" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra, defs), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + TEST_F(ValidateAtomics, AtomicAddFloatVulkanSuccess) { const std::string body = R"( %val1 = OpAtomicFAddEXT %f32 %f32_var %device %relaxed %f32_1 +%val2 = OpAtomicFAddEXT %f32 %f32_var %invocation %relaxed %f32_1 )"; const std::string extra = R"( OpCapability AtomicFloat32AddEXT OpExtension "SPV_EXT_shader_atomic_float_add" )"; - CompileSuccessfully(GenerateShaderCode(body, extra), SPV_ENV_VULKAN_1_0); + CompileSuccessfully(GenerateShaderComputeCode(body, extra), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicMinFloat16VulkanSuccess) { + const std::string defs = R"( +%f16 = OpTypeFloat 16 +%f16_1 = OpConstant %f16 1 +%f16_ptr = OpTypePointer Workgroup %f16 +%f16_var = OpVariable %f16_ptr Workgroup +)"; + const std::string body = R"( +%val1 = OpAtomicFMinEXT %f16 %f16_var %device %relaxed %f16_1 +)"; + const std::string extra = R"( +OpCapability Float16 +OpCapability AtomicFloat16MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra, defs), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicMaxFloat16VulkanSuccess) { + const std::string defs = R"( +%f16 = OpTypeFloat 16 +%f16_1 = OpConstant %f16 1 +%f16_ptr = OpTypePointer Workgroup %f16 +%f16_var = OpVariable %f16_ptr Workgroup +)"; + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %f16 %f16_var %device %relaxed %f16_1 +)"; + const std::string extra = R"( +OpCapability Float16 +OpCapability AtomicFloat16MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra, defs), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicMinFloat32VulkanSuccess) { + const std::string body = R"( +%val1 = OpAtomicFMinEXT %f32 %f32_var %device %relaxed %f32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicMaxFloat32VulkanSuccess) { + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %f32 %f32_var %device %relaxed %f32_1 +)"; + const std::string extra = R"( +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicMinFloat64VulkanSuccess) { + const std::string defs = R"( +%f64 = OpTypeFloat 64 +%f64_1 = OpConstant %f64 1 +%f64_ptr = OpTypePointer Workgroup %f64 +%f64_var = OpVariable %f64_ptr Workgroup +)"; + const std::string body = R"( +%val1 = OpAtomicFMinEXT %f64 %f64_var %device %relaxed %f64_1 +)"; + const std::string extra = R"( +OpCapability Float64 +OpCapability AtomicFloat64MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra, defs), + SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateAtomics, AtomicMaxFloat64VulkanSuccess) { + const std::string defs = R"( +%f64 = OpTypeFloat 64 +%f64_1 = OpConstant %f64 1 +%f64_ptr = OpTypePointer Workgroup %f64 +%f64_var = OpVariable %f64_ptr Workgroup +)"; + const std::string body = R"( +%val1 = OpAtomicFMaxEXT %f64 %f64_var %device %relaxed %f64_1 +)"; + const std::string extra = R"( +OpCapability Float64 +OpCapability AtomicFloat64MinMaxEXT +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderComputeCode(body, extra, defs), + SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } @@ -358,16 +693,31 @@ TEST_F(ValidateAtomics, AtomicLoadFloatVulkan) { %val2 = OpAtomicLoad %f32 %f32_var %workgroup %acquire )"; - CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + CompileSuccessfully(GenerateShaderComputeCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } +TEST_F(ValidateAtomics, AtomicStoreVulkanWrongStorageClass) { + const std::string body = R"( +OpAtomicStore %f32_var %device %relaxed %f32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04645")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("in Vulkan evironment, Workgroup Storage Class is limited to " + "MeshNV, TaskNV, and GLCompute execution model")); +} + TEST_F(ValidateAtomics, AtomicStoreFloatVulkan) { const std::string body = R"( OpAtomicStore %f32_var %device %relaxed %f32_1 )"; - CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + CompileSuccessfully(GenerateShaderComputeCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } @@ -376,7 +726,7 @@ TEST_F(ValidateAtomics, AtomicExchangeFloatVulkan) { %val2 = OpAtomicExchange %f32 %f32_var %device %relaxed %f32_0 )"; - CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + CompileSuccessfully(GenerateShaderComputeCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } @@ -384,10 +734,12 @@ TEST_F(ValidateAtomics, AtomicLoadInt64WithCapabilityVulkanSuccess) { const std::string body = R"( %val1 = OpAtomicLoad %u64 %u64_var %device %relaxed %val2 = OpAtomicLoad %u64 %u64_var %workgroup %acquire + %val3 = OpAtomicLoad %u64 %u64_var %invocation %relaxed )"; - CompileSuccessfully(GenerateShaderCode(body, "OpCapability Int64Atomics\n"), - SPV_ENV_VULKAN_1_0); + CompileSuccessfully( + GenerateShaderComputeCode(body, "OpCapability Int64Atomics\n"), + SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } @@ -397,7 +749,7 @@ TEST_F(ValidateAtomics, AtomicLoadInt64WithoutCapabilityVulkan) { %val2 = OpAtomicLoad %u64 %u64_var %workgroup %acquire )"; - CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + CompileSuccessfully(GenerateShaderComputeCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); EXPECT_THAT(getDiagnosticString(), HasSubstr("64-bit atomics require the Int64Atomics capability")); @@ -421,6 +773,23 @@ OpAtomicStore %f32_var_function %device %relaxed %f32_1 CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04686")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicStore: Vulkan spec only allows storage classes for " + "atomic to be: Uniform, Workgroup, Image, StorageBuffer, or " + "PhysicalStorageBuffer.")); +} + +TEST_F(ValidateAtomics, AtomicStoreFunctionPointerStorageType) { + const std::string body = R"( +%f32_var_function = OpVariable %f32_ptr_function Function +OpAtomicStore %f32_var_function %device %relaxed %f32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body)); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("AtomicStore: Function storage class forbidden when " "the Shader capability is declared.")); @@ -447,6 +816,8 @@ TEST_F(ValidateAtomics, AtomicLoadVulkanRelease) { CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpAtomicLoad-04731")); EXPECT_THAT( getDiagnosticString(), HasSubstr("Vulkan spec disallows OpAtomicLoad with Memory Semantics " @@ -460,6 +831,8 @@ TEST_F(ValidateAtomics, AtomicLoadVulkanAcquireRelease) { CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpAtomicLoad-04731")); EXPECT_THAT( getDiagnosticString(), HasSubstr("Vulkan spec disallows OpAtomicLoad with Memory Semantics " @@ -473,12 +846,29 @@ TEST_F(ValidateAtomics, AtomicLoadVulkanSequentiallyConsistent) { CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpAtomicLoad-04731")); EXPECT_THAT( getDiagnosticString(), HasSubstr("Vulkan spec disallows OpAtomicLoad with Memory Semantics " "Release, AcquireRelease and SequentiallyConsistent")); } +TEST_F(ValidateAtomics, AtomicLoadVulkanInvocationSemantics) { + const std::string body = R"( +%val1 = OpAtomicLoad %u32 %u32_var %invocation %acquire +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04641")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicLoad: Vulkan specification requires Memory Semantics to " + "be None if used with Invocation Memory Scope")); +} + TEST_F(ValidateAtomics, AtomicLoadShaderFloat) { const std::string body = R"( %val1 = OpAtomicLoad %f32 %f32_var %device %relaxed @@ -501,37 +891,43 @@ TEST_F(ValidateAtomics, AtomicLoadVulkanInt64) { "AtomicLoad: 64-bit atomics require the Int64Atomics capability")); } -TEST_F(ValidateAtomics, AtomicLoadWebGPUSuccess) { +TEST_F(ValidateAtomics, AtomicLoadKernelInt64) { const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %queuefamily %relaxed +%val1 = OpAtomicLoad %u64 %u64_var %device %relaxed )"; - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); + CompileSuccessfully(GenerateKernelCode(body)); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "AtomicLoad: 64-bit atomics require the Int64Atomics capability")); } -TEST_F(ValidateAtomics, AtomicLoadWebGPUNonQueueFamilyFailure) { +TEST_F(ValidateAtomics, AtomicStoreVulkanInt64) { const std::string body = R"( -%val3 = OpAtomicLoad %u32 %u32_var %invocation %relaxed +OpAtomicStore %u64_var %device %relaxed %u64_1 )"; - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Memory Scope is limited to QueueFamilyKHR for " - "OpAtomic* operations")); + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "AtomicStore: 64-bit atomics require the Int64Atomics capability")); } -TEST_F(ValidateAtomics, AtomicLoadWebGPUNonRelaxedFailure) { +TEST_F(ValidateAtomics, AtomicStoreKernelInt64) { const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %queuefamily %acquire +OpAtomicStore %u64_var %device %relaxed %u64_1 )"; - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("no bits may be set for Memory Semantics of OpAtomic* " - "instructions")); + CompileSuccessfully(GenerateKernelCode(body)); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "AtomicStore: 64-bit atomics require the Int64Atomics capability")); } TEST_F(ValidateAtomics, VK_KHR_shader_atomic_int64Success) { @@ -565,8 +961,9 @@ OpAtomicStore %u64_var %device %relaxed %u64_1 OpAtomicStore %s64_var %device %relaxed %s64_1 )"; - CompileSuccessfully(GenerateShaderCode(body, "OpCapability Int64Atomics\n"), - SPV_ENV_VULKAN_1_0); + CompileSuccessfully( + GenerateShaderComputeCode(body, "OpCapability Int64Atomics\n"), + SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } @@ -590,9 +987,10 @@ TEST_F(ValidateAtomics, AtomicLoadWrongResultType) { CompileSuccessfully(GenerateKernelCode(body)); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("AtomicLoad: " - "expected Result Type to be int or float scalar type")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicLoad: " + "expected Result Type to be integer or float scalar type")); } TEST_F(ValidateAtomics, AtomicLoadWrongPointerType) { @@ -665,9 +1063,10 @@ OpAtomicStore %u32_var %subgroup %sequentially_consistent %u32_1 TEST_F(ValidateAtomics, AtomicStoreVulkanSuccess) { const std::string body = R"( OpAtomicStore %u32_var %device %release %u32_1 +OpAtomicStore %u32_var %invocation %relaxed %u32_1 )"; - CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + CompileSuccessfully(GenerateShaderComputeCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } @@ -678,6 +1077,8 @@ OpAtomicStore %u32_var %device %acquire %u32_1 CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpAtomicStore-04730")); EXPECT_THAT( getDiagnosticString(), HasSubstr("Vulkan spec disallows OpAtomicStore with Memory Semantics " @@ -691,6 +1092,8 @@ OpAtomicStore %u32_var %device %acquire_release %u32_1 CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpAtomicStore-04730")); EXPECT_THAT( getDiagnosticString(), HasSubstr("Vulkan spec disallows OpAtomicStore with Memory Semantics " @@ -704,42 +1107,27 @@ OpAtomicStore %u32_var %device %sequentially_consistent %u32_1 CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpAtomicStore-04730")); EXPECT_THAT( getDiagnosticString(), HasSubstr("Vulkan spec disallows OpAtomicStore with Memory Semantics " "Acquire, AcquireRelease and SequentiallyConsistent")); } -TEST_F(ValidateAtomics, AtomicStoreWebGPUSuccess) { +TEST_F(ValidateAtomics, AtomicStoreVulkanInvocationSemantics) { const std::string body = R"( -OpAtomicStore %u32_var %queuefamily %relaxed %u32_1 +OpAtomicStore %u32_var %invocation %acquire %u32_1 )"; - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} -TEST_F(ValidateAtomics, AtomicStoreWebGPUNonQueueFamilyFailure) { - const std::string body = R"( -OpAtomicStore %u32_var %workgroup %relaxed %u32_1 -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Memory Scope is limited to QueueFamilyKHR for " - "OpAtomic* operations")); -} - -TEST_F(ValidateAtomics, AtomicStoreWebGPUNonRelaxedFailure) { - const std::string body = R"( -OpAtomicStore %u32_var %queuefamily %release %u32_1 -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("no bits may be set for Memory Semantics of OpAtomic* " - "instructions")); + AnyVUID("VUID-StandaloneSpirv-None-04641")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicStore: Vulkan specification requires Memory Semantics " + "to be None if used with Invocation Memory Scope")); } TEST_F(ValidateAtomics, AtomicStoreWrongPointerType) { @@ -763,9 +1151,9 @@ OpAtomicStore %f32vec4_var %device %relaxed %f32_1 ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), - HasSubstr("AtomicStore: " - "expected Pointer to be a pointer to int or float scalar " - "type")); + HasSubstr( + "AtomicStore: " + "expected Pointer to be a pointer to integer or float scalar type")); } TEST_F(ValidateAtomics, AtomicStoreWrongPointerStorageTypeForOpenCL) { @@ -871,9 +1259,10 @@ OpStore %f32vec4_var %f32vec4_0000 CompileSuccessfully(GenerateKernelCode(body)); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("AtomicExchange: " - "expected Result Type to be int or float scalar type")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicExchange: " + "expected Result Type to be integer or float scalar type")); } TEST_F(ValidateAtomics, AtomicExchangeWrongPointerType) { @@ -941,6 +1330,22 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 "expected Value to be of type Result Type")); } +TEST_F(ValidateAtomics, AtomicExchangeVulkanInvocationSemantics) { + const std::string body = R"( +OpAtomicStore %u32_var %invocation %relaxed %u32_1 +%val2 = OpAtomicExchange %u32 %u32_var %invocation %acquire %u32_0 +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04641")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicExchange: Vulkan specification requires Memory " + "Semantics to be None if used with Invocation Memory Scope")); +} + TEST_F(ValidateAtomics, AtomicCompareExchangeShaderSuccess) { const std::string body = R"( OpAtomicStore %u32_var %device %relaxed %u32_1 @@ -953,10 +1358,8 @@ OpAtomicStore %u32_var %device %relaxed %u32_1 TEST_F(ValidateAtomics, AtomicCompareExchangeKernelSuccess) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %device %relaxed %relaxed %f32_0 %f32_1 OpAtomicStore %u32_var %device %relaxed %u32_1 -%val4 = OpAtomicCompareExchange %u32 %u32_var %device %relaxed %relaxed %u32_0 %u32_0 +%val2 = OpAtomicCompareExchange %u32 %u32_var %device %relaxed %relaxed %u32_0 %u32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -973,7 +1376,7 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("AtomicCompareExchange: " - "expected Result Type to be int scalar type")); + "expected Result Type to be integer scalar type")); } TEST_F(ValidateAtomics, AtomicCompareExchangeWrongResultType) { @@ -986,7 +1389,7 @@ OpStore %f32vec4_var %f32vec4_0000 ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("AtomicCompareExchange: " - "expected Result Type to be int or float scalar type")); + "expected Result Type to be integer scalar type")); } TEST_F(ValidateAtomics, AtomicCompareExchangeWrongPointerType) { @@ -1004,7 +1407,7 @@ TEST_F(ValidateAtomics, AtomicCompareExchangeWrongPointerType) { TEST_F(ValidateAtomics, AtomicCompareExchangeWrongPointerDataType) { const std::string body = R"( OpStore %f32vec4_var %f32vec4_0000 -%val2 = OpAtomicCompareExchange %f32 %f32vec4_var %device %relaxed %relaxed %f32_0 %f32_1 +%val2 = OpAtomicCompareExchange %u32 %f32vec4_var %device %relaxed %relaxed %u32_0 %u32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -1017,11 +1420,11 @@ OpStore %f32vec4_var %f32vec4_0000 TEST_F(ValidateAtomics, AtomicCompareExchangeWrongScopeType) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %f32_1 %relaxed %relaxed %f32_0 %f32_0 +OpAtomicStore %u64_var %device %relaxed %u64_1 +%val2 = OpAtomicCompareExchange %u64 %u64_var %u64_1 %relaxed %relaxed %u32_0 %u32_0 )"; - CompileSuccessfully(GenerateKernelCode(body)); + CompileSuccessfully(GenerateKernelCode(body, "OpCapability Int64Atomics\n")); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("AtomicCompareExchange: expected scope to be a 32-bit " @@ -1030,8 +1433,8 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 TEST_F(ValidateAtomics, AtomicCompareExchangeWrongMemorySemanticsType1) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %device %f32_1 %relaxed %f32_0 %f32_0 +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %device %f32_1 %relaxed %u32_0 %u32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -1043,8 +1446,8 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 TEST_F(ValidateAtomics, AtomicCompareExchangeWrongMemorySemanticsType2) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %device %relaxed %f32_1 %f32_0 %f32_0 +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %device %relaxed %f32_1 %u32_0 %u32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -1056,8 +1459,8 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 TEST_F(ValidateAtomics, AtomicCompareExchangeUnequalRelease) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %device %relaxed %release %f32_0 %f32_0 +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %device %relaxed %release %u32_0 %u32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -1069,8 +1472,8 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 TEST_F(ValidateAtomics, AtomicCompareExchangeWrongValueType) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %device %relaxed %relaxed %u32_0 %f32_1 +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %device %relaxed %relaxed %f32_1 %u32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -1082,8 +1485,8 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 TEST_F(ValidateAtomics, AtomicCompareExchangeWrongComparatorType) { const std::string body = R"( -OpAtomicStore %f32_var %device %relaxed %f32_1 -%val2 = OpAtomicCompareExchange %f32 %f32_var %device %relaxed %relaxed %f32_0 %u32_1 +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %device %relaxed %relaxed %u32_0 %f32_0 )"; CompileSuccessfully(GenerateKernelCode(body)); @@ -1113,7 +1516,39 @@ OpAtomicStore %f32_var %device %relaxed %f32_1 ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("AtomicCompareExchangeWeak: " - "expected Result Type to be int scalar type")); + "expected Result Type to be integer scalar type")); +} + +TEST_F(ValidateAtomics, AtomicCompareExchangeVulkanInvocationSemanticsEqual) { + const std::string body = R"( +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %invocation %release %relaxed %u32_0 %u32_0 +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04641")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicCompareExchange: Vulkan specification requires Memory " + "Semantics to be None if used with Invocation Memory Scope")); +} + +TEST_F(ValidateAtomics, AtomicCompareExchangeVulkanInvocationSemanticsUnequal) { + const std::string body = R"( +OpAtomicStore %u32_var %device %relaxed %u32_1 +%val2 = OpAtomicCompareExchange %u32 %u32_var %invocation %relaxed %acquire %u32_0 %u32_0 +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04641")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("AtomicCompareExchange: Vulkan specification requires Memory " + "Semantics to be None if used with Invocation Memory Scope")); } TEST_F(ValidateAtomics, AtomicArithmeticsSuccess) { @@ -1180,7 +1615,7 @@ TEST_F(ValidateAtomics, AtomicFlagTestAndSetNotIntPointer) { EXPECT_THAT( getDiagnosticString(), HasSubstr("AtomicFlagTestAndSet: " - "expected Pointer to point to a value of 32-bit int type")); + "expected Pointer to point to a value of 32-bit integer type")); } TEST_F(ValidateAtomics, AtomicFlagTestAndSetNotInt32Pointer) { @@ -1188,12 +1623,12 @@ TEST_F(ValidateAtomics, AtomicFlagTestAndSetNotInt32Pointer) { %val1 = OpAtomicFlagTestAndSet %bool %u64_var %device %relaxed )"; - CompileSuccessfully(GenerateKernelCode(body)); + CompileSuccessfully(GenerateKernelCode(body, "OpCapability Int64Atomics\n")); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("AtomicFlagTestAndSet: " - "expected Pointer to point to a value of 32-bit int type")); + "expected Pointer to point to a value of 32-bit integer type")); } TEST_F(ValidateAtomics, AtomicFlagTestAndSetWrongScopeType) { @@ -1254,7 +1689,7 @@ OpAtomicFlagClear %f32_var %device %relaxed EXPECT_THAT( getDiagnosticString(), HasSubstr("AtomicFlagClear: " - "expected Pointer to point to a value of 32-bit int type")); + "expected Pointer to point to a value of 32-bit integer type")); } TEST_F(ValidateAtomics, AtomicFlagClearNotInt32Pointer) { @@ -1262,12 +1697,12 @@ TEST_F(ValidateAtomics, AtomicFlagClearNotInt32Pointer) { OpAtomicFlagClear %u64_var %device %relaxed )"; - CompileSuccessfully(GenerateKernelCode(body)); + CompileSuccessfully(GenerateKernelCode(body, "OpCapability Int64Atomics\n")); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("AtomicFlagClear: " - "expected Pointer to point to a value of 32-bit int type")); + "expected Pointer to point to a value of 32-bit integer type")); } TEST_F(ValidateAtomics, AtomicFlagClearWrongScopeType) { @@ -1365,7 +1800,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1384,7 +1819,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1404,7 +1839,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1424,7 +1859,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1444,7 +1879,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1464,7 +1899,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1484,7 +1919,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1503,7 +1938,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1522,7 +1957,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1541,7 +1976,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1560,7 +1995,28 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), + SPV_ENV_UNIVERSAL_1_3); + EXPECT_EQ(SPV_ERROR_INVALID_DATA, + ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("SequentiallyConsistent memory semantics cannot be " + "used with the VulkanKHR memory model.")); +} + +TEST_F(ValidateAtomics, VulkanMemoryModelBanSequentiallyConsistentAtomicFMinEXT) { + const std::string body = R"( +%max = OpAtomicFMinEXT %f32 %f32_var %workgroup %sequentially_consistent %f32_0 +)"; + + const std::string extra = R"( +OpCapability VulkanMemoryModelKHR +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_KHR_vulkan_memory_model" +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1579,7 +2035,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1598,7 +2054,28 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), + SPV_ENV_UNIVERSAL_1_3); + EXPECT_EQ(SPV_ERROR_INVALID_DATA, + ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("SequentiallyConsistent memory semantics cannot be " + "used with the VulkanKHR memory model.")); +} + +TEST_F(ValidateAtomics, VulkanMemoryModelBanSequentiallyConsistentAtomicFMaxEXT) { + const std::string body = R"( +%max = OpAtomicFMaxEXT %f32 %f32_var %workgroup %sequentially_consistent %f32_0 +)"; + + const std::string extra = R"( +OpCapability VulkanMemoryModelKHR +OpCapability AtomicFloat32MinMaxEXT +OpExtension "SPV_KHR_vulkan_memory_model" +OpExtension "SPV_EXT_shader_atomic_float_min_max" +)"; + + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1617,7 +2094,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1636,7 +2113,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1655,7 +2132,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -1879,7 +2356,7 @@ OpCapability VulkanMemoryModelKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderComputeCode(body, extra, "", "VulkanKHR"), SPV_ENV_VULKAN_1_1); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_1)); } @@ -2007,7 +2484,7 @@ TEST_F(ValidateAtomics, VulkanMemoryModelDeviceScopeBad) { OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); @@ -2027,80 +2504,11 @@ OpCapability VulkanMemoryModelDeviceScopeKHR OpExtension "SPV_KHR_vulkan_memory_model" )"; - CompileSuccessfully(GenerateShaderCode(body, extra, "VulkanKHR"), + CompileSuccessfully(GenerateShaderCode(body, extra, "", "VulkanKHR"), SPV_ENV_UNIVERSAL_1_3); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); } -TEST_F(ValidateAtomics, WebGPUCrossDeviceMemoryScopeBad) { - const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %cross_device %relaxed -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("in WebGPU environment Memory Scope is limited to " - "QueueFamilyKHR for OpAtomic* operations")); -} - -TEST_F(ValidateAtomics, WebGPUDeviceMemoryScopeBad) { - const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %device %relaxed -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("in WebGPU environment Memory Scope is limited to " - "QueueFamilyKHR for OpAtomic* operations")); -} - -TEST_F(ValidateAtomics, WebGPUWorkgroupMemoryScopeBad) { - const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %workgroup %relaxed -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("in WebGPU environment Memory Scope is limited to " - "QueueFamilyKHR for OpAtomic* operations")); -} - -TEST_F(ValidateAtomics, WebGPUSubgroupMemoryScopeBad) { - const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %subgroup %relaxed -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("in WebGPU environment Memory Scope is limited to " - "QueueFamilyKHR for OpAtomic* operations")); -} - -TEST_F(ValidateAtomics, WebGPUInvocationMemoryScopeBad) { - const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %invocation %relaxed -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("in WebGPU environment Memory Scope is limited to " - "QueueFamilyKHR for OpAtomic* operations")); -} - -TEST_F(ValidateAtomics, WebGPUQueueFamilyMemoryScopeGood) { - const std::string body = R"( -%val1 = OpAtomicLoad %u32 %u32_var %queuefamily %relaxed -)"; - - CompileSuccessfully(GenerateWebGPUShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - TEST_F(ValidateAtomics, CompareExchangeWeakV13ValV14Good) { const std::string body = R"( %val1 = OpAtomicCompareExchangeWeak %u32 %u32_var %device %relaxed %relaxed %u32_0 %u32_0 diff --git a/third_party/spirv-tools/test/val/val_barriers_test.cpp b/third_party/spirv-tools/test/val/val_barriers_test.cpp index 3643883227..1178ca02d6 100644 --- a/third_party/spirv-tools/test/val/val_barriers_test.cpp +++ b/third_party/spirv-tools/test/val/val_barriers_test.cpp @@ -121,40 +121,13 @@ OpCapability Int64 execution_model, memory_model); } -std::string GenerateWebGPUComputeShaderCode( - const std::string& body, - const std::string& capabilities_and_extensions = "", - const std::string& execution_model = "GLCompute") { - const std::string vulkan_memory_capability = R"( -OpCapability VulkanMemoryModelKHR -)"; - const std::string vulkan_memory_extension = R"( -OpExtension "SPV_KHR_vulkan_memory_model" -)"; - const std::string memory_model = "OpMemoryModel Logical VulkanKHR"; - return GenerateShaderCodeImpl(body, - vulkan_memory_capability + - capabilities_and_extensions + - vulkan_memory_extension, - "", execution_model, memory_model); -} - -std::string GenerateWebGPUVertexShaderCode( +std::string GenerateVulkanVertexShaderCode( const std::string& body, const std::string& capabilities_and_extensions = "", const std::string& execution_model = "Vertex") { - const std::string vulkan_memory_capability = R"( -OpCapability VulkanMemoryModelKHR -)"; - const std::string vulkan_memory_extension = R"( -OpExtension "SPV_KHR_vulkan_memory_model" -)"; - const std::string memory_model = "OpMemoryModel Logical VulkanKHR"; - return GenerateShaderCodeImpl(body, - vulkan_memory_capability + - capabilities_and_extensions + - vulkan_memory_extension, - "", execution_model, memory_model); + const std::string memory_model = "OpMemoryModel Logical GLSL450"; + return GenerateShaderCodeImpl(body, capabilities_and_extensions, "", + execution_model, memory_model); } std::string GenerateKernelCode( @@ -271,64 +244,6 @@ OpControlBarrier %workgroup %workgroup %acquire_release_uniform_workgroup ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } -TEST_F(ValidateBarriers, OpControlBarrierWebGPUAcquireReleaseSuccess) { - const std::string body = R"( -OpControlBarrier %workgroup %workgroup %acquire_release_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateBarriers, OpControlBarrierWebGPURelaxedFailure) { - const std::string body = R"( -OpControlBarrier %workgroup %workgroup %workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, AcquireRelease must be set for Memory " - "Semantics of OpControlBarrier")); -} - -TEST_F(ValidateBarriers, OpControlBarrierWebGPUMissingWorkgroupFailure) { - const std::string body = R"( -OpControlBarrier %workgroup %workgroup %acquire_release -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, WorkgroupMemory must be set for Memory " - "Semantics")); -} - -TEST_F(ValidateBarriers, OpControlBarrierWebGPUUniformFailure) { - const std::string body = R"( -OpControlBarrier %workgroup %workgroup %acquire_release_uniform_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("For WebGPU only WorkgroupMemory and AcquireRelease may be set " - "for Memory Semantics of OpControlBarrier.")); -} - -TEST_F(ValidateBarriers, OpControlBarrierWebGPUReleaseFailure) { - const std::string body = R"( -OpControlBarrier %workgroup %workgroup %release_uniform_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, AcquireRelease must be set for Memory " - "Semantics of OpControlBarrier")); -} - TEST_F(ValidateBarriers, OpControlBarrierExecutionModelFragmentSpirv12) { const std::string body = R"( OpControlBarrier %device %device %none @@ -430,49 +345,13 @@ OpControlBarrier %device %workgroup %none CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04636")); EXPECT_THAT(getDiagnosticString(), HasSubstr("ControlBarrier: in Vulkan environment Execution Scope " "is limited to Workgroup and Subgroup")); } -TEST_F(ValidateBarriers, OpControlBarrierWebGPUExecutionScopeDeviceBad) { - const std::string body = R"( -OpControlBarrier %device %workgroup %none -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("ControlBarrier: in WebGPU environment Execution Scope " - "is limited to Workgroup")); -} - -TEST_F(ValidateBarriers, OpControlBarrierWebGPUExecutionScopeSubgroupBad) { - const std::string body = R"( -OpControlBarrier %subgroup %workgroup %none -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("ControlBarrier: in WebGPU environment Execution Scope " - "is limited to Workgroup")); -} - -TEST_F(ValidateBarriers, - OpControlBarrierWebGPUExecutionScopeWorkgroupNonComputeBad) { - const std::string body = R"( -OpControlBarrier %workgroup %workgroup %acquire_release_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUVertexShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr( - "Workgroup Execution Scope is limited to GLCompute execution model")); -} - TEST_F(ValidateBarriers, OpControlBarrierVulkanMemoryScopeSubgroup) { const std::string body = R"( OpControlBarrier %subgroup %subgroup %none @@ -480,6 +359,8 @@ OpControlBarrier %subgroup %subgroup %none CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04638")); EXPECT_THAT( getDiagnosticString(), HasSubstr("ControlBarrier: in Vulkan 1.0 environment Memory Scope is " @@ -502,21 +383,84 @@ OpControlBarrier %subgroup %cross_device %none CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04638")); EXPECT_THAT(getDiagnosticString(), HasSubstr("ControlBarrier: in Vulkan environment, Memory Scope " "cannot be CrossDevice")); } -TEST_F(ValidateBarriers, OpControlBarrierWebGPUMemoryScopeNonWorkgroup) { +TEST_F(ValidateBarriers, + OpControlBarrierVulkan1p1WorkgroupNonComputeMemoryFailure) { const std::string body = R"( -OpControlBarrier %workgroup %subgroup %acquire_release_workgroup +OpControlBarrier %subgroup %workgroup %acquire )"; - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); + CompileSuccessfully(GenerateVulkanVertexShaderCode(body), SPV_ENV_VULKAN_1_1); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("ControlBarrier: in WebGPU environment Memory Scope is " - "limited to Workgroup for OpControlBarrier")); + AnyVUID("VUID-StandaloneSpirv-None-04639")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Workgroup Memory Scope is limited to MeshNV, TaskNV, " + "and GLCompute execution model")); +} + +TEST_F(ValidateBarriers, + OpControlBarrierVulkan1p1WorkgroupNonComputeExecutionFailure) { + const std::string body = R"( +OpControlBarrier %workgroup %subgroup %acquire +)"; + + CompileSuccessfully(GenerateVulkanVertexShaderCode(body), SPV_ENV_VULKAN_1_1); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04637")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("in Vulkan environment, Workgroup execution scope is " + "only for TaskNV, MeshNV, TessellationControl, and " + "GLCompute execution models")); +} + +TEST_F(ValidateBarriers, OpControlBarrierVulkan1p1WorkgroupComputeSuccess) { + const std::string body = R"( +OpControlBarrier %workgroup %workgroup %acquire +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_1); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_1)); +} + +TEST_F(ValidateBarriers, OpControlBarrierVulkan1p1WorkgroupNonComputeSuccess) { + const std::string body = R"( +OpControlBarrier %subgroup %subgroup %acquire +)"; + + CompileSuccessfully(GenerateVulkanVertexShaderCode(body), SPV_ENV_VULKAN_1_1); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_1)); +} + +TEST_F(ValidateBarriers, OpControlBarrierVulkanInvocationSuccess) { + const std::string body = R"( +OpControlBarrier %workgroup %invocation %none +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateBarriers, OpControlBarrierVulkanInvocationFailure) { + const std::string body = R"( +OpControlBarrier %workgroup %invocation %acquire +)"; + + CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04641")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("ControlBarrier: Vulkan specification requires Memory " + "Semantics to be None if used with Invocation Memory Scope")); } TEST_F(ValidateBarriers, OpControlBarrierAcquireAndRelease) { @@ -567,9 +511,13 @@ OpControlBarrier %workgroup %workgroup %acquire_release SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("OpControlBarrier execution scope must be Subgroup for " - "Fragment, Vertex, Geometry and TessellationEvaluation " - "execution models")); + AnyVUID("VUID-StandaloneSpirv-OpControlBarrier-04682")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpControlBarrier execution scope must be Subgroup for Fragment, " + "Vertex, Geometry, TessellationEvaluation, RayGeneration, " + "Intersection, AnyHit, ClosestHit, and Miss execution models")); } TEST_F(ValidateBarriers, OpControlBarrierSubgroupExecutionFragment1p0) { @@ -605,9 +553,13 @@ OpControlBarrier %workgroup %workgroup %acquire_release SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("OpControlBarrier execution scope must be Subgroup for " - "Fragment, Vertex, Geometry and TessellationEvaluation " - "execution models")); + AnyVUID("VUID-StandaloneSpirv-OpControlBarrier-04682")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpControlBarrier execution scope must be Subgroup for Fragment, " + "Vertex, Geometry, TessellationEvaluation, RayGeneration, " + "Intersection, AnyHit, ClosestHit, and Miss execution models")); } TEST_F(ValidateBarriers, OpControlBarrierSubgroupExecutionVertex1p0) { @@ -645,9 +597,13 @@ OpControlBarrier %workgroup %workgroup %acquire_release SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("OpControlBarrier execution scope must be Subgroup for " - "Fragment, Vertex, Geometry and TessellationEvaluation " - "execution models")); + AnyVUID("VUID-StandaloneSpirv-OpControlBarrier-04682")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpControlBarrier execution scope must be Subgroup for Fragment, " + "Vertex, Geometry, TessellationEvaluation, RayGeneration, " + "Intersection, AnyHit, ClosestHit, and Miss execution models")); } TEST_F(ValidateBarriers, OpControlBarrierSubgroupExecutionGeometry1p0) { @@ -688,9 +644,13 @@ OpControlBarrier %workgroup %workgroup %acquire_release SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("OpControlBarrier execution scope must be Subgroup for " - "Fragment, Vertex, Geometry and TessellationEvaluation " - "execution models")); + AnyVUID("VUID-StandaloneSpirv-OpControlBarrier-04682")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpControlBarrier execution scope must be Subgroup for Fragment, " + "Vertex, Geometry, TessellationEvaluation, RayGeneration, " + "Intersection, AnyHit, ClosestHit, and Miss execution models")); } TEST_F(ValidateBarriers, @@ -738,100 +698,6 @@ OpMemoryBarrier %workgroup %acquire_release_uniform_workgroup ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUImageMemorySuccess) { - const std::string body = R"( -OpMemoryBarrier %workgroup %image_memory -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUDeviceFailure) { - const std::string body = R"( -OpMemoryBarrier %subgroup %image_memory -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("in WebGPU environment Memory Scope is limited to " - "Workgroup for OpMemoryBarrier")); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUAcquireReleaseFailure) { - const std::string body = R"( -OpMemoryBarrier %workgroup %acquire_release_uniform_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("ImageMemory must be set for Memory Semantics of " - "OpMemoryBarrier")); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPURelaxedFailure) { - const std::string body = R"( -OpMemoryBarrier %workgroup %uniform_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("ImageMemory must be set for Memory Semantics of " - "OpMemoryBarrier")); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUAcquireFailure) { - const std::string body = R"( -OpMemoryBarrier %workgroup %acquire_uniform_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("ImageMemory must be set for Memory Semantics of " - "OpMemoryBarrier")); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUReleaseFailure) { - const std::string body = R"( -OpMemoryBarrier %workgroup %release_uniform_workgroup -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("ImageMemory must be set for Memory Semantics of " - "OpMemoryBarrier")); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUUniformFailure) { - const std::string body = R"( -OpMemoryBarrier %workgroup %uniform_image_memory -)"; - - CompileSuccessfully(GenerateWebGPUComputeShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("only ImageMemory may be set for Memory Semantics of " - "OpMemoryBarrier")); -} - -TEST_F(ValidateBarriers, OpMemoryBarrierWebGPUWorkgroupNonComputeFailure) { - const std::string body = R"( -OpMemoryBarrier %workgroup %image_memory -)"; - - CompileSuccessfully(GenerateWebGPUVertexShaderCode(body), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr( - "Workgroup Memory Scope is limited to GLCompute execution model")); -} - TEST_F(ValidateBarriers, OpMemoryBarrierFloatMemoryScope) { const std::string body = R"( OpMemoryBarrier %f32_1 %acquire_release_uniform_workgroup @@ -885,6 +751,8 @@ OpMemoryBarrier %subgroup %acquire_release_uniform_workgroup CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04638")); EXPECT_THAT( getDiagnosticString(), HasSubstr("MemoryBarrier: in Vulkan 1.0 environment Memory Scope is " @@ -920,6 +788,8 @@ OpMemoryBarrier %device %none CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpMemoryBarrier-04732")); EXPECT_THAT( getDiagnosticString(), HasSubstr("MemoryBarrier: Vulkan specification requires Memory Semantics " @@ -934,6 +804,8 @@ OpMemoryBarrier %device %acquire CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpMemoryBarrier-04733")); EXPECT_THAT(getDiagnosticString(), HasSubstr("MemoryBarrier: expected Memory Semantics to include a " "Vulkan-supported storage class")); @@ -946,6 +818,8 @@ OpMemoryBarrier %device %acquire_release_subgroup CompileSuccessfully(GenerateShaderCode(body), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpMemoryBarrier-04733")); EXPECT_THAT(getDiagnosticString(), HasSubstr("MemoryBarrier: expected Memory Semantics to include a " "Vulkan-supported storage class")); @@ -1595,7 +1469,7 @@ TEST_F(ValidateBarriers, OpMemoryBarrierShaderCallRayGenSuccess) { // capabilities_and_extensions R"( OpCapability VulkanMemoryModelKHR - OpCapability RayTracingProvisionalKHR + OpCapability RayTracingKHR OpExtension "SPV_KHR_vulkan_memory_model" OpExtension "SPV_KHR_ray_tracing" )", @@ -1629,6 +1503,8 @@ TEST_F(ValidateBarriers, OpMemoryBarrierShaderCallComputeFailure) { SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04640")); EXPECT_THAT( getDiagnosticString(), HasSubstr( @@ -1642,7 +1518,7 @@ TEST_F(ValidateBarriers, OpControlBarrierShaderCallRayGenFailure) { // capabilities_and_extensions R"( OpCapability VulkanMemoryModelKHR - OpCapability RayTracingProvisionalKHR + OpCapability RayTracingKHR OpExtension "SPV_KHR_vulkan_memory_model" OpExtension "SPV_KHR_ray_tracing" )", @@ -1655,6 +1531,8 @@ TEST_F(ValidateBarriers, OpControlBarrierShaderCallRayGenFailure) { SPV_ENV_VULKAN_1_1); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04636")); EXPECT_THAT(getDiagnosticString(), HasSubstr("in Vulkan environment Execution Scope is limited to " "Workgroup and Subgroup")); diff --git a/third_party/spirv-tools/test/val/val_builtins_test.cpp b/third_party/spirv-tools/test/val/val_builtins_test.cpp index 74d5c3ab50..2116fff26a 100644 --- a/third_party/spirv-tools/test/val/val_builtins_test.cpp +++ b/third_party/spirv-tools/test/val/val_builtins_test.cpp @@ -54,18 +54,14 @@ using ::testing::Values; using ::testing::ValuesIn; using ValidateBuiltIns = spvtest::ValidateBase; -using ValidateVulkanSubgroupBuiltIns = spvtest::ValidateBase< - std::tuple>; +using ValidateVulkanSubgroupBuiltIns = + spvtest::ValidateBase>; using ValidateVulkanCombineBuiltInExecutionModelDataTypeResult = spvtest::ValidateBase>; -using ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult = - spvtest::ValidateBase>; using ValidateVulkanCombineBuiltInArrayedVariable = spvtest::ValidateBase< std::tuple>; -using ValidateWebGPUCombineBuiltInArrayedVariable = spvtest::ValidateBase< - std::tuple>; using ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult = spvtest::ValidateBase< std::tuple>; -bool InitializerRequired(spv_target_env env, const char* const storage_class) { - return spvIsWebGPUEnv(env) && (strncmp(storage_class, "Output", 6) == 0 || - strncmp(storage_class, "Private", 7) == 0 || - strncmp(storage_class, "Function", 8) == 0); +bool InitializerRequired(const char* const storage_class) { + return (strncmp(storage_class, "Output", 6) == 0 || + strncmp(storage_class, "Private", 7) == 0 || + strncmp(storage_class, "Function", 8) == 0); } -CodeGenerator GetInMainCodeGenerator(spv_target_env env, - const char* const built_in, +CodeGenerator GetInMainCodeGenerator(const char* const built_in, const char* const execution_model, const char* const storage_class, const char* const capabilities, const char* const extensions, const char* const data_type) { - CodeGenerator generator = - spvIsWebGPUEnv(env) ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); if (capabilities) { generator.capabilities_ += capabilities; @@ -107,13 +100,13 @@ CodeGenerator GetInMainCodeGenerator(spv_target_env env, std::ostringstream after_types; after_types << "%built_in_type = OpTypeStruct " << data_type << "\n"; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << "%built_in_null = OpConstantNull %built_in_type\n"; } after_types << "%built_in_ptr = OpTypePointer " << storage_class << " %built_in_type\n"; after_types << "%built_in_var = OpVariable %built_in_ptr " << storage_class; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << " %built_in_null"; } after_types << "\n"; @@ -158,44 +151,6 @@ CodeGenerator GetInMainCodeGenerator(spv_target_env env, return generator; } -// Allows test parameter test to list all possible VUIDs with a delimiter that -// is then split here to check if one VUID was in the error message -MATCHER_P(AnyVUID, vuid_set, "VUID from the set is in error message") { - // use space as delimiter because clang-format will properly line break VUID - // strings which is important the entire VUID is in a single line for script - // to scan - std::string delimiter = " "; - std::string token; - std::string vuids = std::string(vuid_set); - size_t position; - - // Catch case were someone accidentally left spaces by trimming string - // clang-format off - vuids.erase(std::find_if(vuids.rbegin(), vuids.rend(), [](unsigned char c) { - return (c != ' '); - }).base(), vuids.end()); - vuids.erase(vuids.begin(), std::find_if(vuids.begin(), vuids.end(), [](unsigned char c) { - return (c != ' '); - })); - // clang-format on - - do { - position = vuids.find(delimiter); - if (position != std::string::npos) { - token = vuids.substr(0, position); - vuids.erase(0, position + delimiter.length()); - } else { - token = vuids.substr(0); // last item - } - - // arg contains diagnostic message - if (arg.find(token) != std::string::npos) { - return true; - } - } while (position != std::string::npos); - return false; -} - TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, InMain) { const char* const built_in = std::get<0>(GetParam()); const char* const execution_model = std::get<1>(GetParam()); @@ -204,9 +159,8 @@ TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, InMain) { const char* const vuid = std::get<4>(GetParam()); const TestResult& test_result = std::get<5>(GetParam()); - CodeGenerator generator = - GetInMainCodeGenerator(SPV_ENV_VULKAN_1_0, built_in, execution_model, - storage_class, NULL, NULL, data_type); + CodeGenerator generator = GetInMainCodeGenerator( + built_in, execution_model, storage_class, NULL, NULL, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -222,28 +176,6 @@ TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, InMain) { } } -TEST_P(ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, InMain) { - const char* const built_in = std::get<0>(GetParam()); - const char* const execution_model = std::get<1>(GetParam()); - const char* const storage_class = std::get<2>(GetParam()); - const char* const data_type = std::get<3>(GetParam()); - const TestResult& test_result = std::get<4>(GetParam()); - - CodeGenerator generator = - GetInMainCodeGenerator(SPV_ENV_WEBGPU_0, built_in, execution_model, - storage_class, NULL, NULL, data_type); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(test_result.validation_result, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - if (test_result.error_str) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str)); - } - if (test_result.error_str2) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str2)); - } -} - TEST_P( ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, InMain) { @@ -256,9 +188,9 @@ TEST_P( const char* const vuid = std::get<6>(GetParam()); const TestResult& test_result = std::get<7>(GetParam()); - CodeGenerator generator = GetInMainCodeGenerator( - SPV_ENV_VULKAN_1_0, built_in, execution_model, storage_class, - capabilities, extensions, data_type); + CodeGenerator generator = + GetInMainCodeGenerator(built_in, execution_model, storage_class, + capabilities, extensions, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -288,7 +220,7 @@ TEST_P( const TestResult& test_result = std::get<8>(GetParam()); CodeGenerator generator = - GetInMainCodeGenerator(env, built_in, execution_model, storage_class, + GetInMainCodeGenerator(built_in, execution_model, storage_class, capabilities, extensions, data_type); CompileSuccessfully(generator.Build(), env); @@ -304,16 +236,13 @@ TEST_P( } } -CodeGenerator GetInFunctionCodeGenerator(spv_target_env env, - const char* const built_in, +CodeGenerator GetInFunctionCodeGenerator(const char* const built_in, const char* const execution_model, const char* const storage_class, const char* const capabilities, const char* const extensions, const char* const data_type) { - CodeGenerator generator = - spvIsWebGPUEnv(env) ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); if (capabilities) { generator.capabilities_ += capabilities; @@ -328,13 +257,13 @@ CodeGenerator GetInFunctionCodeGenerator(spv_target_env env, std::ostringstream after_types; after_types << "%built_in_type = OpTypeStruct " << data_type << "\n"; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << "%built_in_null = OpConstantNull %built_in_type\n"; } after_types << "%built_in_ptr = OpTypePointer " << storage_class << " %built_in_type\n"; after_types << "%built_in_var = OpVariable %built_in_ptr " << storage_class; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << " %built_in_null"; } after_types << "\n"; @@ -383,11 +312,7 @@ OpReturn OpFunctionEnd )"; - if (spvIsWebGPUEnv(env)) { - generator.after_types_ += function_body; - } else { - generator.add_at_the_end_ = function_body; - } + generator.add_at_the_end_ = function_body; generator.entry_points_.push_back(std::move(entry_point)); @@ -402,9 +327,8 @@ TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, InFunction) { const char* const vuid = std::get<4>(GetParam()); const TestResult& test_result = std::get<5>(GetParam()); - CodeGenerator generator = - GetInFunctionCodeGenerator(SPV_ENV_VULKAN_1_0, built_in, execution_model, - storage_class, NULL, NULL, data_type); + CodeGenerator generator = GetInFunctionCodeGenerator( + built_in, execution_model, storage_class, NULL, NULL, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -420,28 +344,6 @@ TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, InFunction) { } } -TEST_P(ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, InFunction) { - const char* const built_in = std::get<0>(GetParam()); - const char* const execution_model = std::get<1>(GetParam()); - const char* const storage_class = std::get<2>(GetParam()); - const char* const data_type = std::get<3>(GetParam()); - const TestResult& test_result = std::get<4>(GetParam()); - - CodeGenerator generator = - GetInFunctionCodeGenerator(SPV_ENV_WEBGPU_0, built_in, execution_model, - storage_class, NULL, NULL, data_type); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(test_result.validation_result, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - if (test_result.error_str) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str)); - } - if (test_result.error_str2) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str2)); - } -} - TEST_P( ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, InFunction) { @@ -454,9 +356,9 @@ TEST_P( const char* const vuid = std::get<6>(GetParam()); const TestResult& test_result = std::get<7>(GetParam()); - CodeGenerator generator = GetInFunctionCodeGenerator( - SPV_ENV_VULKAN_1_0, built_in, execution_model, storage_class, - capabilities, extensions, data_type); + CodeGenerator generator = + GetInFunctionCodeGenerator(built_in, execution_model, storage_class, + capabilities, extensions, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -472,16 +374,13 @@ TEST_P( } } -CodeGenerator GetVariableCodeGenerator(spv_target_env env, - const char* const built_in, +CodeGenerator GetVariableCodeGenerator(const char* const built_in, const char* const execution_model, const char* const storage_class, const char* const capabilities, const char* const extensions, const char* const data_type) { - CodeGenerator generator = - spvIsWebGPUEnv(env) ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); if (capabilities) { generator.capabilities_ += capabilities; @@ -495,13 +394,13 @@ CodeGenerator GetVariableCodeGenerator(spv_target_env env, generator.before_types_ += "\n"; std::ostringstream after_types; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << "%built_in_null = OpConstantNull " << data_type << "\n"; } after_types << "%built_in_ptr = OpTypePointer " << storage_class << " " << data_type << "\n"; after_types << "%built_in_var = OpVariable %built_in_ptr " << storage_class; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << " %built_in_null"; } after_types << "\n"; @@ -553,9 +452,8 @@ TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Variable) { const char* const vuid = std::get<4>(GetParam()); const TestResult& test_result = std::get<5>(GetParam()); - CodeGenerator generator = - GetVariableCodeGenerator(SPV_ENV_VULKAN_1_0, built_in, execution_model, - storage_class, NULL, NULL, data_type); + CodeGenerator generator = GetVariableCodeGenerator( + built_in, execution_model, storage_class, NULL, NULL, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -571,28 +469,6 @@ TEST_P(ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Variable) { } } -TEST_P(ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, Variable) { - const char* const built_in = std::get<0>(GetParam()); - const char* const execution_model = std::get<1>(GetParam()); - const char* const storage_class = std::get<2>(GetParam()); - const char* const data_type = std::get<3>(GetParam()); - const TestResult& test_result = std::get<4>(GetParam()); - - CodeGenerator generator = - GetVariableCodeGenerator(SPV_ENV_WEBGPU_0, built_in, execution_model, - storage_class, NULL, NULL, data_type); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(test_result.validation_result, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - if (test_result.error_str) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str)); - } - if (test_result.error_str2) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str2)); - } -} - TEST_P( ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, Variable) { @@ -605,9 +481,9 @@ TEST_P( const char* const vuid = std::get<6>(GetParam()); const TestResult& test_result = std::get<7>(GetParam()); - CodeGenerator generator = GetVariableCodeGenerator( - SPV_ENV_VULKAN_1_0, built_in, execution_model, storage_class, - capabilities, extensions, data_type); + CodeGenerator generator = + GetVariableCodeGenerator(built_in, execution_model, storage_class, + capabilities, extensions, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -641,11 +517,27 @@ INSTANTIATE_TEST_SUITE_P( Values("Input"), Values("%f32arr2", "%f32arr4"), Values(nullptr), Values(TestResult()))); +INSTANTIATE_TEST_SUITE_P( + ClipAndCullDistanceInvalidStorageClass, + ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, + Combine(Values("ClipDistance", "CullDistance"), + Values("Vertex", "Geometry", "TessellationControl", + "TessellationEvaluation"), + Values("Private"), Values("%f32arr2", "%f32arr4"), + Values("VUID-ClipDistance-ClipDistance-04190 " + "VUID-CullDistance-CullDistance-04199"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "to be only used for variables with Input or Output storage " + "class.")))); + INSTANTIATE_TEST_SUITE_P( ClipAndCullDistanceFragmentOutput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("ClipDistance", "CullDistance"), Values("Fragment"), - Values("Output"), Values("%f32arr4"), Values(nullptr), + Values("Output"), Values("%f32arr4"), + Values("VUID-ClipDistance-ClipDistance-04189 " + "VUID-CullDistance-CullDistance-04198"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow BuiltIn ClipDistance/CullDistance " @@ -654,20 +546,22 @@ INSTANTIATE_TEST_SUITE_P( "which is called with execution model Fragment.")))); INSTANTIATE_TEST_SUITE_P( - VertexIdAndInstanceIdVertexInput, + VertexIdVertexInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("VertexId", "InstanceId"), Values("Vertex"), Values("Input"), - Values("%u32"), Values(nullptr), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "Vulkan spec doesn't allow BuiltIn VertexId/InstanceId to be " - "used.")))); + Combine( + Values("VertexId"), Values("Vertex"), Values("Input"), Values("%u32"), + Values(nullptr), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec doesn't allow BuiltIn VertexId to be " + "used.")))); INSTANTIATE_TEST_SUITE_P( ClipAndCullDistanceVertexInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("ClipDistance", "CullDistance"), Values("Vertex"), - Values("Input"), Values("%f32arr4"), Values(nullptr), + Values("Input"), Values("%f32arr4"), + Values("VUID-ClipDistance-ClipDistance-04188 " + "VUID-CullDistance-CullDistance-04197"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow BuiltIn ClipDistance/CullDistance " @@ -725,11 +619,6 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("FragCoord"), Values("Fragment"), Values("Input"), Values("%f32vec4"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - FragCoordSuccess, ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragCoord"), Values("Fragment"), Values("Input"), - Values("%f32vec4"), Values(TestResult()))); - INSTANTIATE_TEST_SUITE_P( FragCoordNotFragment, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -742,15 +631,6 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "to be used only with Fragment execution model")))); -INSTANTIATE_TEST_SUITE_P( - FragCoordNotFragment, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("FragCoord"), Values("Vertex", "GLCompute"), Values("Input"), - Values("%f32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with Fragment execution model")))); - INSTANTIATE_TEST_SUITE_P( FragCoordNotInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("FragCoord"), Values("Fragment"), Values("Output"), @@ -760,15 +640,6 @@ INSTANTIATE_TEST_SUITE_P( "to be only used for variables with Input storage class", "uses storage class Output")))); -INSTANTIATE_TEST_SUITE_P( - FragCoordNotInput, ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragCoord"), Values("Fragment"), Values("Output"), - Values("%f32vec4"), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "to be only used for variables with Input storage class", - "uses storage class Output")))); - INSTANTIATE_TEST_SUITE_P( FragCoordNotFloatVector, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -779,15 +650,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 4-component 32-bit float vector", "is not a float vector")))); -INSTANTIATE_TEST_SUITE_P( - FragCoordNotFloatVector, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragCoord"), Values("Fragment"), Values("Input"), - Values("%f32arr4", "%u32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 4-component 32-bit float vector", - "is not a float vector")))); - INSTANTIATE_TEST_SUITE_P( FragCoordNotFloatVec4, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -797,15 +659,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 4-component 32-bit float vector", "has 3 components")))); -INSTANTIATE_TEST_SUITE_P( - FragCoordNotFloatVec4, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragCoord"), Values("Fragment"), Values("Input"), - Values("%f32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 4-component 32-bit float vector", - "has 3 components")))); - INSTANTIATE_TEST_SUITE_P( FragCoordNotF32Vec4, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -820,11 +673,6 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("FragDepth"), Values("Fragment"), Values("Output"), Values("%f32"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - FragDepthSuccess, ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragDepth"), Values("Fragment"), Values("Output"), - Values("%f32"), Values(TestResult()))); - INSTANTIATE_TEST_SUITE_P( FragDepthNotFragment, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -837,15 +685,6 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "to be used only with Fragment execution model")))); -INSTANTIATE_TEST_SUITE_P( - FragDepthNotFragment, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("FragDepth"), Values("Vertex", "GLCompute"), Values("Output"), - Values("%f32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with Fragment execution model")))); - INSTANTIATE_TEST_SUITE_P( FragDepthNotOutput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -856,16 +695,6 @@ INSTANTIATE_TEST_SUITE_P( "to be only used for variables with Output storage class", "uses storage class Input")))); -INSTANTIATE_TEST_SUITE_P( - FragDepthNotOutput, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragDepth"), Values("Fragment"), Values("Input"), - Values("%f32"), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "to be only used for variables with Output storage class", - "uses storage class Input")))); - INSTANTIATE_TEST_SUITE_P( FragDepthNotFloatScalar, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -876,15 +705,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 32-bit float scalar", "is not a float scalar")))); -INSTANTIATE_TEST_SUITE_P( - FragDepthNotFloatScalar, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FragDepth"), Values("Fragment"), Values("Output"), - Values("%f32vec4", "%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 32-bit float scalar", - "is not a float scalar")))); - INSTANTIATE_TEST_SUITE_P( FragDepthNotF32, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("FragDepth"), Values("Fragment"), Values("Output"), @@ -900,12 +720,6 @@ INSTANTIATE_TEST_SUITE_P( Values("Input"), Values("%bool"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - FrontFacingSuccess, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FrontFacing"), Values("Fragment"), Values("Input"), - Values("%bool"), Values(TestResult()))); - INSTANTIATE_TEST_SUITE_P( FrontFacingAndHelperInvocationNotFragment, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -919,15 +733,6 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "to be used only with Fragment execution model")))); -INSTANTIATE_TEST_SUITE_P( - FrontFacingNotFragment, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("FrontFacing"), Values("Vertex", "GLCompute"), Values("Input"), - Values("%bool"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with Fragment execution model")))); - INSTANTIATE_TEST_SUITE_P( FrontFacingAndHelperInvocationNotInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -940,16 +745,6 @@ INSTANTIATE_TEST_SUITE_P( "to be only used for variables with Input storage class", "uses storage class Output")))); -INSTANTIATE_TEST_SUITE_P( - FrontFacingNotInput, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FrontFacing"), Values("Fragment"), Values("Output"), - Values("%bool"), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "to be only used for variables with Input storage class", - "uses storage class Output")))); - INSTANTIATE_TEST_SUITE_P( FrontFacingAndHelperInvocationNotBool, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -961,15 +756,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a bool scalar", "is not a bool scalar")))); -INSTANTIATE_TEST_SUITE_P( - FrontFacingNotBool, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("FrontFacing"), Values("Fragment"), Values("Input"), - Values("%f32", "%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a bool scalar", - "is not a bool scalar")))); - INSTANTIATE_TEST_SUITE_P( ComputeShaderInputInt32Vec3Success, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -978,13 +764,6 @@ INSTANTIATE_TEST_SUITE_P( Values("GLCompute"), Values("Input"), Values("%u32vec3"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - ComputeShaderInputInt32Vec3Success, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("GlobalInvocationId", "LocalInvocationId", "NumWorkgroups"), - Values("GLCompute"), Values("Input"), Values("%u32vec3"), - Values(TestResult()))); - INSTANTIATE_TEST_SUITE_P( ComputeShaderInputInt32Vec3NotGLCompute, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1001,15 +780,6 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "to be used only with GLCompute execution model")))); -INSTANTIATE_TEST_SUITE_P( - ComputeShaderInputInt32Vec3NotGLCompute, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("GlobalInvocationId", "LocalInvocationId", "NumWorkgroups"), - Values("Vertex", "Fragment"), Values("Input"), Values("%u32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with GLCompute execution model")))); - INSTANTIATE_TEST_SUITE_P( ComputeShaderInputInt32Vec3NotInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1025,16 +795,6 @@ INSTANTIATE_TEST_SUITE_P( "to be only used for variables with Input storage class", "uses storage class Output")))); -INSTANTIATE_TEST_SUITE_P( - ComputeShaderInputInt32Vec3NotInput, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("GlobalInvocationId", "LocalInvocationId", "NumWorkgroups"), - Values("GLCompute"), Values("Output"), Values("%u32vec3"), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "to be only used for variables with Input storage class", - "uses storage class Output")))); - INSTANTIATE_TEST_SUITE_P( ComputeShaderInputInt32Vec3NotIntVector, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1050,16 +810,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 3-component 32-bit int vector", "is not an int vector")))); -INSTANTIATE_TEST_SUITE_P( - ComputeShaderInputInt32Vec3NotIntVector, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("GlobalInvocationId", "LocalInvocationId", "NumWorkgroups"), - Values("GLCompute"), Values("Input"), - Values("%u32arr3", "%f32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 3-component 32-bit int vector", - "is not an int vector")))); - INSTANTIATE_TEST_SUITE_P( ComputeShaderInputInt32Vec3NotIntVec3, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1074,15 +824,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 3-component 32-bit int vector", "has 4 components")))); -INSTANTIATE_TEST_SUITE_P( - ComputeShaderInputInt32Vec3NotIntVec3, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("GlobalInvocationId", "LocalInvocationId", "NumWorkgroups"), - Values("GLCompute"), Values("Input"), Values("%u32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 3-component 32-bit int vector", - "has 4 components")))); - INSTANTIATE_TEST_SUITE_P( ComputeShaderInputInt32Vec3NotInt32Vec, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1152,12 +893,6 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("InstanceIndex"), Values("Vertex"), Values("Input"), Values("%u32"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - InstanceIndexSuccess, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("InstanceIndex"), Values("Vertex"), Values("Input"), - Values("%u32"), Values(TestResult()))); - INSTANTIATE_TEST_SUITE_P( InstanceIndexInvalidExecutionModel, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1169,14 +904,6 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "to be used only with Vertex execution model")))); -INSTANTIATE_TEST_SUITE_P( - InstanceIndexInvalidExecutionModel, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("InstanceIndex"), Values("Fragment", "GLCompute"), - Values("Input"), Values("%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with Vertex execution model")))); - INSTANTIATE_TEST_SUITE_P( InstanceIndexNotInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1187,16 +914,6 @@ INSTANTIATE_TEST_SUITE_P( "to be only used for variables with Input storage class", "uses storage class Output")))); -INSTANTIATE_TEST_SUITE_P( - InstanceIndexNotInput, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("InstanceIndex"), Values("Vertex"), Values("Output"), - Values("%u32"), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "to be only used for variables with Input storage class", - "uses storage class Output")))); - INSTANTIATE_TEST_SUITE_P( InstanceIndexNotIntScalar, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1207,15 +924,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 32-bit int scalar", "is not an int scalar")))); -INSTANTIATE_TEST_SUITE_P( - InstanceIndexNotIntScalar, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("InstanceIndex"), Values("Vertex"), Values("Input"), - Values("%f32", "%u32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 32-bit int scalar", - "is not an int scalar")))); - INSTANTIATE_TEST_SUITE_P( InstanceIndexNotInt32, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1256,7 +964,8 @@ INSTANTIATE_TEST_SUITE_P( ViewportIndexExecutionModelEnabledByCapability, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("ViewportIndex"), Values("Vertex", "TessellationEvaluation"), - Values("Output"), Values("%u32"), Values(nullptr), + Values("Output"), Values("%u32"), + Values("VUID-ViewportIndex-ViewportIndex-04405"), Values(TestResult( SPV_ERROR_INVALID_DATA, "ShaderViewportIndexLayerEXT or ShaderViewportIndex")))); @@ -1265,7 +974,7 @@ INSTANTIATE_TEST_SUITE_P( LayerExecutionModelEnabledByCapability, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("Layer"), Values("Vertex", "TessellationEvaluation"), - Values("Output"), Values("%u32"), Values(nullptr), + Values("Output"), Values("%u32"), Values("VUID-Layer-Layer-04273"), Values(TestResult(SPV_ERROR_INVALID_DATA, "ShaderViewportIndexLayerEXT or ShaderLayer")))); @@ -1506,21 +1215,6 @@ INSTANTIATE_TEST_SUITE_P( Values("Output"), Values("%f32vec4"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - PositionOutputSuccess, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("Position"), Values("Vertex"), Values("Output"), - Values("%f32vec4"), Values(TestResult()))); - -INSTANTIATE_TEST_SUITE_P( - PositionOutputFailure, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("Position"), Values("Fragment", "GLCompute"), - Values("Output"), Values("%f32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "WebGPU spec allows BuiltIn Position to be used " - "only with the Vertex execution model.")))); - INSTANTIATE_TEST_SUITE_P( PositionInputSuccess, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1530,20 +1224,22 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult()))); INSTANTIATE_TEST_SUITE_P( - PositionInputFailure, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("Position"), Values("Vertex", "Fragment", "GLCompute"), - Values("Input"), Values("%f32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "WebGPU spec allows BuiltIn Position to be only used " - "for variables with Output storage class")))); + PositionInvalidStorageClass, + ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, + Combine(Values("Position"), + Values("Geometry", "TessellationControl", "TessellationEvaluation"), + Values("Private"), Values("%f32vec4"), + Values("VUID-Position-Position-04320"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn Position to be only used for " + "variables with Input or Output storage class.")))); INSTANTIATE_TEST_SUITE_P( PositionVertexInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("Position"), Values("Vertex"), Values("Input"), - Values("%f32vec4"), Values("VUID-Position-Position-04320"), + Values("%f32vec4"), Values("VUID-Position-Position-04319"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow BuiltIn Position " @@ -1572,15 +1268,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 4-component 32-bit float vector", "is not a float vector")))); -INSTANTIATE_TEST_SUITE_P( - PositionNotFloatVector, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("Position"), Values("Vertex"), Values("Output"), - Values("%f32arr4", "%u32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 4-component 32-bit float vector")))); - INSTANTIATE_TEST_SUITE_P( PositionNotFloatVec4, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1590,15 +1277,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 4-component 32-bit float vector", "has 3 components")))); -INSTANTIATE_TEST_SUITE_P( - PositionNotFloatVec4, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("Position"), Values("Vertex"), Values("Output"), - Values("%f32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 4-component 32-bit float vector")))); - INSTANTIATE_TEST_SUITE_P( PositionNotF32Vec4, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -1632,7 +1310,8 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult( SPV_ERROR_INVALID_DATA, "to be used only with Fragment, TessellationControl, " - "TessellationEvaluation or Geometry execution models")))); + "TessellationEvaluation, Geometry, MeshNV, IntersectionKHR, " + "AnyHitKHR, and ClosestHitKHR execution models")))); INSTANTIATE_TEST_SUITE_P( PrimitiveIdFragmentNotInput, @@ -1645,7 +1324,7 @@ INSTANTIATE_TEST_SUITE_P( "which is called with execution model Fragment")))); INSTANTIATE_TEST_SUITE_P( - PrimitiveIdGeometryNotInput, + PrimitiveIdTessellationNotInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("PrimitiveId"), Values("TessellationControl", "TessellationEvaluation"), @@ -1917,7 +1596,8 @@ INSTANTIATE_TEST_SUITE_P( TessLevelOuterOutputTese, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("TessLevelOuter"), Values("TessellationEvaluation"), - Values("Output"), Values("%f32arr4"), Values(nullptr), + Values("Output"), Values("%f32arr4"), + Values("VUID-TessLevelOuter-TessLevelOuter-04392"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow TessLevelOuter/TessLevelInner to be " @@ -1928,7 +1608,8 @@ INSTANTIATE_TEST_SUITE_P( TessLevelOuterInputTesc, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("TessLevelOuter"), Values("TessellationControl"), - Values("Input"), Values("%f32arr4"), Values(nullptr), + Values("Input"), Values("%f32arr4"), + Values("VUID-TessLevelOuter-TessLevelOuter-04391"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow TessLevelOuter/TessLevelInner to be " @@ -2004,7 +1685,8 @@ INSTANTIATE_TEST_SUITE_P( TessLevelInnerOutputTese, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("TessLevelInner"), Values("TessellationEvaluation"), - Values("Output"), Values("%f32arr2"), Values(nullptr), + Values("Output"), Values("%f32arr2"), + Values("VUID-TessLevelInner-TessLevelInner-04396"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow TessLevelOuter/TessLevelInner to be " @@ -2015,7 +1697,8 @@ INSTANTIATE_TEST_SUITE_P( TessLevelInnerInputTesc, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, Combine(Values("TessLevelInner"), Values("TessellationControl"), - Values("Input"), Values("%f32arr2"), Values(nullptr), + Values("Input"), Values("%f32arr2"), + Values("VUID-TessLevelInner-TessLevelInner-04395"), Values(TestResult( SPV_ERROR_INVALID_DATA, "Vulkan spec doesn't allow TessLevelOuter/TessLevelInner to be " @@ -2068,12 +1751,6 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("VertexIndex"), Values("Vertex"), Values("Input"), Values("%u32"), Values(nullptr), Values(TestResult()))); -INSTANTIATE_TEST_SUITE_P( - VertexIndexSuccess, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("VertexIndex"), Values("Vertex"), Values("Input"), - Values("%u32"), Values(TestResult()))); - INSTANTIATE_TEST_SUITE_P( VertexIndexInvalidExecutionModel, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -2085,14 +1762,6 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "to be used only with Vertex execution model")))); -INSTANTIATE_TEST_SUITE_P( - VertexIndexInvalidExecutionModel, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("VertexIndex"), Values("Fragment", "GLCompute"), - Values("Input"), Values("%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with Vertex execution model")))); - INSTANTIATE_TEST_SUITE_P( VertexIndexNotInput, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -2103,16 +1772,6 @@ INSTANTIATE_TEST_SUITE_P( "Vulkan spec allows BuiltIn VertexIndex to be only " "used for variables with Input storage class")))); -INSTANTIATE_TEST_SUITE_P( - VertexIndexNotInput, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("VertexIndex"), Values("Vertex"), Values("Output"), - Values("%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "WebGPU spec allows BuiltIn VertexIndex to be only " - "used for variables with Input storage class")))); - INSTANTIATE_TEST_SUITE_P( VertexIndexNotIntScalar, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -2123,15 +1782,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 32-bit int scalar", "is not an int scalar")))); -INSTANTIATE_TEST_SUITE_P( - VertexIndexNotIntScalar, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("VertexIndex"), Values("Vertex"), Values("Input"), - Values("%f32", "%u32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 32-bit int scalar", - "is not an int scalar")))); - INSTANTIATE_TEST_SUITE_P( VertexIndexNotInt32, ValidateVulkanCombineBuiltInExecutionModelDataTypeResult, @@ -2141,50 +1791,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 32-bit int scalar", "has bit width 64")))); -INSTANTIATE_TEST_SUITE_P( - LocalInvocationIndexSuccess, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("LocalInvocationIndex"), Values("GLCompute"), - Values("Input"), Values("%u32"), Values(TestResult()))); - -INSTANTIATE_TEST_SUITE_P( - LocalInvocationIndexInvalidExecutionModel, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("LocalInvocationIndex"), Values("Fragment", "Vertex"), - Values("Input"), Values("%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "to be used only with GLCompute execution model")))); - -INSTANTIATE_TEST_SUITE_P( - LocalInvocationIndexNotInput, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine( - Values("LocalInvocationIndex"), Values("GLCompute"), Values("Output"), - Values("%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "WebGPU spec allows BuiltIn LocalInvocationIndex to " - "be only used for variables with Input storage " - "class")))); - -INSTANTIATE_TEST_SUITE_P( - LocalInvocationIndexNotIntScalar, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("LocalInvocationIndex"), Values("GLCompute"), - Values("Input"), Values("%f32", "%u32vec3"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 32-bit int", "is not an int")))); - -INSTANTIATE_TEST_SUITE_P( - AllowListRejection, - ValidateWebGPUCombineBuiltInExecutionModelDataTypeResult, - Combine(Values("PointSize", "ClipDistance", "CullDistance", "VertexId", - "InstanceId", "PointCoord", "SampleMask", "HelperInvocation", - "WorkgroupId"), - Values("Vertex"), Values("Input"), Values("%u32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "WebGPU does not allow BuiltIn")))); - INSTANTIATE_TEST_SUITE_P( BaseInstanceOrVertexSuccess, ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, @@ -2362,14 +1968,586 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 32-bit int scalar", "is not an int scalar")))); -CodeGenerator GetArrayedVariableCodeGenerator(spv_target_env env, - const char* const built_in, +// Test HitKind in NV RT shaders +INSTANTIATE_TEST_SUITE_P( + HitKindNVSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitKindNV"), + Values("AnyHitNV", "ClosestHitNV"), Values("Input"), Values("%u32"), + Values("OpCapability RayTracingNV\n"), + Values("OpExtension \"SPV_NV_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +// HitKind is valid in AH, CH shaders as input i32 scalar +INSTANTIATE_TEST_SUITE_P( + HitKindSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitKindKHR"), + Values("AnyHitKHR", "ClosestHitKHR"), Values("Input"), + Values("%u32"), Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + HitKindNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitKindKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "IntersectionKHR", + "MissKHR", "CallableKHR"), + Values("Input"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-HitKindKHR-HitKindKHR-04242"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + HitKindNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitKindKHR"), + Values("AnyHitKHR", "ClosestHitKHR"), Values("Output"), + Values("%u32"), Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-HitKindKHR-HitKindKHR-04243"), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); + +INSTANTIATE_TEST_SUITE_P( + HitKindNotIntScalar, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitKindKHR"), + Values("AnyHitKHR", "ClosestHitKHR"), Values("Input"), + Values("%f32", "%u32vec3"), Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-HitKindKHR-HitKindKHR-04244"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit int scalar", + "is not an int scalar")))); + +// Ensure HitT is not supported in KHR RT shaders +INSTANTIATE_TEST_SUITE_P( + HitTNVNotSupportedInKHR, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitTNV"), + Values("AnyHitKHR", "ClosestHitKHR"), Values("Input"), + Values("%u32"), Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult( + SPV_ERROR_INVALID_CAPABILITY, + "of MemberDecorate requires one of these capabilities")))); + +// HitT is valid in AH, CH shaders as input f32 scalar (NV RT only) +INSTANTIATE_TEST_SUITE_P( + HitTNVSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitTNV"), + Values("AnyHitNV", "ClosestHitNV"), Values("Input"), Values("%f32"), + Values("OpCapability RayTracingNV\n"), + Values("OpExtension \"SPV_NV_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + HitTNVNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitTNV"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationNV", "IntersectionNV", "MissNV", + "CallableNV"), + Values("Input"), Values("%f32"), + Values("OpCapability RayTracingNV\n"), + Values("OpExtension \"SPV_NV_ray_tracing\"\n"), + Values("VUID-HitTNV-HitTNV-04245"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + HitTNVNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitTNV"), + Values("AnyHitNV", "ClosestHitNV"), Values("Output"), + Values("%f32"), Values("OpCapability RayTracingNV\n"), + Values("OpExtension \"SPV_NV_ray_tracing\"\n"), + Values("VUID-HitTNV-HitTNV-04246"), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); +INSTANTIATE_TEST_SUITE_P( + HitTNVNotIntScalar, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("HitTNV"), + Values("AnyHitNV", "ClosestHitNV"), Values("Input"), + Values("%u32", "%f32vec3"), Values("OpCapability RayTracingNV\n"), + Values("OpExtension \"SPV_NV_ray_tracing\"\n"), + Values("VUID-HitTNV-HitTNV-04247"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit float scalar", + "is not a float scalar")))); + +// InstanceCustomIndexKHR, InstanceId, PrimitiveId, RayGeometryIndexKHR are +// valid in IS, AH, CH shaders as input i32 scalars +INSTANTIATE_TEST_SUITE_P( + RTBuiltIn3StageI32Success, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("InstanceCustomIndexKHR", "RayGeometryIndexKHR", + "InstanceId", "PrimitiveId"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + RTBuiltIn3StageI32NotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("InstanceCustomIndexKHR", "RayGeometryIndexKHR", + "InstanceId"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "MissKHR", "CallableKHR"), + Values("Input"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-InstanceCustomIndexKHR-InstanceCustomIndexKHR-04251 " + "VUID-RayGeometryIndexKHR-RayGeometryIndexKHR-04345 " + "VUID-InstanceId-InstanceId-04254 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + RTBuiltIn3StageI32NotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("InstanceCustomIndexKHR", "RayGeometryIndexKHR", + "InstanceId"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Output"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-InstanceCustomIndexKHR-InstanceCustomIndexKHR-04252 " + "VUID-RayGeometryIndexKHR-RayGeometryIndexKHR-04346 " + "VUID-InstanceId-InstanceId-04255 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); + +INSTANTIATE_TEST_SUITE_P( + RTBuiltIn3StageI32NotIntScalar, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("InstanceCustomIndexKHR", "RayGeometryIndexKHR", + "InstanceId"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%f32", "%u32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-InstanceCustomIndexKHR-InstanceCustomIndexKHR-04253 " + "VUID-RayGeometryIndexKHR-RayGeometryIndexKHR-04347 " + "VUID-InstanceId-InstanceId-04256 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit int scalar", + "is not an int scalar")))); + +// PrimitiveId needs special negative testing because it has non-RT uses +INSTANTIATE_TEST_SUITE_P( + PrimitiveIdRTNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("PrimitiveId"), + Values("RayGenerationKHR", "MissKHR", "CallableKHR"), + Values("Input"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-PrimitiveId-PrimitiveId-04330"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "to be used only with Fragment, TessellationControl, " + "TessellationEvaluation, Geometry, MeshNV, IntersectionKHR, " + "AnyHitKHR, and ClosestHitKHR execution models")))); + +INSTANTIATE_TEST_SUITE_P( + PrimitiveIdRTNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("PrimitiveId"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Output"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-PrimitiveId-PrimitiveId-04334"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Output storage class if execution model is ")))); + +INSTANTIATE_TEST_SUITE_P( + PrimitiveIdRTNotIntScalar, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("PrimitiveId"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%f32", "%u32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-PrimitiveId-PrimitiveId-04337"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit int scalar", + "is not an int scalar")))); + +// ObjectRayDirectionKHR and ObjectRayOriginKHR valid +// in IS, AH, CH shaders as input 32-bit float vec3 +INSTANTIATE_TEST_SUITE_P( + ObjectRayDirectionAndOriginSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectRayDirectionKHR", "ObjectRayOriginKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + ObjectRayDirectionAndOriginNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectRayDirectionKHR", "ObjectRayOriginKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "MissKHR", "CallableKHR"), + Values("Input"), Values("%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-ObjectRayDirectionKHR-ObjectRayDirectionKHR-04299 " + "VUID-ObjectRayOriginKHR-ObjectRayOriginKHR-04302 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + ObjectRayDirectionAndOriginNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectRayDirectionKHR", "ObjectRayOriginKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Output"), Values("%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-ObjectRayDirectionKHR-ObjectRayDirectionKHR-04300 " + "VUID-ObjectRayOriginKHR-ObjectRayOriginKHR-04303 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); + +INSTANTIATE_TEST_SUITE_P( + ObjectRayDirectionAndOriginNotFloatVec3, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine( + Values(SPV_ENV_VULKAN_1_2), + Values("ObjectRayDirectionKHR", "ObjectRayOriginKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%u32vec3", "%f32", "%f32vec2", "%f32vec4"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-ObjectRayDirectionKHR-ObjectRayDirectionKHR-04301 " + "VUID-ObjectRayOriginKHR-ObjectRayOriginKHR-04304 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 3-component 32-bit float vector")))); + +// ObjectToWorldKHR and WorldToObjectKHR valid +// in IS, AH, CH shaders as input mat4x3 +INSTANTIATE_TEST_SUITE_P( + RTObjectMatrixSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectToWorldKHR", "WorldToObjectKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%f32mat34"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + RTObjectMatrixNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectToWorldKHR", "WorldToObjectKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "MissKHR", "CallableKHR"), + Values("Input"), Values("%f32mat34"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-ObjectToWorldKHR-ObjectToWorldKHR-04305 " + "VUID-WorldToObjectKHR-WorldToObjectKHR-04434 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + RTObjectMatrixNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectToWorldKHR", "WorldToObjectKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Output"), Values("%f32mat34"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-ObjectToWorldKHR-ObjectToWorldKHR-04306 " + "VUID-WorldToObjectKHR-WorldToObjectKHR-04435 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); + +INSTANTIATE_TEST_SUITE_P( + RTObjectMatrixNotMat4x3, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("ObjectToWorldKHR", "WorldToObjectKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR"), + Values("Input"), Values("%f32mat43", "%f32mat44", "%f32vec4"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-ObjectToWorldKHR-ObjectToWorldKHR-04307 " + "VUID-WorldToObjectKHR-WorldToObjectKHR-04436 "), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "variable needs to be a matrix with " + "4 columns of 3-component vectors of 32-bit floats")))); + +// IncomingRayFlagsKHR is valid +// in IS, AH, CH, MS shaders as an input i32 scalar +INSTANTIATE_TEST_SUITE_P( + IncomingRayFlagsSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("IncomingRayFlagsKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Input"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + IncomingRayFlagsNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("IncomingRayFlagsKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "CallableKHR"), + Values("Input"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04248 " + "VUID-RayTmaxKHR-RayTmaxKHR-04348 " + "VUID-RayTminKHR-RayTminKHR-04351 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + IncomingRayFlagsNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("IncomingRayFlagsKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Output"), Values("%u32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04249 " + "VUID-RayTmaxKHR-RayTmaxKHR-04349 " + "VUID-RayTminKHR-RayTminKHR-04352 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); +INSTANTIATE_TEST_SUITE_P( + IncomingRayFlagsNotIntScalar, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("IncomingRayFlagsKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Input"), Values("%f32", "%u32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04250 " + "VUID-RayTmaxKHR-RayTmaxKHR-04350 " + "VUID-RayTminKHR-RayTminKHR-04353 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit int scalar", + "is not an int scalar")))); + +// RayTmaxKHR, RayTminKHR are all valid +// in IS, AH, CH, MS shaders as input f32 scalars +INSTANTIATE_TEST_SUITE_P( + RayTSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("RayTmaxKHR", "RayTminKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Input"), Values("%f32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + RayTNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("RayTmaxKHR", "RayTminKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "CallableKHR"), + Values("Input"), Values("%f32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04248 " + "VUID-RayTmaxKHR-RayTmaxKHR-04348 " + "VUID-RayTminKHR-RayTminKHR-04351 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + RayTNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("RayTmaxKHR", "RayTminKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Output"), Values("%f32"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04249 " + "VUID-RayTmaxKHR-RayTmaxKHR-04349 " + "VUID-RayTminKHR-RayTminKHR-04352 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); +INSTANTIATE_TEST_SUITE_P( + RayTNotFloatScalar, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("RayTmaxKHR", "RayTminKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Input"), Values("%u32", "%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-IncomingRayFlagsKHR-IncomingRayFlagsKHR-04250 " + "VUID-RayTmaxKHR-RayTmaxKHR-04350 " + "VUID-RayTminKHR-RayTminKHR-04353 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit float scalar", + "is not a float scalar")))); + +// WorldRayDirectionKHR and WorldRayOriginKHR are valid +// in IS, AH, CH, MS shaders as input 32-bit float vec3 +INSTANTIATE_TEST_SUITE_P( + WorldRayDirectionAndOriginSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("WorldRayDirectionKHR", "WorldRayOriginKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Input"), Values("%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + WorldRayDirectionAndOriginNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("WorldRayDirectionKHR", "WorldRayOriginKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute", "RayGenerationKHR", "CallableKHR"), + Values("Input"), Values("%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-WorldRayDirectionKHR-WorldRayDirectionKHR-04428 " + "VUID-WorldRayOriginKHR-WorldRayOriginKHR-04431 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + WorldRayDirectionAndOriginNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), + Values("WorldRayDirectionKHR", "WorldRayOriginKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Output"), Values("%f32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-WorldRayDirectionKHR-WorldRayDirectionKHR-04429 " + "VUID-WorldRayOriginKHR-WorldRayOriginKHR-04432 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); + +INSTANTIATE_TEST_SUITE_P( + WorldRayDirectionAndOriginNotFloatVec3, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine( + Values(SPV_ENV_VULKAN_1_2), + Values("WorldRayDirectionKHR", "WorldRayOriginKHR"), + Values("AnyHitKHR", "ClosestHitKHR", "IntersectionKHR", "MissKHR"), + Values("Input"), Values("%u32vec3", "%f32", "%f32vec2", "%f32vec4"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-WorldRayDirectionKHR-WorldRayDirectionKHR-04430 " + "VUID-WorldRayOriginKHR-WorldRayOriginKHR-04433 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 3-component 32-bit float vector")))); + +// LaunchIdKHR and LaunchSizeKHR are valid +// in RG, IS, AH, CH, MS shaders as input 32-bit ivec3 +INSTANTIATE_TEST_SUITE_P( + LaunchRTSuccess, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("LaunchIdKHR", "LaunchSizeKHR"), + Values("RayGenerationKHR", "AnyHitKHR", "ClosestHitKHR", + "IntersectionKHR", "MissKHR", "CallableKHR"), + Values("Input"), Values("%u32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), Values(nullptr), + Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + LaunchRTNotExecutionMode, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("LaunchIdKHR", "LaunchSizeKHR"), + Values("Vertex", "Fragment", "TessellationControl", + "TessellationEvaluation", "Geometry", "Fragment", + "GLCompute"), + Values("Input"), Values("%u32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-LaunchIdKHR-LaunchIdKHR-04266 " + "VUID-LaunchSizeKHR-LaunchSizeKHR-04269 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec does not allow BuiltIn", + "to be used with the execution model")))); + +INSTANTIATE_TEST_SUITE_P( + LaunchRTNotInput, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("LaunchIdKHR", "LaunchSizeKHR"), + Values("RayGenerationKHR", "AnyHitKHR", "ClosestHitKHR", + "IntersectionKHR", "MissKHR", "CallableKHR"), + Values("Output"), Values("%u32vec3"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-LaunchIdKHR-LaunchIdKHR-04267 " + "VUID-LaunchSizeKHR-LaunchSizeKHR-04270 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, "Vulkan spec allows", + "used for variables with Input storage class")))); + +INSTANTIATE_TEST_SUITE_P( + LaunchRTNotIntVec3, + ValidateGenericCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values(SPV_ENV_VULKAN_1_2), Values("LaunchIdKHR", "LaunchSizeKHR"), + Values("RayGenerationKHR", "AnyHitKHR", "ClosestHitKHR", + "IntersectionKHR", "MissKHR", "CallableKHR"), + Values("Input"), Values("%f32vec3", "%u32", "%u32vec2", "%u32vec4"), + Values("OpCapability RayTracingKHR\n"), + Values("OpExtension \"SPV_KHR_ray_tracing\"\n"), + Values("VUID-LaunchIdKHR-LaunchIdKHR-04268 " + "VUID-LaunchSizeKHR-LaunchSizeKHR-04271 "), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 3-component 32-bit int vector")))); + +CodeGenerator GetArrayedVariableCodeGenerator(const char* const built_in, const char* const execution_model, const char* const storage_class, const char* const data_type) { - CodeGenerator generator = - spvIsWebGPUEnv(env) ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = "OpDecorate %built_in_var BuiltIn "; generator.before_types_ += built_in; @@ -2377,14 +2555,14 @@ CodeGenerator GetArrayedVariableCodeGenerator(spv_target_env env, std::ostringstream after_types; after_types << "%built_in_array = OpTypeArray " << data_type << " %u32_3\n"; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << "%built_in_array_null = OpConstantNull %built_in_array\n"; } after_types << "%built_in_ptr = OpTypePointer " << storage_class << " %built_in_array\n"; after_types << "%built_in_var = OpVariable %built_in_ptr " << storage_class; - if (InitializerRequired(env, storage_class)) { + if (InitializerRequired(storage_class)) { after_types << " %built_in_array_null"; } after_types << "\n"; @@ -2433,7 +2611,7 @@ TEST_P(ValidateVulkanCombineBuiltInArrayedVariable, Variable) { const TestResult& test_result = std::get<4>(GetParam()); CodeGenerator generator = GetArrayedVariableCodeGenerator( - SPV_ENV_VULKAN_1_0, built_in, execution_model, storage_class, data_type); + built_in, execution_model, storage_class, data_type); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, @@ -2446,27 +2624,6 @@ TEST_P(ValidateVulkanCombineBuiltInArrayedVariable, Variable) { } } -TEST_P(ValidateWebGPUCombineBuiltInArrayedVariable, Variable) { - const char* const built_in = std::get<0>(GetParam()); - const char* const execution_model = std::get<1>(GetParam()); - const char* const storage_class = std::get<2>(GetParam()); - const char* const data_type = std::get<3>(GetParam()); - const TestResult& test_result = std::get<4>(GetParam()); - - CodeGenerator generator = GetArrayedVariableCodeGenerator( - SPV_ENV_WEBGPU_0, built_in, execution_model, storage_class, data_type); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(test_result.validation_result, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - if (test_result.error_str) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str)); - } - if (test_result.error_str2) { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str2)); - } -} - INSTANTIATE_TEST_SUITE_P(PointSizeArrayedF32TessControl, ValidateVulkanCombineBuiltInArrayedVariable, Combine(Values("PointSize"), @@ -2512,14 +2669,6 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 4-component 32-bit float vector", "is not a float vector")))); -INSTANTIATE_TEST_SUITE_P( - PositionArrayedF32Vec4Vertex, ValidateWebGPUCombineBuiltInArrayedVariable, - Combine(Values("Position"), Values("Vertex"), Values("Output"), - Values("%f32vec4"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 4-component 32-bit float vector", - "is not a float vector")))); - INSTANTIATE_TEST_SUITE_P( ClipAndCullDistanceOutputSuccess, ValidateVulkanCombineBuiltInArrayedVariable, @@ -2623,10 +2772,8 @@ INSTANTIATE_TEST_SUITE_P( "needs to be a 32-bit int scalar", "has bit width 64")))); -CodeGenerator GetWorkgroupSizeSuccessGenerator(spv_target_env env) { - CodeGenerator generator = - env == SPV_ENV_WEBGPU_0 ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetWorkgroupSizeSuccessGenerator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpDecorate %workgroup_size BuiltIn WorkgroupSize @@ -2648,22 +2795,13 @@ OpDecorate %workgroup_size BuiltIn WorkgroupSize } TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeSuccess) { - CodeGenerator generator = - GetWorkgroupSizeSuccessGenerator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetWorkgroupSizeSuccessGenerator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } -TEST_F(ValidateBuiltIns, WebGPUWorkgroupSizeSuccess) { - CodeGenerator generator = GetWorkgroupSizeSuccessGenerator(SPV_ENV_WEBGPU_0); - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -CodeGenerator GetWorkgroupSizeFragmentGenerator(spv_target_env env) { - CodeGenerator generator = - env == SPV_ENV_WEBGPU_0 ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetWorkgroupSizeFragmentGenerator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpDecorate %workgroup_size BuiltIn WorkgroupSize @@ -2686,8 +2824,7 @@ OpDecorate %workgroup_size BuiltIn WorkgroupSize } TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeFragment) { - CodeGenerator generator = - GetWorkgroupSizeFragmentGenerator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetWorkgroupSizeFragmentGenerator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); @@ -2703,20 +2840,6 @@ TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeFragment) { "VUID-WorkgroupSize-WorkgroupSize-04427")); } -TEST_F(ValidateBuiltIns, WebGPUWorkgroupSizeFragment) { - CodeGenerator generator = GetWorkgroupSizeFragmentGenerator(SPV_ENV_WEBGPU_0); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("WebGPU spec allows BuiltIn WorkgroupSize to be used " - "only with GLCompute execution model")); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("is referencing ID <2> (OpConstantComposite) which is " - "decorated with BuiltIn WorkgroupSize in function <1> " - "called with execution model Fragment")); -} - TEST_F(ValidateBuiltIns, WorkgroupSizeNotConstant) { CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( @@ -2742,10 +2865,8 @@ OpDecorate %copy BuiltIn WorkgroupSize HasSubstr("BuiltIns can only target variables, structs or constants")); } -CodeGenerator GetWorkgroupSizeNotVectorGenerator(spv_target_env env) { - CodeGenerator generator = - env == SPV_ENV_WEBGPU_0 ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetWorkgroupSizeNotVectorGenerator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpDecorate %workgroup_size BuiltIn WorkgroupSize @@ -2767,8 +2888,7 @@ OpDecorate %workgroup_size BuiltIn WorkgroupSize } TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeNotVector) { - CodeGenerator generator = - GetWorkgroupSizeNotVectorGenerator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetWorkgroupSizeNotVectorGenerator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); @@ -2780,22 +2900,8 @@ TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeNotVector) { AnyVUID("VUID-WorkgroupSize-WorkgroupSize-04427")); } -TEST_F(ValidateBuiltIns, WebGPUWorkgroupSizeNotVector) { - CodeGenerator generator = - GetWorkgroupSizeNotVectorGenerator(SPV_ENV_WEBGPU_0); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("According to the WebGPU spec BuiltIn WorkgroupSize " - "variable needs to be a 3-component 32-bit int vector. " - "ID <2> (OpConstant) is not an int vector.")); -} - -CodeGenerator GetWorkgroupSizeNotIntVectorGenerator(spv_target_env env) { - CodeGenerator generator = - env == SPV_ENV_WEBGPU_0 ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetWorkgroupSizeNotIntVectorGenerator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpDecorate %workgroup_size BuiltIn WorkgroupSize @@ -2817,8 +2923,7 @@ OpDecorate %workgroup_size BuiltIn WorkgroupSize } TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeNotIntVector) { - CodeGenerator generator = - GetWorkgroupSizeNotIntVectorGenerator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetWorkgroupSizeNotIntVectorGenerator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); @@ -2830,22 +2935,8 @@ TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeNotIntVector) { AnyVUID("VUID-WorkgroupSize-WorkgroupSize-04427")); } -TEST_F(ValidateBuiltIns, WebGPUWorkgroupSizeNotIntVector) { - CodeGenerator generator = - GetWorkgroupSizeNotIntVectorGenerator(SPV_ENV_WEBGPU_0); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("According to the WebGPU spec BuiltIn WorkgroupSize " - "variable needs to be a 3-component 32-bit int vector. " - "ID <2> (OpConstantComposite) is not an int vector.")); -} - -CodeGenerator GetWorkgroupSizeNotVec3Generator(spv_target_env env) { - CodeGenerator generator = - env == SPV_ENV_WEBGPU_0 ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetWorkgroupSizeNotVec3Generator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpDecorate %workgroup_size BuiltIn WorkgroupSize @@ -2867,8 +2958,7 @@ OpDecorate %workgroup_size BuiltIn WorkgroupSize } TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeNotVec3) { - CodeGenerator generator = - GetWorkgroupSizeNotVec3Generator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetWorkgroupSizeNotVec3Generator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); @@ -2880,17 +2970,6 @@ TEST_F(ValidateBuiltIns, VulkanWorkgroupSizeNotVec3) { AnyVUID("VUID-WorkgroupSize-WorkgroupSize-04427")); } -TEST_F(ValidateBuiltIns, WebGPUWorkgroupSizeNotVec3) { - CodeGenerator generator = GetWorkgroupSizeNotVec3Generator(SPV_ENV_WEBGPU_0); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("According to the WebGPU spec BuiltIn WorkgroupSize " - "variable needs to be a 3-component 32-bit int vector. " - "ID <2> (OpConstantComposite) has 2 components.")); -} - TEST_F(ValidateBuiltIns, WorkgroupSizeNotInt32Vec) { CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( @@ -3168,10 +3247,8 @@ OpFunctionEnd HasSubstr("called with execution model Fragment")); } -CodeGenerator GetNoDepthReplacingGenerator(spv_target_env env) { - CodeGenerator generator = - spvIsWebGPUEnv(env) ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetNoDepthReplacingGenerator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpMemberDecorate %output_type 0 BuiltIn FragDepth @@ -3204,17 +3281,13 @@ OpReturn OpFunctionEnd )"; - if (spvIsWebGPUEnv(env)) { - generator.after_types_ += function_body; - } else { generator.add_at_the_end_ = function_body; - } return generator; } TEST_F(ValidateBuiltIns, VulkanFragmentFragDepthNoDepthReplacing) { - CodeGenerator generator = GetNoDepthReplacingGenerator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetNoDepthReplacingGenerator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); @@ -3225,21 +3298,8 @@ TEST_F(ValidateBuiltIns, VulkanFragmentFragDepthNoDepthReplacing) { HasSubstr("VUID-FragDepth-FragDepth-04216")); } -TEST_F(ValidateBuiltIns, WebGPUFragmentFragDepthNoDepthReplacing) { - CodeGenerator generator = GetNoDepthReplacingGenerator(SPV_ENV_WEBGPU_0); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("WebGPU spec requires DepthReplacing execution mode to " - "be declared when using BuiltIn FragDepth")); -} - -CodeGenerator GetOneMainHasDepthReplacingOtherHasntGenerator( - spv_target_env env) { - CodeGenerator generator = - spvIsWebGPUEnv(env) ? CodeGenerator::GetWebGPUShaderCodeGenerator() - : CodeGenerator::GetDefaultShaderCodeGenerator(); +CodeGenerator GetOneMainHasDepthReplacingOtherHasntGenerator() { + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = R"( OpMemberDecorate %output_type 0 BuiltIn FragDepth @@ -3283,19 +3343,14 @@ OpReturn OpFunctionEnd )"; - if (spvIsWebGPUEnv(env)) { - generator.after_types_ += function_body; - } else { generator.add_at_the_end_ = function_body; - } return generator; } TEST_F(ValidateBuiltIns, VulkanFragmentFragDepthOneMainHasDepthReplacingOtherHasnt) { - CodeGenerator generator = - GetOneMainHasDepthReplacingOtherHasntGenerator(SPV_ENV_VULKAN_1_0); + CodeGenerator generator = GetOneMainHasDepthReplacingOtherHasntGenerator(); CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); @@ -3306,17 +3361,6 @@ TEST_F(ValidateBuiltIns, HasSubstr("VUID-FragDepth-FragDepth-04216")); } -TEST_F(ValidateBuiltIns, - WebGPUFragmentFragDepthOneMainHasDepthReplacingOtherHasnt) { - CodeGenerator generator = - GetOneMainHasDepthReplacingOtherHasntGenerator(SPV_ENV_WEBGPU_0); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("WebGPU spec requires DepthReplacing execution mode to " - "be declared when using BuiltIn FragDepth")); -} TEST_F(ValidateBuiltIns, AllowInstanceIdWithIntersectionShader) { CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); @@ -3358,44 +3402,6 @@ OpFunctionEnd EXPECT_THAT(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } -TEST_F(ValidateBuiltIns, DisallowInstanceIdWithRayGenShader) { - CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); - generator.capabilities_ += R"( -OpCapability RayTracingNV -)"; - - generator.extensions_ = R"( -OpExtension "SPV_NV_ray_tracing" -)"; - - generator.before_types_ = R"( -OpMemberDecorate %input_type 0 BuiltIn InstanceId -)"; - - generator.after_types_ = R"( -%input_type = OpTypeStruct %u32 -%input_ptr = OpTypePointer Input %input_type -%input_ptr_u32 = OpTypePointer Input %u32 -%input = OpVariable %input_ptr Input -)"; - - EntryPoint entry_point; - entry_point.name = "main_d_r"; - entry_point.execution_model = "RayGenerationNV"; - entry_point.interfaces = "%input"; - entry_point.body = R"( -%input_member = OpAccessChain %input_ptr_u32 %input %u32_0 -)"; - generator.entry_points_.push_back(std::move(entry_point)); - - CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Vulkan spec allows BuiltIn InstanceId to be used " - "only with IntersectionNV, ClosestHitNV and " - "AnyHitNV execution models")); -} - TEST_F(ValidateBuiltIns, ValidBuiltinsForMeshShader) { CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.capabilities_ += R"( @@ -3509,7 +3515,8 @@ TEST_P(ValidateVulkanSubgroupBuiltIns, InMain) { const char* const execution_model = std::get<1>(GetParam()); const char* const storage_class = std::get<2>(GetParam()); const char* const data_type = std::get<3>(GetParam()); - const TestResult& test_result = std::get<4>(GetParam()); + const char* const vuid = std::get<4>(GetParam()); + const TestResult& test_result = std::get<5>(GetParam()); CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.capabilities_ += R"( @@ -3569,6 +3576,9 @@ OpCapability GroupNonUniformBallot if (test_result.error_str2) { EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str2)); } + if (vuid) { + EXPECT_THAT(getDiagnosticString(), AnyVUID(vuid)); + } } INSTANTIATE_TEST_SUITE_P( @@ -3576,6 +3586,11 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("SubgroupEqMask", "SubgroupGeMask", "SubgroupGtMask", "SubgroupLeMask", "SubgroupLtMask"), Values("GLCompute"), Values("Input"), Values("%u32vec3"), + Values("VUID-SubgroupEqMask-SubgroupEqMask-04371 " + "VUID-SubgroupGeMask-SubgroupGeMask-04373 " + "VUID-SubgroupGtMask-SubgroupGtMask-04375 " + "VUID-SubgroupLeMask-SubgroupLeMask-04377 " + "VUID-SubgroupLtMask-SubgroupLtMask-04379"), Values(TestResult(SPV_ERROR_INVALID_DATA, "needs to be a 4-component 32-bit int vector")))); @@ -3584,6 +3599,11 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("SubgroupEqMask", "SubgroupGeMask", "SubgroupGtMask", "SubgroupLeMask", "SubgroupLtMask"), Values("GLCompute"), Values("Input"), Values("%f32vec4"), + Values("VUID-SubgroupEqMask-SubgroupEqMask-04371 " + "VUID-SubgroupGeMask-SubgroupGeMask-04373 " + "VUID-SubgroupGtMask-SubgroupGtMask-04375 " + "VUID-SubgroupLeMask-SubgroupLeMask-04377 " + "VUID-SubgroupLtMask-SubgroupLtMask-04379"), Values(TestResult(SPV_ERROR_INVALID_DATA, "needs to be a 4-component 32-bit int vector")))); @@ -3593,6 +3613,11 @@ INSTANTIATE_TEST_SUITE_P( "SubgroupLeMask", "SubgroupLtMask"), Values("GLCompute"), Values("Output", "Workgroup", "Private"), Values("%u32vec4"), + Values("VUID-SubgroupEqMask-SubgroupEqMask-04370 " + "VUID-SubgroupGeMask-SubgroupGeMask-04372 " + "VUID-SubgroupGtMask-SubgroupGtMask-04374 " + "VUID-SubgroupLeMask-SubgroupLeMask-04376 " + "VUID-SubgroupLtMask-SubgroupLtMask-04378"), Values(TestResult( SPV_ERROR_INVALID_DATA, "to be only used for variables with Input storage class")))); @@ -3602,7 +3627,7 @@ INSTANTIATE_TEST_SUITE_P(SubgroupMaskOk, ValidateVulkanSubgroupBuiltIns, "SubgroupGtMask", "SubgroupLeMask", "SubgroupLtMask"), Values("GLCompute"), Values("Input"), - Values("%u32vec4"), + Values("%u32vec4"), Values(nullptr), Values(TestResult(SPV_SUCCESS, "")))); TEST_F(ValidateBuiltIns, SubgroupMaskMemberDecorate) { @@ -3633,25 +3658,31 @@ OpFunctionEnd INSTANTIATE_TEST_SUITE_P( SubgroupInvocationIdAndSizeNotU32, ValidateVulkanSubgroupBuiltIns, - Combine(Values("SubgroupLocalInvocationId", "SubgroupSize"), - Values("GLCompute"), Values("Input"), Values("%f32"), - Values(TestResult(SPV_ERROR_INVALID_DATA, - "needs to be a 32-bit int")))); + Combine( + Values("SubgroupLocalInvocationId", "SubgroupSize"), + Values("GLCompute"), Values("Input"), Values("%f32"), + Values("VUID-SubgroupLocalInvocationId-SubgroupLocalInvocationId-04381 " + "VUID-SubgroupSize-SubgroupSize-04383"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "needs to be a 32-bit int")))); INSTANTIATE_TEST_SUITE_P( SubgroupInvocationIdAndSizeNotInput, ValidateVulkanSubgroupBuiltIns, - Combine(Values("SubgroupLocalInvocationId", "SubgroupSize"), - Values("GLCompute"), Values("Output", "Workgroup", "Private"), - Values("%u32"), - Values(TestResult( - SPV_ERROR_INVALID_DATA, - "to be only used for variables with Input storage class")))); + Combine( + Values("SubgroupLocalInvocationId", "SubgroupSize"), + Values("GLCompute"), Values("Output", "Workgroup", "Private"), + Values("%u32"), + Values("VUID-SubgroupLocalInvocationId-SubgroupLocalInvocationId-04380 " + "VUID-SubgroupSize-SubgroupSize-04382"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "to be only used for variables with Input storage class")))); INSTANTIATE_TEST_SUITE_P( SubgroupInvocationIdAndSizeOk, ValidateVulkanSubgroupBuiltIns, Combine(Values("SubgroupLocalInvocationId", "SubgroupSize"), Values("GLCompute"), Values("Input"), Values("%u32"), - Values(TestResult(SPV_SUCCESS, "")))); + Values(nullptr), Values(TestResult(SPV_SUCCESS, "")))); TEST_F(ValidateBuiltIns, SubgroupSizeMemberDecorate) { const std::string text = R"( @@ -3678,10 +3709,22 @@ OpFunctionEnd HasSubstr("BuiltIn SubgroupSize cannot be used as a member decoration")); } +INSTANTIATE_TEST_SUITE_P( + SubgroupNumAndIdNotCompute, ValidateVulkanSubgroupBuiltIns, + Combine( + Values("SubgroupId", "NumSubgroups"), Values("Vertex"), Values("Input"), + Values("%u32"), + Values("VUID-SubgroupId-SubgroupId-04367 " + "VUID-NumSubgroups-NumSubgroups-04293"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "to be used only with GLCompute execution model")))); + INSTANTIATE_TEST_SUITE_P( SubgroupNumAndIdNotU32, ValidateVulkanSubgroupBuiltIns, Combine(Values("SubgroupId", "NumSubgroups"), Values("GLCompute"), Values("Input"), Values("%f32"), + Values("VUID-SubgroupId-SubgroupId-04369 " + "VUID-NumSubgroups-NumSubgroups-04295"), Values(TestResult(SPV_ERROR_INVALID_DATA, "needs to be a 32-bit int")))); @@ -3689,6 +3732,8 @@ INSTANTIATE_TEST_SUITE_P( SubgroupNumAndIdNotInput, ValidateVulkanSubgroupBuiltIns, Combine(Values("SubgroupId", "NumSubgroups"), Values("GLCompute"), Values("Output", "Workgroup", "Private"), Values("%u32"), + Values("VUID-SubgroupId-SubgroupId-04368 " + "VUID-NumSubgroups-NumSubgroups-04294"), Values(TestResult( SPV_ERROR_INVALID_DATA, "to be only used for variables with Input storage class")))); @@ -3696,7 +3741,7 @@ INSTANTIATE_TEST_SUITE_P( INSTANTIATE_TEST_SUITE_P(SubgroupNumAndIdOk, ValidateVulkanSubgroupBuiltIns, Combine(Values("SubgroupId", "NumSubgroups"), Values("GLCompute"), Values("Input"), - Values("%u32"), + Values("%u32"), Values(nullptr), Values(TestResult(SPV_SUCCESS, "")))); TEST_F(ValidateBuiltIns, SubgroupIdMemberDecorate) { @@ -3898,6 +3943,184 @@ INSTANTIATE_TEST_SUITE_P( Values(TestResult(SPV_ERROR_INVALID_DATA, "According to the Vulkan spec BuiltIn ShadingRateKHR " "variable needs to be a 32-bit int scalar.")))); + +INSTANTIATE_TEST_SUITE_P( + FragInvocationCountInputSuccess, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragInvocationCountEXT"), Values("Fragment"), + Values("Input"), Values("%u32"), + Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values(nullptr), Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + FragInvocationCountInvalidExecutionModel, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine( + Values("FragInvocationCountEXT"), Values("Vertex"), Values("Input"), + Values("%u32"), Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values("VUID-FragInvocationCountEXT-FragInvocationCountEXT-04217"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FragInvocationCountEXT " + "to be used only with Fragment execution model.")))); + +INSTANTIATE_TEST_SUITE_P( + FragInvocationCountInvalidStorageClass, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragInvocationCountEXT"), Values("Fragment"), + Values("Output"), Values("%u32"), + Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values("VUID-FragInvocationCountEXT-FragInvocationCountEXT-04218"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FragInvocationCountEXT to be only " + "used for variables with Input storage class.")))); + +INSTANTIATE_TEST_SUITE_P( + FragInvocationCountInvalidType, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragInvocationCountEXT"), Values("Fragment"), + Values("Input"), Values("%f32"), + Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values("VUID-FragInvocationCountEXT-FragInvocationCountEXT-04219"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "According to the Vulkan spec BuiltIn FragInvocationCountEXT " + "variable needs to be a 32-bit int scalar.")))); + +INSTANTIATE_TEST_SUITE_P( + FragSizeInputSuccess, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragSizeEXT"), Values("Fragment"), Values("Input"), + Values("%u32vec2"), Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values(nullptr), Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + FragSizeInvalidExecutionModel, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragSizeEXT"), Values("Vertex"), Values("Input"), + Values("%u32vec2"), Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values("VUID-FragSizeEXT-FragSizeEXT-04220"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FragSizeEXT to be " + "used only with Fragment execution model.")))); + +INSTANTIATE_TEST_SUITE_P( + FragSizeInvalidStorageClass, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine( + Values("FragSizeEXT"), Values("Fragment"), Values("Output"), + Values("%u32vec2"), Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values("VUID-FragSizeEXT-FragSizeEXT-04221"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FragSizeEXT to be only " + "used for variables with Input storage class.")))); + +INSTANTIATE_TEST_SUITE_P( + FragSizeInvalidType, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragSizeEXT"), Values("Fragment"), Values("Input"), + Values("%u32vec3"), Values("OpCapability FragmentDensityEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_invocation_density\"\n"), + Values("VUID-FragSizeEXT-FragSizeEXT-04222"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "According to the Vulkan spec BuiltIn FragSizeEXT variable " + "needs to be a 2-component 32-bit int vector.")))); + +INSTANTIATE_TEST_SUITE_P( + FragStencilRefOutputSuccess, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragStencilRefEXT"), Values("Fragment"), Values("Output"), + Values("%u32", "%u64"), Values("OpCapability StencilExportEXT\n"), + Values("OpExtension \"SPV_EXT_shader_stencil_export\"\n"), + Values(nullptr), Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + FragStencilRefInvalidExecutionModel, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragStencilRefEXT"), Values("Vertex"), Values("Output"), + Values("%u32", "%u64"), Values("OpCapability StencilExportEXT\n"), + Values("OpExtension \"SPV_EXT_shader_stencil_export\"\n"), + Values("VUID-FragStencilRefEXT-FragStencilRefEXT-04223"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FragStencilRefEXT to " + "be used only with Fragment execution model.")))); + +INSTANTIATE_TEST_SUITE_P( + FragStencilRefInvalidStorageClass, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragStencilRefEXT"), Values("Fragment"), Values("Input"), + Values("%u32", "%u64"), Values("OpCapability StencilExportEXT\n"), + Values("OpExtension \"SPV_EXT_shader_stencil_export\"\n"), + Values("VUID-FragStencilRefEXT-FragStencilRefEXT-04224"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FragStencilRefEXT to be only used " + "for variables with Output storage class.")))); + +INSTANTIATE_TEST_SUITE_P( + FragStencilRefInvalidType, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FragStencilRefEXT"), Values("Fragment"), Values("Output"), + Values("%f32", "%f64", "%u32vec2"), + Values("OpCapability StencilExportEXT\n"), + Values("OpExtension \"SPV_EXT_shader_stencil_export\"\n"), + Values("VUID-FragStencilRefEXT-FragStencilRefEXT-04225"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "According to the Vulkan spec BuiltIn FragStencilRefEXT " + "variable needs to be a int scalar.")))); + +INSTANTIATE_TEST_SUITE_P( + FullyCoveredEXTInputSuccess, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FullyCoveredEXT"), Values("Fragment"), Values("Input"), + Values("%bool"), Values("OpCapability FragmentFullyCoveredEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_fully_covered\"\n"), + Values(nullptr), Values(TestResult()))); + +INSTANTIATE_TEST_SUITE_P( + FullyCoveredEXTInvalidExecutionModel, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FullyCoveredEXT"), Values("Vertex"), Values("Input"), + Values("%bool"), Values("OpCapability FragmentFullyCoveredEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_fully_covered\"\n"), + Values("VUID-FullyCoveredEXT-FullyCoveredEXT-04232"), + Values(TestResult(SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FullyCoveredEXT to " + "be used only with Fragment execution model.")))); + +INSTANTIATE_TEST_SUITE_P( + FullyCoveredEXTInvalidStorageClass, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FullyCoveredEXT"), Values("Fragment"), Values("Output"), + Values("%bool"), Values("OpCapability FragmentFullyCoveredEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_fully_covered\"\n"), + Values("VUID-FullyCoveredEXT-FullyCoveredEXT-04233"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "Vulkan spec allows BuiltIn FullyCoveredEXT to be only used " + "for variables with Input storage class.")))); + +INSTANTIATE_TEST_SUITE_P( + FullyCoveredEXTInvalidType, + ValidateVulkanCombineBuiltInExecutionModelDataTypeCapabilityExtensionResult, + Combine(Values("FullyCoveredEXT"), Values("Fragment"), Values("Input"), + Values("%f32"), Values("OpCapability FragmentFullyCoveredEXT\n"), + Values("OpExtension \"SPV_EXT_fragment_fully_covered\"\n"), + Values("VUID-FullyCoveredEXT-FullyCoveredEXT-04234"), + Values(TestResult( + SPV_ERROR_INVALID_DATA, + "According to the Vulkan spec BuiltIn FullyCoveredEXT variable " + "needs to be a bool scalar.")))); + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_capability_test.cpp b/third_party/spirv-tools/test/val/val_capability_test.cpp index 9705cb8f89..82f8d38196 100644 --- a/third_party/spirv-tools/test/val/val_capability_test.cpp +++ b/third_party/spirv-tools/test/val/val_capability_test.cpp @@ -116,8 +116,6 @@ using ValidateCapabilityOpenGL40 = spvtest::ValidateBase; using ValidateCapabilityVulkan11 = spvtest::ValidateBase; // Always assembles using Vulkan 1.2. using ValidateCapabilityVulkan12 = spvtest::ValidateBase; -// Always assembles using WebGPU. -using ValidateCapabilityWebGPU = spvtest::ValidateBase; TEST_F(ValidateCapability, Default) { const char str[] = R"( @@ -588,18 +586,6 @@ const std::vector& AllVulkan12Capabilities() { return *r; } -const std::vector& AllWebGPUCapabilities() { - static const auto r = new std::vector{ - "", - "Shader", - "Matrix", - "Sampled1D", - "Image1D", - "ImageQuery", - "DerivativeControl"}; - return *r; -} - const std::vector& MatrixDependencies() { static const auto r = new std::vector{ "Matrix", @@ -790,12 +776,6 @@ const char kGLSL450MemoryModel[] = \ " OpCapability Shader" " OpMemoryModel Logical GLSL450 "; -const char kVulkanMemoryModel[] = \ - " OpCapability Shader" - " OpCapability VulkanMemoryModelKHR" - " OpExtension \"SPV_KHR_vulkan_memory_model\"" - " OpMemoryModel Logical VulkanKHR "; - const char kVoidFVoid[] = \ " %void = OpTypeVoid" " %void_f = OpTypeFunction %void" @@ -1814,16 +1794,6 @@ std::make_pair(std::string(kGLSL450MemoryModel) + AllSpirV10Capabilities()) ))); -INSTANTIATE_TEST_SUITE_P(Capabilities, ValidateCapabilityWebGPU, - Combine( - // All capabilities to try. - ValuesIn(AllCapabilities()), - Values( -std::make_pair(std::string(kVulkanMemoryModel) + - "OpEntryPoint Vertex %func \"shader\" \n" + std::string(kVoidFVoid), - AllWebGPUCapabilities()) -))); - INSTANTIATE_TEST_SUITE_P(Capabilities, ValidateCapabilityVulkan11, Combine( // All capabilities to try. @@ -2047,17 +2017,6 @@ TEST_P(ValidateCapabilityOpenGL40, Capability) { } } -TEST_P(ValidateCapabilityWebGPU, Capability) { - const std::string capability = Capability(GetParam()); - if (Exists(capability, SPV_ENV_WEBGPU_0)) { - const std::string test_code = MakeAssembly(GetParam()); - CompileSuccessfully(test_code, SPV_ENV_WEBGPU_0); - ASSERT_EQ(ExpectedResult(GetParam()), - ValidateInstructions(SPV_ENV_WEBGPU_0)) - << test_code; - } -} - TEST_F(ValidateCapability, SemanticsIdIsAnIdNotALiteral) { // From https://github.com/KhronosGroup/SPIRV-Tools/issues/248 // The validator was interpreting the memory semantics ID number diff --git a/third_party/spirv-tools/test/val/val_cfg_test.cpp b/third_party/spirv-tools/test/val/val_cfg_test.cpp index b4d1c2897c..6ae2ee6db9 100644 --- a/third_party/spirv-tools/test/val/val_cfg_test.cpp +++ b/third_party/spirv-tools/test/val/val_cfg_test.cpp @@ -168,15 +168,6 @@ const std::string& GetDefaultHeader(SpvCapability cap) { return (cap == SpvCapabilityShader) ? shader_header : kernel_header; } -const std::string& GetWebGPUHeader() { - static const std::string header = - "OpCapability Shader\n" - "OpCapability VulkanMemoryModelKHR\n" - "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" - "OpMemoryModel Logical VulkanKHR\n"; - return header; -} - const std::string& types_consts() { static const std::string types = "%voidt = OpTypeVoid\n" @@ -496,10 +487,10 @@ TEST_P(ValidateCFG, BranchTargetFirstBlockBadSinceEntryBlock) { TEST_P(ValidateCFG, BranchTargetFirstBlockBadSinceValue) { Block entry("entry"); - entry.SetBody("%undef = OpUndef %voidt\n"); + entry.SetBody("%undef = OpUndef %boolt\n"); Block bad("bad"); Block end("end", SpvOpReturn); - Block badvalue("undef"); // This referenes the OpUndef. + Block badvalue("undef"); // This references the OpUndef. std::string str = GetDefaultHeader(GetParam()) + nameOps("entry", "bad", std::make_pair("func", "Main")) + types_consts() + @@ -714,10 +705,8 @@ TEST_P(ValidateCFG, HeaderDoesntStrictlyDominateMergeBad) { } } -std::string GetUnreachableMergeNoMergeInst(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeNoMergeInst(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranchConditional); Block t("t", SpvOpReturn); @@ -725,17 +714,11 @@ std::string GetUnreachableMergeNoMergeInst(SpvCapability cap, Block merge("merge", SpvOpReturn); entry.SetBody("%cond = OpSLessThan %boolt %one %two\n"); - if (!spvIsWebGPUEnv(env) && cap == SpvCapabilityShader) + if (cap == SpvCapabilityShader) branch.AppendBody("OpSelectionMerge %merge None\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", std::make_pair("func", "Main")); str += types_consts() + "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; str += branch >> std::vector({t, f}); @@ -748,23 +731,12 @@ std::string GetUnreachableMergeNoMergeInst(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeNoMergeInst) { - CompileSuccessfully( - GetUnreachableMergeNoMergeInst(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableMergeNoMergeInst(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableMergeNoMergeInst) { - CompileSuccessfully( - GetUnreachableMergeNoMergeInst(SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, all blocks must be reachable")); -} - -std::string GetUnreachableMergeTerminatedBy(SpvCapability cap, - spv_target_env env, SpvOp op) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeTerminatedBy(SpvCapability cap, SpvOp op) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranchConditional); @@ -774,16 +746,10 @@ std::string GetUnreachableMergeTerminatedBy(SpvCapability cap, entry.SetBody("%cond = OpSLessThan %boolt %one %two\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpSelectionMerge %merge None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; @@ -797,49 +763,24 @@ std::string GetUnreachableMergeTerminatedBy(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeTerminatedByOpUnreachable) { - CompileSuccessfully(GetUnreachableMergeTerminatedBy( - GetParam(), SPV_ENV_UNIVERSAL_1_0, SpvOpUnreachable)); + CompileSuccessfully( + GetUnreachableMergeTerminatedBy(GetParam(), SpvOpUnreachable)); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidateCFG, UnreachableMergeTerminatedByOpKill) { - CompileSuccessfully(GetUnreachableMergeTerminatedBy( - SpvCapabilityShader, SPV_ENV_UNIVERSAL_1_0, SpvOpKill)); + CompileSuccessfully( + GetUnreachableMergeTerminatedBy(SpvCapabilityShader, SpvOpKill)); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_P(ValidateCFG, UnreachableMergeTerminatedByOpReturn) { - CompileSuccessfully(GetUnreachableMergeTerminatedBy( - GetParam(), SPV_ENV_UNIVERSAL_1_0, SpvOpReturn)); + CompileSuccessfully(GetUnreachableMergeTerminatedBy(GetParam(), SpvOpReturn)); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableMergeTerminatedByOpUnreachable) { - CompileSuccessfully(GetUnreachableMergeTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpUnreachable)); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateCFG, WebGPUUnreachableMergeTerminatedByOpKill) { - CompileSuccessfully(GetUnreachableMergeTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpKill)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("must terminate with OpUnreachable")); -} - -TEST_P(ValidateCFG, WebGPUUnreachableMergeTerminatedByOpReturn) { - CompileSuccessfully(GetUnreachableMergeTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpReturn)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("must terminate with OpUnreachable")); -} - -std::string GetUnreachableContinueTerminatedBy(SpvCapability cap, - spv_target_env env, SpvOp op) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableContinueTerminatedBy(SpvCapability cap, SpvOp op) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranch); @@ -849,16 +790,10 @@ std::string GetUnreachableContinueTerminatedBy(SpvCapability cap, if (op == SpvOpBranch) target >> branch; std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpLoopMerge %merge %target None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; @@ -871,8 +806,8 @@ std::string GetUnreachableContinueTerminatedBy(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableContinueTerminatedBySpvOpUnreachable) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - GetParam(), SPV_ENV_UNIVERSAL_1_0, SpvOpUnreachable)); + CompileSuccessfully( + GetUnreachableContinueTerminatedBy(GetParam(), SpvOpUnreachable)); if (GetParam() == SpvCapabilityShader) { ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), @@ -883,16 +818,16 @@ TEST_P(ValidateCFG, UnreachableContinueTerminatedBySpvOpUnreachable) { } TEST_F(ValidateCFG, UnreachableContinueTerminatedBySpvOpKill) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - SpvCapabilityShader, SPV_ENV_UNIVERSAL_1_0, SpvOpKill)); + CompileSuccessfully( + GetUnreachableContinueTerminatedBy(SpvCapabilityShader, SpvOpKill)); ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("targeted by 0 back-edge blocks")); } TEST_P(ValidateCFG, UnreachableContinueTerminatedBySpvOpReturn) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - GetParam(), SPV_ENV_UNIVERSAL_1_0, SpvOpReturn)); + CompileSuccessfully( + GetUnreachableContinueTerminatedBy(GetParam(), SpvOpReturn)); if (GetParam() == SpvCapabilityShader) { ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), @@ -903,48 +838,13 @@ TEST_P(ValidateCFG, UnreachableContinueTerminatedBySpvOpReturn) { } TEST_P(ValidateCFG, UnreachableContinueTerminatedBySpvOpBranch) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - GetParam(), SPV_ENV_UNIVERSAL_1_0, SpvOpBranch)); + CompileSuccessfully( + GetUnreachableContinueTerminatedBy(GetParam(), SpvOpBranch)); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableContinueTerminatedBySpvOpUnreachable) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpUnreachable)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, unreachable continue-target must " - "terminate with OpBranch.\n %12 = OpLabel\n")); -} - -TEST_F(ValidateCFG, WebGPUUnreachableContinueTerminatedBySpvOpKill) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpKill)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, unreachable continue-target must " - "terminate with OpBranch.\n %12 = OpLabel\n")); -} - -TEST_F(ValidateCFG, WebGPUUnreachableContinueTerminatedBySpvOpReturn) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpReturn)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, unreachable continue-target must " - "terminate with OpBranch.\n %12 = OpLabel\n")); -} - -TEST_F(ValidateCFG, WebGPUUnreachableContinueTerminatedBySpvOpBranch) { - CompileSuccessfully(GetUnreachableContinueTerminatedBy( - SpvCapabilityShader, SPV_ENV_WEBGPU_0, SpvOpBranch)); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -std::string GetUnreachableMergeUnreachableMergeInst(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeUnreachableMergeInst(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block body("body", SpvOpReturn); Block entry("entry"); @@ -955,16 +855,10 @@ std::string GetUnreachableMergeUnreachableMergeInst(SpvCapability cap, entry.SetBody("%cond = OpSLessThan %boolt %one %two\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpSelectionMerge %merge None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += body; @@ -979,23 +873,12 @@ std::string GetUnreachableMergeUnreachableMergeInst(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeUnreachableMergeInst) { - CompileSuccessfully(GetUnreachableMergeUnreachableMergeInst( - GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableMergeUnreachableMergeInst(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableMergeUnreachableMergeInst) { - CompileSuccessfully(GetUnreachableMergeUnreachableMergeInst( - SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("must be referenced by a reachable merge instruction")); -} - -std::string GetUnreachableContinueUnreachableLoopInst(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableContinueUnreachableLoopInst(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block body("body", SpvOpReturn); Block entry("entry"); @@ -1006,16 +889,10 @@ std::string GetUnreachableContinueUnreachableLoopInst(SpvCapability cap, target >> branch; std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpLoopMerge %merge %target None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += body; @@ -1029,8 +906,7 @@ std::string GetUnreachableContinueUnreachableLoopInst(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableContinueUnreachableLoopInst) { - CompileSuccessfully(GetUnreachableContinueUnreachableLoopInst( - GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableContinueUnreachableLoopInst(GetParam())); if (GetParam() == SpvCapabilityShader) { // Shader causes additional structured CFG checks that cause a failure. ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); @@ -1043,18 +919,8 @@ TEST_P(ValidateCFG, UnreachableContinueUnreachableLoopInst) { } } -TEST_F(ValidateCFG, WebGPUUnreachableContinueUnreachableLoopInst) { - CompileSuccessfully(GetUnreachableContinueUnreachableLoopInst( - SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("must be referenced by a reachable loop instruction")); -} - -std::string GetUnreachableMergeWithComplexBody(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeWithComplexBody(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranchConditional); @@ -1062,23 +928,15 @@ std::string GetUnreachableMergeWithComplexBody(SpvCapability cap, Block f("f", SpvOpReturn); Block merge("merge", SpvOpUnreachable); - entry.AppendBody(spvIsWebGPUEnv(env) - ? "%placeholder = OpVariable %intptrt Function %two\n" - : "%placeholder = OpVariable %intptrt Function\n"); + entry.AppendBody("%placeholder = OpVariable %intptrt Function\n"); entry.AppendBody("%cond = OpSLessThan %boolt %one %two\n"); merge.AppendBody("OpStore %placeholder %one\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpSelectionMerge %merge None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", std::make_pair("func", "Main")); str += types_consts(); str += "%intptrt = OpTypePointer Function %intt\n"; str += "%func = OpFunction %voidt None %funct\n"; @@ -1093,24 +951,12 @@ std::string GetUnreachableMergeWithComplexBody(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeWithComplexBody) { - CompileSuccessfully( - GetUnreachableMergeWithComplexBody(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableMergeWithComplexBody(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableMergeWithComplexBody) { - CompileSuccessfully(GetUnreachableMergeWithComplexBody(SpvCapabilityShader, - SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("must only contain an OpLabel and OpUnreachable instruction")); -} - -std::string GetUnreachableContinueWithComplexBody(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableContinueWithComplexBody(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranch); @@ -1119,22 +965,14 @@ std::string GetUnreachableContinueWithComplexBody(SpvCapability cap, target >> branch; - entry.AppendBody(spvIsWebGPUEnv(env) - ? "%placeholder = OpVariable %intptrt Function %two\n" - : "%placeholder = OpVariable %intptrt Function\n"); + entry.AppendBody("%placeholder = OpVariable %intptrt Function\n"); target.AppendBody("OpStore %placeholder %one\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpLoopMerge %merge %target None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); str += types_consts(); str += "%intptrt = OpTypePointer Function %intt\n"; str += "%func = OpFunction %voidt None %funct\n"; @@ -1148,24 +986,12 @@ std::string GetUnreachableContinueWithComplexBody(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableContinueWithComplexBody) { - CompileSuccessfully( - GetUnreachableContinueWithComplexBody(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableContinueWithComplexBody(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableContinueWithComplexBody) { - CompileSuccessfully(GetUnreachableContinueWithComplexBody(SpvCapabilityShader, - SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("must only contain an OpLabel and an OpBranch instruction")); -} - -std::string GetUnreachableMergeWithBranchUse(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeWithBranchUse(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranchConditional); @@ -1176,16 +1002,10 @@ std::string GetUnreachableMergeWithBranchUse(SpvCapability cap, entry.AppendBody("%cond = OpSLessThan %boolt %one %two\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpSelectionMerge %merge None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; @@ -1199,15 +1019,12 @@ std::string GetUnreachableMergeWithBranchUse(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeWithBranchUse) { - CompileSuccessfully( - GetUnreachableMergeWithBranchUse(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableMergeWithBranchUse(GetParam())); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } -std::string GetUnreachableMergeWithMultipleUses(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeWithMultipleUses(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranchConditional); @@ -1219,18 +1036,12 @@ std::string GetUnreachableMergeWithMultipleUses(SpvCapability cap, entry.AppendBody("%cond = OpSLessThan %boolt %one %two\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) { branch.AppendBody("OpSelectionMerge %merge None\n"); duplicate.AppendBody("OpSelectionMerge %merge None\n"); } - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; @@ -1245,8 +1056,7 @@ std::string GetUnreachableMergeWithMultipleUses(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeWithMultipleUses) { - CompileSuccessfully( - GetUnreachableMergeWithMultipleUses(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableMergeWithMultipleUses(GetParam())); if (GetParam() == SpvCapabilityShader) { ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), @@ -1256,18 +1066,8 @@ TEST_P(ValidateCFG, UnreachableMergeWithMultipleUses) { } } -TEST_F(ValidateCFG, WebGPUUnreachableMergeWithMultipleUses) { - CompileSuccessfully(GetUnreachableMergeWithMultipleUses(SpvCapabilityShader, - SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("is already a merge block for another header")); -} - -std::string GetUnreachableContinueWithBranchUse(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableContinueWithBranchUse(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block foo("foo", SpvOpBranch); @@ -1278,21 +1078,13 @@ std::string GetUnreachableContinueWithBranchUse(SpvCapability cap, foo >> target; target >> branch; - entry.AppendBody(spvIsWebGPUEnv(env) - ? "%placeholder = OpVariable %intptrt Function %two\n" - : "%placeholder = OpVariable %intptrt Function\n"); + entry.AppendBody("%placeholder = OpVariable %intptrt Function\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) branch.AppendBody("OpLoopMerge %merge %target None\n"); - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); + str += nameOps("branch", "merge", "target", std::make_pair("func", "Main")); str += types_consts(); str += "%intptrt = OpTypePointer Function %intt\n"; str += "%func = OpFunction %voidt None %funct\n"; @@ -1307,23 +1099,12 @@ std::string GetUnreachableContinueWithBranchUse(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableContinueWithBranchUse) { - CompileSuccessfully( - GetUnreachableContinueWithBranchUse(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableContinueWithBranchUse(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableContinueWithBranchUse) { - CompileSuccessfully(GetUnreachableContinueWithBranchUse(SpvCapabilityShader, - SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("cannot be the target of a branch.")); -} - -std::string GetReachableMergeAndContinue(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetReachableMergeAndContinue(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranch); @@ -1339,20 +1120,13 @@ std::string GetReachableMergeAndContinue(SpvCapability cap, f >> target; std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) { branch.AppendBody("OpLoopMerge %merge %target None\n"); body.AppendBody("OpSelectionMerge %f None\n"); } - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", "target", "body", "t", "f", - std::make_pair("func", "Main")); - + str += nameOps("branch", "merge", "target", "body", "t", "f", + std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; @@ -1368,21 +1142,12 @@ std::string GetReachableMergeAndContinue(SpvCapability cap, } TEST_P(ValidateCFG, ReachableMergeAndContinue) { - CompileSuccessfully( - GetReachableMergeAndContinue(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetReachableMergeAndContinue(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUReachableMergeAndContinue) { - CompileSuccessfully( - GetReachableMergeAndContinue(SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -std::string GetUnreachableMergeAndContinue(SpvCapability cap, - spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableMergeAndContinue(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block branch("branch", SpvOpBranch); @@ -1396,20 +1161,13 @@ std::string GetUnreachableMergeAndContinue(SpvCapability cap, body.SetBody("%cond = OpSLessThan %boolt %one %two\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } if (cap == SpvCapabilityShader) { branch.AppendBody("OpLoopMerge %merge %target None\n"); body.AppendBody("OpSelectionMerge %target None\n"); } - if (!spvIsWebGPUEnv(env)) - str += nameOps("branch", "merge", "target", "body", "t", "f", - std::make_pair("func", "Main")); - + str += nameOps("branch", "merge", "target", "body", "t", "f", + std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> branch; @@ -1425,36 +1183,19 @@ std::string GetUnreachableMergeAndContinue(SpvCapability cap, } TEST_P(ValidateCFG, UnreachableMergeAndContinue) { - CompileSuccessfully( - GetUnreachableMergeAndContinue(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableMergeAndContinue(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableMergeAndContinue) { - CompileSuccessfully( - GetUnreachableMergeAndContinue(SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("unreachable merge-blocks must terminate with OpUnreachable")); -} - -std::string GetUnreachableBlock(SpvCapability cap, spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableBlock(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block unreachable("unreachable"); Block exit("exit", SpvOpReturn); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } - if (!spvIsWebGPUEnv(env)) - str += nameOps("unreachable", "exit", std::make_pair("func", "Main")); + str += nameOps("unreachable", "exit", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; str += entry >> exit; @@ -1466,20 +1207,12 @@ std::string GetUnreachableBlock(SpvCapability cap, spv_target_env env) { } TEST_P(ValidateCFG, UnreachableBlock) { - CompileSuccessfully(GetUnreachableBlock(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableBlock(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableBlock) { - CompileSuccessfully( - GetUnreachableBlock(SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), HasSubstr("all blocks must be reachable")); -} - -std::string GetUnreachableBranch(SpvCapability cap, spv_target_env env) { - std::string header = - spvIsWebGPUEnv(env) ? GetWebGPUHeader() : GetDefaultHeader(cap); +std::string GetUnreachableBranch(SpvCapability cap) { + std::string header = GetDefaultHeader(cap); Block entry("entry"); Block unreachable("unreachable", SpvOpBranchConditional); @@ -1493,13 +1226,7 @@ std::string GetUnreachableBranch(SpvCapability cap, spv_target_env env) { unreachable.AppendBody("OpSelectionMerge %merge None\n"); std::string str = header; - if (spvIsWebGPUEnv(env)) { - str += - "OpEntryPoint Fragment %func \"func\"\n" - "OpExecutionMode %func OriginUpperLeft\n"; - } - if (!spvIsWebGPUEnv(env)) - str += nameOps("unreachable", "exit", std::make_pair("func", "Main")); + str += nameOps("unreachable", "exit", std::make_pair("func", "Main")); str += types_consts(); str += "%func = OpFunction %voidt None %funct\n"; @@ -1516,17 +1243,10 @@ std::string GetUnreachableBranch(SpvCapability cap, spv_target_env env) { } TEST_P(ValidateCFG, UnreachableBranch) { - CompileSuccessfully(GetUnreachableBranch(GetParam(), SPV_ENV_UNIVERSAL_1_0)); + CompileSuccessfully(GetUnreachableBranch(GetParam())); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, WebGPUUnreachableBranch) { - CompileSuccessfully( - GetUnreachableBranch(SpvCapabilityShader, SPV_ENV_WEBGPU_0)); - ASSERT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), HasSubstr("all blocks must be reachable")); -} - TEST_P(ValidateCFG, EmptyFunction) { std::string str = GetDefaultHeader(GetParam()) + std::string(types_consts()) + R"(%func = OpFunction %voidt None %funct @@ -3800,7 +3520,10 @@ OpFunctionEnd CompileSuccessfully(text); EXPECT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), HasSubstr("Selection must be structured")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpSwitch must be preceeded by an OpSelectionMerge instruction")); } TEST_F(ValidateCFG, MissingMergeSwitchBad2) { @@ -3824,7 +3547,10 @@ OpFunctionEnd CompileSuccessfully(text); EXPECT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), HasSubstr("Selection must be structured")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpSwitch must be preceeded by an OpSelectionMerge instruction")); } TEST_F(ValidateCFG, MissingMergeOneBranchToMergeGood) { @@ -3874,7 +3600,7 @@ OpFunctionEnd EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateCFG, MissingMergeOneTargetSwitchGood) { +TEST_F(ValidateCFG, MissingMergeOneTargetSwitchBad) { const std::string text = R"( OpCapability Shader OpCapability Linkage @@ -3892,10 +3618,14 @@ OpFunctionEnd )"; CompileSuccessfully(text); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); + EXPECT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpSwitch must be preceeded by an OpSelectionMerge instruction")); } -TEST_F(ValidateCFG, MissingMergeOneUnseenTargetSwitchGood) { +TEST_F(ValidateCFG, MissingMergeOneUnseenTargetSwitchBad) { const std::string text = R"( OpCapability Shader OpCapability Linkage @@ -3920,7 +3650,11 @@ OpFunctionEnd )"; CompileSuccessfully(text); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); + EXPECT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpSwitch must be preceeded by an OpSelectionMerge instruction")); } TEST_F(ValidateCFG, MissingMergeLoopBreakGood) { @@ -4598,6 +4332,73 @@ TEST_F(ValidateCFG, PhiInstructionWithDuplicateIncomingEdges) { EXPECT_THAT(getDiagnosticString(), HasSubstr("multiple times.")); } +TEST_F(ValidateCFG, PhiOnVoid) { + const std::string text = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %4 "main" + OpName %6 "foo(" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpFunctionCall %2 %6 + OpBranch %20 + %20 = OpLabel + %21 = OpPhi %2 %8 %20 + OpReturn + OpFunctionEnd + %6 = OpFunction %2 None %3 + %7 = OpLabel + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(text); + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("OpPhi must not have void result type")); +} + +TEST_F(ValidateCFG, InvalidExitSingleBlockLoop) { + const std::string text = R"( +OpCapability Shader +OpCapability Linkage +OpMemoryModel Logical GLSL450 +OpName %5 "BAD" +%void = OpTypeVoid +%bool = OpTypeBool +%undef = OpUndef %bool +%void_fn = OpTypeFunction %void +%fn = OpFunction %void None %void_fn +%1 = OpLabel +OpBranch %2 +%2 = OpLabel +OpLoopMerge %3 %4 None +OpBranchConditional %undef %3 %5 +%5 = OpLabel +OpLoopMerge %6 %5 None +OpBranchConditional %undef %5 %4 +%6 = OpLabel +OpReturn +%4 = OpLabel +OpBranch %2 +%3 = OpLabel +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(text); + EXPECT_EQ(SPV_ERROR_INVALID_CFG, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("block 1[%BAD] exits the continue headed by " + "1[%BAD], but not via a structured exit")); +} + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_code_generator.cpp b/third_party/spirv-tools/test/val/val_code_generator.cpp index 62aae9c410..f151f51acb 100644 --- a/third_party/spirv-tools/test/val/val_code_generator.cpp +++ b/third_party/spirv-tools/test/val/val_code_generator.cpp @@ -32,13 +32,6 @@ OpCapability SampleRateShading )"; } -std::string GetWebGPUShaderCapabilities() { - return R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -)"; -} - std::string GetDefaultShaderTypes() { return R"( %void = OpTypeVoid @@ -115,55 +108,15 @@ std::string GetDefaultShaderTypes() { %f32vec3arr3 = OpTypeArray %f32vec3 %u32_3 %f32vec4arr3 = OpTypeArray %f32vec4 %u32_3 %f64vec4arr3 = OpTypeArray %f64vec4 %u32_3 -)"; -} -std::string GetWebGPUShaderTypes() { - return R"( -%void = OpTypeVoid -%func = OpTypeFunction %void -%bool = OpTypeBool -%f32 = OpTypeFloat 32 -%u32 = OpTypeInt 32 0 -%f32vec2 = OpTypeVector %f32 2 -%f32vec3 = OpTypeVector %f32 3 -%f32vec4 = OpTypeVector %f32 4 -%u32vec2 = OpTypeVector %u32 2 -%u32vec3 = OpTypeVector %u32 3 -%u32vec4 = OpTypeVector %u32 4 - -%f32_0 = OpConstant %f32 0 -%f32_1 = OpConstant %f32 1 -%f32_2 = OpConstant %f32 2 -%f32_3 = OpConstant %f32 3 -%f32_4 = OpConstant %f32 4 -%f32_h = OpConstant %f32 0.5 -%f32vec2_01 = OpConstantComposite %f32vec2 %f32_0 %f32_1 -%f32vec2_12 = OpConstantComposite %f32vec2 %f32_1 %f32_2 -%f32vec3_012 = OpConstantComposite %f32vec3 %f32_0 %f32_1 %f32_2 -%f32vec3_123 = OpConstantComposite %f32vec3 %f32_1 %f32_2 %f32_3 -%f32vec4_0123 = OpConstantComposite %f32vec4 %f32_0 %f32_1 %f32_2 %f32_3 -%f32vec4_1234 = OpConstantComposite %f32vec4 %f32_1 %f32_2 %f32_3 %f32_4 - -%u32_0 = OpConstant %u32 0 -%u32_1 = OpConstant %u32 1 -%u32_2 = OpConstant %u32 2 -%u32_3 = OpConstant %u32 3 -%u32_4 = OpConstant %u32 4 - -%u32vec2_01 = OpConstantComposite %u32vec2 %u32_0 %u32_1 -%u32vec2_12 = OpConstantComposite %u32vec2 %u32_1 %u32_2 -%u32vec4_0123 = OpConstantComposite %u32vec4 %u32_0 %u32_1 %u32_2 %u32_3 - -%u32arr2 = OpTypeArray %u32 %u32_2 -%u32arr3 = OpTypeArray %u32 %u32_3 -%u32arr4 = OpTypeArray %u32 %u32_4 -%f32arr2 = OpTypeArray %f32 %u32_2 -%f32arr3 = OpTypeArray %f32 %u32_3 -%f32arr4 = OpTypeArray %f32 %u32_4 - -%f32vec3arr3 = OpTypeArray %f32vec3 %u32_3 -%f32vec4arr3 = OpTypeArray %f32vec4 %u32_3 +%f32mat22 = OpTypeMatrix %f32vec2 2 +%f32mat23 = OpTypeMatrix %f32vec2 3 +%f32mat32 = OpTypeMatrix %f32vec3 2 +%f32mat33 = OpTypeMatrix %f32vec3 3 +%f64mat22 = OpTypeMatrix %f64vec2 2 +%f32mat34 = OpTypeMatrix %f32vec3 4 +%f32mat43 = OpTypeMatrix %f32vec4 3 +%f32mat44 = OpTypeMatrix %f32vec4 4 )"; } @@ -177,15 +130,6 @@ CodeGenerator CodeGenerator::GetDefaultShaderCodeGenerator() { return generator; } -CodeGenerator CodeGenerator::GetWebGPUShaderCodeGenerator() { - CodeGenerator generator; - generator.capabilities_ = GetWebGPUShaderCapabilities(); - generator.memory_model_ = "OpMemoryModel Logical VulkanKHR\n"; - generator.extensions_ = "OpExtension \"SPV_KHR_vulkan_memory_model\"\n"; - generator.types_ = GetWebGPUShaderTypes(); - return generator; -} - std::string CodeGenerator::Build() const { std::ostringstream ss; diff --git a/third_party/spirv-tools/test/val/val_code_generator.h b/third_party/spirv-tools/test/val/val_code_generator.h index e580ddff70..c69deeecea 100644 --- a/third_party/spirv-tools/test/val/val_code_generator.h +++ b/third_party/spirv-tools/test/val/val_code_generator.h @@ -31,7 +31,6 @@ struct EntryPoint { class CodeGenerator { public: static CodeGenerator GetDefaultShaderCodeGenerator(); - static CodeGenerator GetWebGPUShaderCodeGenerator(); std::string Build() const; diff --git a/third_party/spirv-tools/test/val/val_composites_test.cpp b/third_party/spirv-tools/test/val/val_composites_test.cpp index e970562110..bf7caa9fae 100644 --- a/third_party/spirv-tools/test/val/val_composites_test.cpp +++ b/third_party/spirv-tools/test/val/val_composites_test.cpp @@ -1994,6 +1994,36 @@ OpFunctionEnd HasSubstr("Cannot transpose matrices of 16-bit floats")); } +TEST_F(ValidateComposites, CopyObjectVoid) { + const std::string spirv = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + OpName %4 "main" + OpName %6 "foo(" + %2 = OpTypeVoid + %3 = OpTypeFunction %2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + %8 = OpFunctionCall %2 %6 + %20 = OpCopyObject %2 %8 + OpReturn + OpFunctionEnd + %6 = OpFunction %2 None %3 + %7 = OpLabel + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("OpCopyObject cannot have void result type")); +} + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_conversion_test.cpp b/third_party/spirv-tools/test/val/val_conversion_test.cpp index 47e67938d8..b9802ece0a 100644 --- a/third_party/spirv-tools/test/val/val_conversion_test.cpp +++ b/third_party/spirv-tools/test/val/val_conversion_test.cpp @@ -1464,16 +1464,16 @@ OpFunctionEnd TEST_F(ValidateConversion, ConvertUToPtrPSBSuccess) { const std::string body = R"( -OpCapability PhysicalStorageBufferAddressesEXT +OpCapability PhysicalStorageBufferAddresses OpCapability Int64 OpCapability Shader OpExtension "SPV_EXT_physical_storage_buffer" -OpMemoryModel PhysicalStorageBuffer64EXT GLSL450 +OpMemoryModel PhysicalStorageBuffer64 GLSL450 OpEntryPoint Fragment %main "main" OpExecutionMode %main OriginUpperLeft %uint64 = OpTypeInt 64 0 %u64_1 = OpConstant %uint64 1 -%ptr = OpTypePointer PhysicalStorageBufferEXT %uint64 +%ptr = OpTypePointer PhysicalStorageBuffer %uint64 %void = OpTypeVoid %voidfn = OpTypeFunction %void %main = OpFunction %void None %voidfn @@ -1489,11 +1489,11 @@ OpFunctionEnd TEST_F(ValidateConversion, ConvertUToPtrPSBStorageClass) { const std::string body = R"( -OpCapability PhysicalStorageBufferAddressesEXT +OpCapability PhysicalStorageBufferAddresses OpCapability Int64 OpCapability Shader OpExtension "SPV_EXT_physical_storage_buffer" -OpMemoryModel PhysicalStorageBuffer64EXT GLSL450 +OpMemoryModel PhysicalStorageBuffer64 GLSL450 OpEntryPoint Fragment %main "main" OpExecutionMode %main OriginUpperLeft %uint64 = OpTypeInt 64 0 @@ -1513,22 +1513,54 @@ OpFunctionEnd ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Pointer storage class must be " - "PhysicalStorageBufferEXT: ConvertUToPtr")); + "PhysicalStorageBuffer: ConvertUToPtr")); +} + +TEST_F(ValidateConversion, ConvertUToPtrVulkanWrongWidth) { + const std::string body = R"( +OpCapability PhysicalStorageBufferAddresses +OpCapability Int64 +OpCapability Shader +OpExtension "SPV_EXT_physical_storage_buffer" +OpMemoryModel PhysicalStorageBuffer64 GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +%uint32 = OpTypeInt 32 0 +%uint64 = OpTypeInt 64 0 +%u32_1 = OpConstant %uint32 1 +%ptr = OpTypePointer PhysicalStorageBuffer %uint64 +%void = OpTypeVoid +%voidfn = OpTypeFunction %void +%main = OpFunction %void None %voidfn +%entry = OpLabel +%val1 = OpConvertUToPtr %ptr %u32_1 +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(body.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-PhysicalStorageBuffer64-04710")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("PhysicalStorageBuffer64 addressing mode requires the input " + "integer to have a 64-bit width for Vulkan environment.")); } TEST_F(ValidateConversion, ConvertPtrToUPSBSuccess) { const std::string body = R"( -OpCapability PhysicalStorageBufferAddressesEXT +OpCapability PhysicalStorageBufferAddresses OpCapability Int64 OpCapability Shader OpExtension "SPV_EXT_physical_storage_buffer" -OpMemoryModel PhysicalStorageBuffer64EXT GLSL450 +OpMemoryModel PhysicalStorageBuffer64 GLSL450 OpEntryPoint Fragment %main "main" OpExecutionMode %main OriginUpperLeft OpDecorate %val1 RestrictPointerEXT %uint64 = OpTypeInt 64 0 %u64_1 = OpConstant %uint64 1 -%ptr = OpTypePointer PhysicalStorageBufferEXT %uint64 +%ptr = OpTypePointer PhysicalStorageBuffer %uint64 %pptr_f = OpTypePointer Function %ptr %void = OpTypeVoid %voidfn = OpTypeFunction %void @@ -1547,11 +1579,11 @@ OpFunctionEnd TEST_F(ValidateConversion, ConvertPtrToUPSBStorageClass) { const std::string body = R"( -OpCapability PhysicalStorageBufferAddressesEXT +OpCapability PhysicalStorageBufferAddresses OpCapability Int64 OpCapability Shader OpExtension "SPV_EXT_physical_storage_buffer" -OpMemoryModel PhysicalStorageBuffer64EXT GLSL450 +OpMemoryModel PhysicalStorageBuffer64 GLSL450 OpEntryPoint Fragment %main "main" OpExecutionMode %main OriginUpperLeft %uint64 = OpTypeInt 64 0 @@ -1571,7 +1603,42 @@ OpFunctionEnd ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Pointer storage class must be " - "PhysicalStorageBufferEXT: ConvertPtrToU")); + "PhysicalStorageBuffer: ConvertPtrToU")); +} + +TEST_F(ValidateConversion, ConvertPtrToUVulkanWrongWidth) { + const std::string body = R"( +OpCapability PhysicalStorageBufferAddresses +OpCapability Int64 +OpCapability Shader +OpExtension "SPV_EXT_physical_storage_buffer" +OpMemoryModel PhysicalStorageBuffer64 GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +OpDecorate %val1 RestrictPointerEXT +%uint32 = OpTypeInt 32 0 +%uint64 = OpTypeInt 64 0 +%ptr = OpTypePointer PhysicalStorageBuffer %uint64 +%pptr_f = OpTypePointer Function %ptr +%void = OpTypeVoid +%voidfn = OpTypeFunction %void +%main = OpFunction %void None %voidfn +%entry = OpLabel +%val1 = OpVariable %pptr_f Function +%val2 = OpLoad %ptr %val1 +%val3 = OpConvertPtrToU %uint32 %val2 +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(body.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-PhysicalStorageBuffer64-04710")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("PhysicalStorageBuffer64 addressing mode requires the result " + "integer type to have a 64-bit width for Vulkan environment.")); } using ValidateSmallConversions = spvtest::ValidateBase; diff --git a/third_party/spirv-tools/test/val/val_data_test.cpp b/third_party/spirv-tools/test/val/val_data_test.cpp index 30afd03cd9..1d4c0e044b 100644 --- a/third_party/spirv-tools/test/val/val_data_test.cpp +++ b/third_party/spirv-tools/test/val/val_data_test.cpp @@ -36,24 +36,6 @@ std::string HeaderWith(std::string cap) { cap + " OpMemoryModel Logical GLSL450 "; } -std::string WebGPUHeaderWith(std::string cap) { - return R"( -OpCapability Shader -OpCapability )" + - cap + R"( -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -)"; -} - -std::string webgpu_header = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -)"; - std::string header = R"( OpCapability Shader OpCapability Linkage @@ -267,18 +249,6 @@ TEST_F(ValidateData, int8_with_storage_push_constant_8_good) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()) << getDiagnosticString(); } -TEST_F(ValidateData, webgpu_int8_bad) { - std::string str = WebGPUHeaderWith("Int8") + "%2 = OpTypeInt 8 0"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Capability Int8 is not allowed by WebGPU specification (or " - "requires extension)\n" - " OpCapability Int8\n")); -} - TEST_F(ValidateData, int16_good) { std::string str = header_with_int16 + "%2 = OpTypeInt 16 1"; CompileSuccessfully(str.c_str()); @@ -338,34 +308,6 @@ TEST_F(ValidateData, int16_bad) { EXPECT_THAT(getDiagnosticString(), HasSubstr(missing_int16_cap_error)); } -TEST_F(ValidateData, webgpu_int16_bad) { - std::string str = WebGPUHeaderWith("Int16") + "%2 = OpTypeInt 16 1"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Capability Int16 is not allowed by WebGPU specification (or " - "requires extension)\n" - " OpCapability Int16\n")); -} - -TEST_F(ValidateData, webgpu_int32_good) { - std::string str = webgpu_header + R"( - OpEntryPoint Fragment %func "func" - OpExecutionMode %func OriginUpperLeft -%uint_t = OpTypeInt 32 0 - %void = OpTypeVoid -%func_t = OpTypeFunction %void - %func = OpFunction %void None %func_t - %1 = OpLabel - OpReturn - OpFunctionEnd -)"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - TEST_F(ValidateData, int64_good) { std::string str = header_with_int64 + "%2 = OpTypeInt 64 1"; CompileSuccessfully(str.c_str()); @@ -379,18 +321,6 @@ TEST_F(ValidateData, int64_bad) { EXPECT_THAT(getDiagnosticString(), HasSubstr(missing_int64_cap_error)); } -TEST_F(ValidateData, webgpu_int64_bad) { - std::string str = WebGPUHeaderWith("Int64") + "%2 = OpTypeInt 64 1"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Capability Int64 is not allowed by WebGPU specification (or " - "requires extension)\n" - " OpCapability Int64\n")); -} - // Number of bits in an integer may be only one of: {8,16,32,64} TEST_F(ValidateData, int_invalid_num_bits) { std::string str = header + "%2 = OpTypeInt 48 1"; @@ -418,34 +348,6 @@ TEST_F(ValidateData, float16_bad) { EXPECT_THAT(getDiagnosticString(), HasSubstr(missing_float16_cap_error)); } -TEST_F(ValidateData, webgpu_float16_bad) { - std::string str = WebGPUHeaderWith("Float16") + "%2 = OpTypeFloat 16"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Capability Float16 is not allowed by WebGPU specification (or " - "requires extension)\n" - " OpCapability Float16\n")); -} - -TEST_F(ValidateData, webgpu_float32_good) { - std::string str = webgpu_header + R"( - OpEntryPoint Fragment %func "func" - OpExecutionMode %func OriginUpperLeft -%float_t = OpTypeFloat 32 - %void = OpTypeVoid - %func_t = OpTypeFunction %void - %func = OpFunction %void None %func_t - %1 = OpLabel - OpReturn - OpFunctionEnd -)"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - TEST_F(ValidateData, float64_good) { std::string str = header_with_float64 + "%2 = OpTypeFloat 64"; CompileSuccessfully(str.c_str()); @@ -459,18 +361,6 @@ TEST_F(ValidateData, float64_bad) { EXPECT_THAT(getDiagnosticString(), HasSubstr(missing_float64_cap_error)); } -TEST_F(ValidateData, webgpu_float64_bad) { - std::string str = WebGPUHeaderWith("Float64") + "%2 = OpTypeFloat 64"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Capability Float64 is not allowed by WebGPU specification (or " - "requires extension)\n" - " OpCapability Float64\n")); -} - // Number of bits in a float may be only one of: {16,32,64} TEST_F(ValidateData, float_invalid_num_bits) { std::string str = header + "%2 = OpTypeFloat 48"; @@ -497,7 +387,7 @@ TEST_F(ValidateData, ids_should_be_validated_before_data) { CompileSuccessfully(str.c_str()); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), - HasSubstr("ID 3[%3] has not been defined")); + HasSubstr("Operand 3[%3] requires a previous definition")); } TEST_F(ValidateData, matrix_bad_column_type) { @@ -882,66 +772,58 @@ TEST_F(ValidateData, vulkan_RTA_not_at_end_of_struct) { "OpTypeStruct %_runtimearr_uint %uint\n")); } -TEST_F(ValidateData, webgpu_RTA_array_at_end_of_struct) { - std::string str = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Fragment %func "func" - OpExecutionMode %func OriginUpperLeft - OpDecorate %array_t ArrayStride 4 - OpMemberDecorate %struct_t 0 Offset 0 - OpMemberDecorate %struct_t 1 Offset 4 - OpDecorate %struct_t Block - %uint_t = OpTypeInt 32 0 - %array_t = OpTypeRuntimeArray %uint_t - %struct_t = OpTypeStruct %uint_t %array_t -%struct_ptr = OpTypePointer StorageBuffer %struct_t - %2 = OpVariable %struct_ptr StorageBuffer - %void = OpTypeVoid - %func_t = OpTypeFunction %void - %func = OpFunction %void None %func_t - %1 = OpLabel - OpReturn - OpFunctionEnd +TEST_F(ValidateData, TypeForwardReference) { + std::string test = R"( +OpCapability Shader +OpCapability PhysicalStorageBufferAddresses +OpCapability Linkage +OpMemoryModel Logical GLSL450 +OpTypeForwardPointer %1 PhysicalStorageBuffer +%2 = OpTypeStruct +%3 = OpTypeRuntimeArray %1 +%1 = OpTypePointer PhysicalStorageBuffer %2 )"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); + CompileSuccessfully(test, SPV_ENV_UNIVERSAL_1_5); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_5)); } -TEST_F(ValidateData, webgpu_RTA_not_at_end_of_struct) { - std::string str = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Fragment %func "func" - OpExecutionMode %func OriginUpperLeft - OpDecorate %array_t ArrayStride 4 - OpMemberDecorate %struct_t 0 Offset 0 - OpMemberDecorate %struct_t 1 Offset 4 - OpDecorate %struct_t Block - %uint_t = OpTypeInt 32 0 - %array_t = OpTypeRuntimeArray %uint_t - %struct_t = OpTypeStruct %array_t %uint_t -%struct_ptr = OpTypePointer StorageBuffer %struct_t - %2 = OpVariable %struct_ptr StorageBuffer - %void = OpTypeVoid - %func_t = OpTypeFunction %void - %func = OpFunction %void None %func_t - %1 = OpLabel - OpReturn - OpFunctionEnd +TEST_F(ValidateData, VulkanTypeForwardStorageClass) { + std::string test = R"( +OpCapability Shader +OpCapability PhysicalStorageBufferAddresses +OpMemoryModel Logical GLSL450 +OpTypeForwardPointer %1 Uniform +%2 = OpTypeStruct +%3 = OpTypeRuntimeArray %1 +%1 = OpTypePointer Uniform %2 )"; - CompileSuccessfully(str.c_str(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); + CompileSuccessfully(test, SPV_ENV_VULKAN_1_2); + ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_2)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("In WebGPU, OpTypeRuntimeArray must only be used for " - "the last member of an OpTypeStruct\n %_struct_3 = " - "OpTypeStruct %_runtimearr_uint %uint\n")); + AnyVUID("VUID-StandaloneSpirv-OpTypeForwardPointer-04711")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("In Vulkan, OpTypeForwardPointer must have " + "a storage class of PhysicalStorageBuffer.")); +} + +TEST_F(ValidateData, TypeForwardReferenceMustBeForwardPointer) { + std::string test = R"( +OpCapability Shader +OpCapability PhysicalStorageBufferAddresses +OpCapability Linkage +OpMemoryModel Logical GLSL450 +%1 = OpTypeStruct +%2 = OpTypeRuntimeArray %3 +%3 = OpTypePointer PhysicalStorageBuffer %1 +)"; + + CompileSuccessfully(test, SPV_ENV_UNIVERSAL_1_5); + ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_UNIVERSAL_1_5)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Operand 3[%_ptr_PhysicalStorageBuffer__struct_1] " + "requires a previous definition")); } } // namespace diff --git a/third_party/spirv-tools/test/val/val_decoration_test.cpp b/third_party/spirv-tools/test/val/val_decoration_test.cpp index e646162420..096fd172dd 100644 --- a/third_party/spirv-tools/test/val/val_decoration_test.cpp +++ b/third_party/spirv-tools/test/val/val_decoration_test.cpp @@ -42,8 +42,8 @@ struct TestResult { }; using ValidateDecorations = spvtest::ValidateBase; -using ValidateWebGPUCombineDecorationResult = - spvtest::ValidateBase>; +using ValidateVulkanCombineDecorationResult = + spvtest::ValidateBase>; TEST_F(ValidateDecorations, ValidateOpDecorateRegistration) { std::string spirv = R"( @@ -163,44 +163,6 @@ TEST_F(ValidateDecorations, ValidateGroupDecorateRegistration) { EXPECT_THAT(vstate_->id_decorations(4), Eq(expected_decorations)); } -TEST_F(ValidateDecorations, WebGPUOpDecorationGroupBad) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpDecorate %1 DescriptorSet 0 - OpDecorate %1 NonWritable - OpDecorate %1 Restrict - %1 = OpDecorationGroup - OpGroupDecorate %1 %2 %3 - OpGroupDecorate %1 %4 - %float = OpTypeFloat 32 -%_runtimearr_float = OpTypeRuntimeArray %float - %_struct_9 = OpTypeStruct %_runtimearr_float -%_ptr_Uniform__struct_9 = OpTypePointer Uniform %_struct_9 - %2 = OpVariable %_ptr_Uniform__struct_9 Uniform - %_struct_10 = OpTypeStruct %_runtimearr_float -%_ptr_Uniform__struct_10 = OpTypePointer Uniform %_struct_10 - %3 = OpVariable %_ptr_Uniform__struct_10 Uniform - %_struct_11 = OpTypeStruct %_runtimearr_float -%_ptr_Uniform__struct_11 = OpTypePointer Uniform %_struct_11 - %4 = OpVariable %_ptr_Uniform__struct_11 Uniform - )"; - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("OpDecorationGroup is not allowed in the WebGPU " - "execution environment.\n %1 = OpDecorationGroup\n")); -} - -// For WebGPU, OpGroupDecorate does not have a test case, because it requires -// being preceded by OpDecorationGroup, which will cause a validation error. - -// For WebGPU, OpGroupMemberDecorate does not have a test case, because it -// requires being preceded by OpDecorationGroup, which will cause a validation -// error. - TEST_F(ValidateDecorations, ValidateGroupMemberDecorateRegistration) { std::string spirv = R"( OpCapability Shader @@ -4679,6 +4641,95 @@ OpFunctionEnd "Object operand of an OpStore.")); } +TEST_F(ValidateDecorations, VulkanFPRoundingModeGood) { + std::string spirv = R"( + OpCapability Shader + OpCapability StorageBuffer16BitAccess + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 1 1 1 + OpMemberDecorate %ssbo 0 Offset 0 + OpDecorate %ssbo Block + OpDecorate %_ DescriptorSet 0 + OpDecorate %_ Binding 0 + OpDecorate %17 FPRoundingMode RTE + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 +%_ptr_Function_float = OpTypePointer Function %float + %float_1 = OpConstant %float 1 + %half = OpTypeFloat 16 + %ssbo = OpTypeStruct %half +%_ptr_StorageBuffer_ssbo = OpTypePointer StorageBuffer %ssbo + %_ = OpVariable %_ptr_StorageBuffer_ssbo StorageBuffer + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 +%_ptr_StorageBuffer_half = OpTypePointer StorageBuffer %half + %main = OpFunction %void None %3 + %5 = OpLabel + %b = OpVariable %_ptr_Function_float Function + OpStore %b %float_1 + %16 = OpLoad %float %b + %17 = OpFConvert %half %16 + %19 = OpAccessChain %_ptr_StorageBuffer_half %_ %int_0 + OpStore %19 %17 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_2); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_VULKAN_1_2)); +} + +TEST_F(ValidateDecorations, VulkanFPRoundingModeBadMode) { + std::string spirv = R"( + OpCapability Shader + OpCapability StorageBuffer16BitAccess + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 1 1 1 + OpMemberDecorate %ssbo 0 Offset 0 + OpDecorate %ssbo Block + OpDecorate %_ DescriptorSet 0 + OpDecorate %_ Binding 0 + OpDecorate %17 FPRoundingMode RTP + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 +%_ptr_Function_float = OpTypePointer Function %float + %float_1 = OpConstant %float 1 + %half = OpTypeFloat 16 + %ssbo = OpTypeStruct %half +%_ptr_StorageBuffer_ssbo = OpTypePointer StorageBuffer %ssbo + %_ = OpVariable %_ptr_StorageBuffer_ssbo StorageBuffer + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 +%_ptr_StorageBuffer_half = OpTypePointer StorageBuffer %half + %main = OpFunction %void None %3 + %5 = OpLabel + %b = OpVariable %_ptr_Function_float Function + OpStore %b %float_1 + %16 = OpLoad %float %b + %17 = OpFConvert %half %16 + %19 = OpAccessChain %_ptr_StorageBuffer_half %_ %int_0 + OpStore %19 %17 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_2); + EXPECT_EQ(SPV_ERROR_INVALID_ID, + ValidateAndRetrieveValidationState(SPV_ENV_VULKAN_1_2)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-FPRoundingMode-04675")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("In Vulkan, the FPRoundingMode mode must only by RTE or RTZ.")); +} + TEST_F(ValidateDecorations, GroupDecorateTargetsDecorationGroup) { std::string spirv = R"( OpCapability Shader @@ -4940,6 +4991,8 @@ TEST_F(ValidateDecorations, UniformDecorationWithScopeIdV14VulkanEnv) { CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_1_SPIRV_1_4); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_1_SPIRV_1_4)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04636")); EXPECT_THAT(getDiagnosticString(), HasSubstr(": in Vulkan environment Execution Scope is limited to " "Workgroup and Subgroup")); @@ -6299,11 +6352,12 @@ TEST_F(ValidateDecorations, NonWritableRuntimeArrayGood) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_P(ValidateWebGPUCombineDecorationResult, Decorate) { +TEST_P(ValidateVulkanCombineDecorationResult, Decorate) { const char* const decoration = std::get<0>(GetParam()); - const TestResult& test_result = std::get<1>(GetParam()); + const char* const vuid = std::get<1>(GetParam()); + const TestResult& test_result = std::get<2>(GetParam()); - CodeGenerator generator = CodeGenerator::GetWebGPUShaderCodeGenerator(); + CodeGenerator generator = CodeGenerator::GetDefaultShaderCodeGenerator(); generator.before_types_ = "OpDecorate %u32 "; generator.before_types_ += decoration; generator.before_types_ += "\n"; @@ -6313,52 +6367,24 @@ TEST_P(ValidateWebGPUCombineDecorationResult, Decorate) { entry_point.execution_model = "Vertex"; generator.entry_points_.push_back(std::move(entry_point)); - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); + CompileSuccessfully(generator.Build(), SPV_ENV_VULKAN_1_0); ASSERT_EQ(test_result.validation_result, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - if (test_result.error_str != "") { - EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str)); - } -} - -TEST_P(ValidateWebGPUCombineDecorationResult, DecorateMember) { - const char* const decoration = std::get<0>(GetParam()); - const TestResult& test_result = std::get<1>(GetParam()); - - CodeGenerator generator = CodeGenerator::GetWebGPUShaderCodeGenerator(); - generator.before_types_ = "OpMemberDecorate %struct_type 0 "; - generator.before_types_ += decoration; - generator.before_types_ += "\n"; - - generator.after_types_ = "%struct_type = OpTypeStruct %u32\n"; - - EntryPoint entry_point; - entry_point.name = "main"; - entry_point.execution_model = "Vertex"; - generator.entry_points_.push_back(std::move(entry_point)); - - CompileSuccessfully(generator.Build(), SPV_ENV_WEBGPU_0); - ASSERT_EQ(test_result.validation_result, - ValidateInstructions(SPV_ENV_WEBGPU_0)); + ValidateInstructions(SPV_ENV_VULKAN_1_0)); if (!test_result.error_str.empty()) { EXPECT_THAT(getDiagnosticString(), HasSubstr(test_result.error_str)); } + if (vuid) { + EXPECT_THAT(getDiagnosticString(), AnyVUID(vuid)); + } } INSTANTIATE_TEST_SUITE_P( - DecorationCapabilityFailure, ValidateWebGPUCombineDecorationResult, - Combine(Values("CPacked", "Patch", "Sample", "Constant", - "SaturatedConversion", "NonUniformEXT"), - Values(TestResult(SPV_ERROR_INVALID_CAPABILITY, - "requires one of these capabilities")))); - -INSTANTIATE_TEST_SUITE_P( - DecorationAllowListFailure, ValidateWebGPUCombineDecorationResult, - Combine(Values("RelaxedPrecision", "BufferBlock", "GLSLShared", - "GLSLPacked", "Invariant", "Volatile", "Coherent"), + DecorationAllowListFailure, ValidateVulkanCombineDecorationResult, + Combine(Values("GLSLShared", "GLSLPacked"), + Values("VUID-StandaloneSpirv-GLSLShared-04669"), Values(TestResult( SPV_ERROR_INVALID_ID, - "is not valid for the WebGPU execution environment.")))); + "is not valid for the Vulkan execution environment.")))); TEST_F(ValidateDecorations, NonWritableVarFunctionV13Bad) { std::string spirv = ShaderWithNonWritableTarget("%var_func"); @@ -7159,6 +7185,469 @@ OpDecorate %float Location 0 "or member of a structure type")); } +TEST_F(ValidateDecorations, WorkgroupSingleBlockVariable) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 8 1 1 + OpMemberDecorate %first 0 Offset 0 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); +} + +TEST_F(ValidateDecorations, WorkgroupBlockVariableRequiresV14) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 8 1 1 + OpMemberDecorate %first 0 Offset 0 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_3); + EXPECT_EQ(SPV_ERROR_WRONG_VERSION, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("requires SPIR-V version 1.4 or later")); +} + +TEST_F(ValidateDecorations, WorkgroupSingleNonBlockVariable) { + std::string spirv = R"( + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %a + OpExecutionMode %main LocalSize 8 1 1 + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %a = OpVariable %_ptr_Workgroup_int Workgroup + %int_2 = OpConstant %int 2 + %main = OpFunction %void None %3 + %5 = OpLabel + OpStore %a %int_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); +} + +TEST_F(ValidateDecorations, WorkgroupMultiBlockVariable) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ %__0 + OpExecutionMode %main LocalSize 8 1 1 + OpMemberDecorate %first 0 Offset 0 + OpDecorate %first Block + OpMemberDecorate %second 0 Offset 0 + OpDecorate %second Block + OpDecorate %_ Aliased + OpDecorate %__0 Aliased + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %second = OpTypeStruct %int +%_ptr_Workgroup_second = OpTypePointer Workgroup %second + %__0 = OpVariable %_ptr_Workgroup_second Workgroup + %int_3 = OpConstant %int 3 + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + %18 = OpAccessChain %_ptr_Workgroup_int %__0 %int_0 + OpStore %18 %int_3 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); +} + +TEST_F(ValidateDecorations, WorkgroupBlockVariableWith8BitType) { + std::string spirv = R"( + OpCapability Shader + OpCapability Int8 + OpCapability WorkgroupMemoryExplicitLayout8BitAccessKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 2 1 1 + OpMemberDecorate %first 0 Offset 0 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %char = OpTypeInt 8 1 + %first = OpTypeStruct %char +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %char_2 = OpConstant %char 2 +%_ptr_Workgroup_char = OpTypePointer Workgroup %char + %main = OpFunction %void None %3 + %5 = OpLabel + %14 = OpAccessChain %_ptr_Workgroup_char %_ %int_0 + OpStore %14 %char_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); +} + +TEST_F(ValidateDecorations, WorkgroupMultiNonBlockVariable) { + std::string spirv = R"( + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %a %b + OpExecutionMode %main LocalSize 8 1 1 + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %a = OpVariable %_ptr_Workgroup_int Workgroup + %int_2 = OpConstant %int 2 + %b = OpVariable %_ptr_Workgroup_int Workgroup + %int_3 = OpConstant %int 3 + %main = OpFunction %void None %3 + %5 = OpLabel + OpStore %a %int_2 + OpStore %b %int_3 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); +} + +TEST_F(ValidateDecorations, WorkgroupBlockVariableWith16BitType) { + std::string spirv = R"( + OpCapability Shader + OpCapability Float16 + OpCapability Int16 + OpCapability WorkgroupMemoryExplicitLayout16BitAccessKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 2 1 1 + OpMemberDecorate %first 0 Offset 0 + OpMemberDecorate %first 1 Offset 2 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %short = OpTypeInt 16 1 + %half = OpTypeFloat 16 + %first = OpTypeStruct %short %half +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int = OpTypeInt 32 1 + %int_0 = OpConstant %int 0 + %short_3 = OpConstant %short 3 +%_ptr_Workgroup_short = OpTypePointer Workgroup %short + %int_1 = OpConstant %int 1 +%half_0x1_898p_3 = OpConstant %half 0x1.898p+3 +%_ptr_Workgroup_half = OpTypePointer Workgroup %half + %main = OpFunction %void None %3 + %5 = OpLabel + %15 = OpAccessChain %_ptr_Workgroup_short %_ %int_0 + OpStore %15 %short_3 + %19 = OpAccessChain %_ptr_Workgroup_half %_ %int_1 + OpStore %19 %half_0x1_898p_3 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_SUCCESS, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); +} + +TEST_F(ValidateDecorations, WorkgroupBlockVariableScalarLayout) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint Vertex %main "main" %B + OpSource GLSL 450 + OpMemberDecorate %S 0 Offset 0 + OpMemberDecorate %S 1 Offset 4 + OpMemberDecorate %S 2 Offset 16 + OpMemberDecorate %S 3 Offset 28 + OpDecorate %S Block + OpDecorate %B Aliased + %void = OpTypeVoid + %3 = OpTypeFunction %void + %float = OpTypeFloat 32 + %v3float = OpTypeVector %float 3 + %S = OpTypeStruct %float %v3float %v3float %v3float +%_ptr_Workgroup_S = OpTypePointer Workgroup %S + %B = OpVariable %_ptr_Workgroup_S Workgroup + %main = OpFunction %void None %3 + %5 = OpLabel + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + spvValidatorOptionsSetWorkgroupScalarBlockLayout(getValidatorOptions(), true); + EXPECT_EQ(SPV_SUCCESS, ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)) + << getDiagnosticString(); +} + +TEST_F(ValidateDecorations, WorkgroupMixBlockAndNonBlockBad) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ %b + OpExecutionMode %main LocalSize 8 1 1 + OpMemberDecorate %first 0 Offset 0 + OpDecorate %first Block + OpDecorate %_ Aliased + OpDecorate %b Aliased + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %b = OpVariable %_ptr_Workgroup_int Workgroup + %int_3 = OpConstant %int 3 + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + OpStore %b %int_3 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_ERROR_INVALID_BINARY, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("either all or none of the Workgroup Storage Class variables " + "in the entry point interface must point to struct types " + "decorated with Block")); +} + +TEST_F(ValidateDecorations, WorkgroupMultiBlockVariableMissingAliased) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ %__0 + OpExecutionMode %main LocalSize 8 1 1 + OpMemberDecorate %first 0 Offset 0 + OpDecorate %first Block + OpMemberDecorate %second 0 Offset 0 + OpDecorate %second Block + OpDecorate %_ Aliased + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %second = OpTypeStruct %int +%_ptr_Workgroup_second = OpTypePointer Workgroup %second + %__0 = OpVariable %_ptr_Workgroup_second Workgroup + %int_3 = OpConstant %int 3 + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + %18 = OpAccessChain %_ptr_Workgroup_int %__0 %int_0 + OpStore %18 %int_3 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_ERROR_INVALID_BINARY, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("more than one Workgroup Storage Class variable in the " + "entry point interface point to a type decorated with Block, " + "all of them must be decorated with Aliased")); +} + +TEST_F(ValidateDecorations, WorkgroupSingleBlockVariableNotAStruct) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 8 1 1 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %int_3 = OpConstant %int 3 + %first = OpTypeArray %int %int_3 +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_ERROR_INVALID_ID, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Block decoration on a non-struct type")); +} + +TEST_F(ValidateDecorations, WorkgroupSingleBlockVariableMissingLayout) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 8 1 1 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_ERROR_INVALID_ID, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Block must be explicitly laid out with Offset decorations")); +} + +TEST_F(ValidateDecorations, WorkgroupSingleBlockVariableBadLayout) { + std::string spirv = R"( + OpCapability Shader + OpCapability WorkgroupMemoryExplicitLayoutKHR + OpExtension "SPV_KHR_workgroup_memory_explicit_layout" + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %main "main" %_ + OpExecutionMode %main LocalSize 8 1 1 + OpMemberDecorate %first 0 Offset 1 + OpDecorate %first Block + %void = OpTypeVoid + %3 = OpTypeFunction %void + %int = OpTypeInt 32 1 + %first = OpTypeStruct %int +%_ptr_Workgroup_first = OpTypePointer Workgroup %first + %_ = OpVariable %_ptr_Workgroup_first Workgroup + %int_0 = OpConstant %int 0 + %int_2 = OpConstant %int 2 +%_ptr_Workgroup_int = OpTypePointer Workgroup %int + %main = OpFunction %void None %3 + %5 = OpLabel + %13 = OpAccessChain %_ptr_Workgroup_int %_ %int_0 + OpStore %13 %int_2 + OpReturn + OpFunctionEnd + )"; + + CompileSuccessfully(spirv, SPV_ENV_UNIVERSAL_1_4); + EXPECT_EQ(SPV_ERROR_INVALID_ID, + ValidateAndRetrieveValidationState(SPV_ENV_UNIVERSAL_1_4)); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "Block for variable in Workgroup storage class must follow " + "standard storage buffer layout rules: " + "member 0 at offset 1 is not aligned to 4")); +} + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_ext_inst_test.cpp b/third_party/spirv-tools/test/val/val_ext_inst_test.cpp index 683a76f5ed..b73ec3415d 100644 --- a/third_party/spirv-tools/test/val/val_ext_inst_test.cpp +++ b/third_party/spirv-tools/test/val/val_ext_inst_test.cpp @@ -5204,6 +5204,49 @@ TEST_F(ValidateExtInst, GlslStd450InterpolateAtCentroidSuccess) { ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } +TEST_F(ValidateExtInst, GlslStd450InterpolateAtCentroidInternalSuccess) { + const std::string body = R"( +%ld1 = OpLoad %f32 %f32_input +%val1 = OpExtInst %f32 %extinst InterpolateAtCentroid %ld1 +%ld2 = OpLoad %f32vec2 %f32vec2_input +%val2 = OpExtInst %f32vec2 %extinst InterpolateAtCentroid %ld2 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + getValidatorOptions()->before_hlsl_legalization = true; + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateExtInst, GlslStd450InterpolateAtCentroidInternalInvalidDataF32) { + const std::string body = R"( +%ld1 = OpLoad %f32 %f32_input +%val1 = OpExtInst %f32 %extinst InterpolateAtCentroid %ld1 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("GLSL.std.450 InterpolateAtCentroid: " + "expected Interpolant to be a pointer")); +} + +TEST_F(ValidateExtInst, + GlslStd450InterpolateAtCentroidInternalInvalidDataF32Vec2) { + const std::string body = R"( +%ld2 = OpLoad %f32vec2 %f32vec2_input +%val2 = OpExtInst %f32vec2 %extinst InterpolateAtCentroid %ld2 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("GLSL.std.450 InterpolateAtCentroid: " + "expected Interpolant to be a pointer")); +} + TEST_F(ValidateExtInst, GlslStd450InterpolateAtCentroidNoCapability) { const std::string body = R"( %val1 = OpExtInst %f32 %extinst InterpolateAtCentroid %f32_input @@ -5308,6 +5351,49 @@ TEST_F(ValidateExtInst, GlslStd450InterpolateAtSampleSuccess) { ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } +TEST_F(ValidateExtInst, GlslStd450InterpolateAtSampleInternalSuccess) { + const std::string body = R"( +%ld1 = OpLoad %f32 %f32_input +%val1 = OpExtInst %f32 %extinst InterpolateAtSample %ld1 %u32_1 +%ld2 = OpLoad %f32vec2 %f32vec2_input +%val2 = OpExtInst %f32vec2 %extinst InterpolateAtSample %ld2 %u32_1 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + getValidatorOptions()->before_hlsl_legalization = true; + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateExtInst, GlslStd450InterpolateAtSampleInternalInvalidDataF32) { + const std::string body = R"( +%ld1 = OpLoad %f32 %f32_input +%val1 = OpExtInst %f32 %extinst InterpolateAtSample %ld1 %u32_1 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("GLSL.std.450 InterpolateAtSample: " + "expected Interpolant to be a pointer")); +} + +TEST_F(ValidateExtInst, + GlslStd450InterpolateAtSampleInternalInvalidDataF32Vec2) { + const std::string body = R"( +%ld2 = OpLoad %f32vec2 %f32vec2_input +%val2 = OpExtInst %f32vec2 %extinst InterpolateAtSample %ld2 %u32_1 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("GLSL.std.450 InterpolateAtSample: " + "expected Interpolant to be a pointer")); +} + TEST_F(ValidateExtInst, GlslStd450InterpolateAtSampleNoCapability) { const std::string body = R"( %val1 = OpExtInst %f32 %extinst InterpolateAtSample %f32_input %u32_1 @@ -5438,6 +5524,48 @@ TEST_F(ValidateExtInst, GlslStd450InterpolateAtOffsetSuccess) { ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } +TEST_F(ValidateExtInst, GlslStd450InterpolateAtOffsetInternalSuccess) { + const std::string body = R"( +%ld1 = OpLoad %f32 %f32_input +%val1 = OpExtInst %f32 %extinst InterpolateAtOffset %ld1 %f32vec2_01 +%ld2 = OpLoad %f32vec2 %f32vec2_input +%val2 = OpExtInst %f32vec2 %extinst InterpolateAtOffset %ld2 %f32vec2_01 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + getValidatorOptions()->before_hlsl_legalization = true; + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateExtInst, GlslStd450InterpolateAtOffsetInternalInvalidDataF32) { + const std::string body = R"( +%ld1 = OpLoad %f32 %f32_input +%val1 = OpExtInst %f32 %extinst InterpolateAtOffset %ld1 %f32vec2_01 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("GLSL.std.450 InterpolateAtOffset: " + "expected Interpolant to be a pointer")); +} + +TEST_F(ValidateExtInst, GlslStd450InterpolateAtOffsetInternalInvalidDataF32Vec2) { + const std::string body = R"( +%ld2 = OpLoad %f32vec2 %f32vec2_input +%val2 = OpExtInst %f32vec2 %extinst InterpolateAtOffset %ld2 %f32vec2_01 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "OpCapability InterpolationFunction\n")); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("GLSL.std.450 InterpolateAtOffset: " + "expected Interpolant to be a pointer")); +} + TEST_F(ValidateExtInst, GlslStd450InterpolateAtOffsetNoCapability) { const std::string body = R"( %val1 = OpExtInst %f32 %extinst InterpolateAtOffset %f32_input %f32vec2_01 diff --git a/third_party/spirv-tools/test/val/val_extension_spv_khr_bit_instructions.cpp b/third_party/spirv-tools/test/val/val_extension_spv_khr_bit_instructions.cpp new file mode 100644 index 0000000000..0e926716f7 --- /dev/null +++ b/third_party/spirv-tools/test/val/val_extension_spv_khr_bit_instructions.cpp @@ -0,0 +1,117 @@ +// Copyright (c) 2021 The Khronos Group Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Tests for OpExtension validator rules. + +#include +#include + +#include "gmock/gmock.h" +#include "source/enum_string_mapping.h" +#include "source/extensions.h" +#include "source/spirv_target_env.h" +#include "test/test_fixture.h" +#include "test/unit_spirv.h" +#include "test/val/val_fixtures.h" + +namespace spvtools { +namespace val { +namespace { + +using ::testing::HasSubstr; +using ::testing::Values; +using ::testing::ValuesIn; + +using ValidateSpvKHRBitInstructions = spvtest::ValidateBase; + +TEST_F(ValidateSpvKHRBitInstructions, Valid) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability BitInstructions + OpExtension "SPV_KHR_bit_instructions" + OpMemoryModel Physical32 OpenCL + OpEntryPoint Kernel %main "main" + + %void = OpTypeVoid + %void_fn = OpTypeFunction %void + %u32 = OpTypeInt 32 0 + %u32_1 = OpConstant %u32 1 + + %main = OpFunction %void None %void_fn + %entry = OpLabel + %unused = OpBitReverse %u32 %u32_1 + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateSpvKHRBitInstructions, RequiresExtension) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability BitInstructions + OpMemoryModel Physical32 OpenCL + OpEntryPoint Kernel %main "main" + + %void = OpTypeVoid + %void_fn = OpTypeFunction %void + %u32 = OpTypeInt 32 0 + %u32_1 = OpConstant %u32 1 + + %main = OpFunction %void None %void_fn + %entry = OpLabel + %unused = OpBitReverse %u32 %u32_1 + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("1st operand of Capability: operand BitInstructions(6025) " + "requires one of these extensions: SPV_KHR_bit_instructions")); +} + +TEST_F(ValidateSpvKHRBitInstructions, RequiresCapability) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpExtension "SPV_KHR_bit_instructions" + OpMemoryModel Physical32 OpenCL + OpEntryPoint Kernel %main "main" + + %void = OpTypeVoid + %void_fn = OpTypeFunction %void + %u32 = OpTypeInt 32 0 + %u32_1 = OpConstant %u32 1 + + %main = OpFunction %void None %void_fn + %entry = OpLabel + %unused = OpBitReverse %u32 %u32_1 + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Opcode BitReverse requires one of these capabilities: " + "Shader BitInstructions")); +} + +} // namespace +} // namespace val +} // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_extension_spv_khr_expect_assume.cpp b/third_party/spirv-tools/test/val/val_extension_spv_khr_expect_assume.cpp new file mode 100644 index 0000000000..6ece15d18e --- /dev/null +++ b/third_party/spirv-tools/test/val/val_extension_spv_khr_expect_assume.cpp @@ -0,0 +1,310 @@ +// Copyright (c) 2020 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Tests for OpExtension validator rules. + +#include +#include + +#include "gmock/gmock.h" +#include "source/enum_string_mapping.h" +#include "source/extensions.h" +#include "source/spirv_target_env.h" +#include "test/test_fixture.h" +#include "test/unit_spirv.h" +#include "test/val/val_fixtures.h" + +namespace spvtools { +namespace val { +namespace { + +using ::testing::HasSubstr; +using ::testing::Values; +using ::testing::ValuesIn; + +using ValidateSpvExpectAssumeKHR = spvtest::ValidateBase; + +TEST_F(ValidateSpvExpectAssumeKHR, Valid) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpCapability ExpectAssumeKHR + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %bool = OpTypeBool + %true = OpConstantTrue %bool + %undef = OpUndef %bool + + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 + %uint_2 = OpConstant %uint 2 + + %v2bool = OpTypeVector %bool 2 + %v2uint = OpTypeVector %uint 2 + + %null_v2bool = OpConstantNull %v2bool + %null_v2uint = OpConstantNull %v2uint + + %main = OpFunction %void None %voidfn + %entry = OpLabel + OpAssumeTrueKHR %true + OpAssumeTrueKHR %undef ; probably undefined behaviour + %bool_val = OpExpectKHR %bool %true %true + %uint_val = OpExpectKHR %uint %uint_1 %uint_2 ; a bad expectation + %v2bool_val = OpExpectKHR %v2bool %null_v2bool %null_v2bool + %v2uint_val = OpExpectKHR %v2uint %null_v2uint %null_v2uint + OpReturn + OpFunctionEnd + +)"; + CompileSuccessfully(str.c_str()); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateSpvExpectAssumeKHR, RequiresExtension) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpCapability ExpectAssumeKHR + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %bool = OpTypeBool + %true = OpConstantTrue %bool + %undef = OpUndef %bool + + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 + %uint_2 = OpConstant %uint 2 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + OpAssumeTrueKHR %true + OpAssumeTrueKHR %undef ; probably undefined behaviour + %val = OpExpectKHR %uint %uint_1 %uint_2 ; a bad expectation + OpReturn + OpFunctionEnd + +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Capability: operand ExpectAssumeKHR(5629) requires " + "one of these extensions: SPV_KHR_expect_assume")); +} + +TEST_F(ValidateSpvExpectAssumeKHR, + AssumeTrueKHR_RequiresExpectAssumeCapability) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %bool = OpTypeBool + %true = OpConstantTrue %bool + %undef = OpUndef %bool + + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 + %uint_2 = OpConstant %uint 2 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + OpAssumeTrueKHR %true + OpAssumeTrueKHR %undef ; probably undefined behaviour + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Opcode AssumeTrueKHR requires one of these " + "capabilities: ExpectAssumeKHR \n" + " OpAssumeTrueKHR %true\n")); +} + +TEST_F(ValidateSpvExpectAssumeKHR, AssumeTrueKHR_OperandMustBeBool) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpCapability ExpectAssumeKHR + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %bool = OpTypeBool + %true = OpConstantTrue %bool + %undef = OpUndef %bool + + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 + %uint_2 = OpConstant %uint 2 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + OpAssumeTrueKHR %uint_1 ; bad type + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Value operand of OpAssumeTrueKHR must be a boolean scalar\n" + " OpAssumeTrueKHR %uint_1\n")); +} + +TEST_F(ValidateSpvExpectAssumeKHR, ExpectKHR_RequiresExpectAssumeCapability) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %bool = OpTypeBool + %true = OpConstantTrue %bool + %undef = OpUndef %bool + + %uint = OpTypeInt 32 0 + %uint_1 = OpConstant %uint 1 + %uint_2 = OpConstant %uint 2 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + %val = OpExpectKHR %uint %uint_1 %uint_2 ; a bad expectation + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Opcode ExpectKHR requires one of these capabilities: " + "ExpectAssumeKHR \n" + " %11 = OpExpectKHR %uint %uint_1 %uint_2\n")); +} + +TEST_F(ValidateSpvExpectAssumeKHR, ExpectKHR_ResultMustBeBoolOrIntScalar) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpCapability ExpectAssumeKHR + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %float = OpTypeFloat 32 + + %float_0 = OpConstant %float 0 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + %val = OpExpectKHR %float %float_0 %float_0 + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Result of OpExpectKHR must be a scalar or vector of " + "integer type or boolean type\n" + " %7 = OpExpectKHR %float %float_0 %float_0\n")); +} + +TEST_F(ValidateSpvExpectAssumeKHR, ExpectKHR_Value0MustMatchResultType) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpCapability ExpectAssumeKHR + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %uint = OpTypeInt 32 0 + %float = OpTypeFloat 32 + %float_0 = OpConstant %float 0 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + %val = OpExpectKHR %uint %float_0 %float_0 + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Type of Value operand of OpExpectKHR does not match " + "the result type \n" + " %8 = OpExpectKHR %uint %float_0 %float_0\n")); +} + +TEST_F(ValidateSpvExpectAssumeKHR, ExpectKHR_Value1MustMatchResultType) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpCapability ExpectAssumeKHR + OpExtension "SPV_KHR_expect_assume" + OpMemoryModel Physical32 OpenCL + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + + %uint = OpTypeInt 32 0 + %uint_0 = OpConstant %uint 0 + %float = OpTypeFloat 32 + %float_0 = OpConstant %float 0 + + %main = OpFunction %void None %voidfn + %entry = OpLabel + %val = OpExpectKHR %uint %uint_0 %float_0 + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Type of ExpectedValue operand of OpExpectKHR does not " + "match the result type \n" + " %9 = OpExpectKHR %uint %uint_0 %float_0\n")); +} + +} // namespace +} // namespace val +} // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_extension_spv_khr_integer_dot_product.cpp b/third_party/spirv-tools/test/val/val_extension_spv_khr_integer_dot_product.cpp new file mode 100644 index 0000000000..e0e6896c90 --- /dev/null +++ b/third_party/spirv-tools/test/val/val_extension_spv_khr_integer_dot_product.cpp @@ -0,0 +1,1330 @@ +// Copyright (c) 2020 Google Inc. +// Copyright (c) 2021 Arm Ltd. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include +#include + +#include "gmock/gmock.h" +#include "source/enum_string_mapping.h" +#include "source/extensions.h" +#include "source/spirv_target_env.h" +#include "test/test_fixture.h" +#include "test/unit_spirv.h" +#include "test/val/val_fixtures.h" + +namespace spvtools { +namespace val { +namespace { + +using ::testing::HasSubstr; +using ::testing::Values; + +struct Case { + std::vector caps; + std::string inst; + std::string result_type; + std::string op0_type; + std::string op1_type; + std::string acc_type; // can be empty + bool packed; + std::string expected_error; // empty for no error. +}; + +inline std::ostream& operator<<(std::ostream& out, Case c) { + out << "\nSPV_KHR_integer_dot_product Case{{"; + bool first = true; + for (const auto& cap : c.caps) { + if (!first) { + out << " "; + } + first = false; + out << cap; + } + out << "} "; + out << c.inst << " "; + out << c.result_type << " "; + out << c.op0_type << " "; + out << c.op1_type << " "; + out << "'" << c.acc_type << "' "; + out << (c.packed ? "packed " : "unpacked "); + out << "err'" << c.expected_error << "'"; + return out; +} + +std::string AssemblyForCase(const Case& c) { + std::ostringstream ss; + ss << "OpCapability Shader\n"; + for (auto& cap : c.caps) { + ss << "OpCapability " << cap << "\n"; + } + ss << R"( + OpExtension "SPV_KHR_integer_dot_product" + OpMemoryModel Logical Simple + OpEntryPoint GLCompute %main "main" + OpExecutionMode %main LocalSize 1 1 1 + + %void = OpTypeVoid + %voidfn = OpTypeFunction %void + %uint = OpTypeInt 32 0 + %int = OpTypeInt 32 1 + + %v2uint = OpTypeVector %uint 2 + %v3uint = OpTypeVector %uint 3 + %v4uint = OpTypeVector %uint 4 + %v2int = OpTypeVector %int 2 + %v3int = OpTypeVector %int 3 + %v4int = OpTypeVector %int 4 + + %uint_0 = OpConstant %uint 0 + %uint_1 = OpConstant %uint 1 + %int_0 = OpConstant %int 0 + %int_1 = OpConstant %int 1 + + %v2uint_0 = OpConstantComposite %v2uint %uint_0 %uint_0 + %v2uint_1 = OpConstantComposite %v2uint %uint_1 %uint_1 + %v3uint_0 = OpConstantComposite %v3uint %uint_0 %uint_0 %uint_0 + %v3uint_1 = OpConstantComposite %v3uint %uint_1 %uint_1 %uint_1 + %v4uint_0 = OpConstantComposite %v4uint %uint_0 %uint_0 %uint_0 %uint_0 + %v4uint_1 = OpConstantComposite %v4uint %uint_1 %uint_1 %uint_1 %uint_1 + + %v2int_0 = OpConstantComposite %v2int %int_0 %int_0 + %v2int_1 = OpConstantComposite %v2int %int_1 %int_1 + %v3int_0 = OpConstantComposite %v3int %int_0 %int_0 %int_0 + %v3int_1 = OpConstantComposite %v3int %int_1 %int_1 %int_1 + %v4int_0 = OpConstantComposite %v4int %int_0 %int_0 %int_0 %int_0 + %v4int_1 = OpConstantComposite %v4int %int_1 %int_1 %int_1 %int_1 +)"; + + bool use8bit = false; + for (auto& cap : c.caps) { + if (cap == "DotProductInput4x8BitKHR") { + use8bit = true; + } + if (cap == "Int8") { + use8bit = true; + } + } + if (use8bit) { + ss << R"( + %uchar = OpTypeInt 8 0 + %char = OpTypeInt 8 1 + + %v4uchar = OpTypeVector %uchar 4 + %v4char = OpTypeVector %char 4 + + %uchar_0 = OpConstant %uchar 0 + %uchar_1 = OpConstant %uchar 1 + %char_0 = OpConstant %char 0 + %char_1 = OpConstant %char 1 + + %v4uchar_0 = OpConstantComposite %v4uchar %uchar_0 %uint_0 %uchar_0 %uchar_0 + %v4uchar_1 = OpConstantComposite %v4uchar %uchar_1 %uchar_1 %uchar_1 %uchar_1 + %v4char_0 = OpConstantComposite %v4char %char_0 %char_0 %char_0 %char_0 + %v4char_1 = OpConstantComposite %v4char %char_1 %char_1 %char_1 %char_1 + + )"; + } + + ss << R"( + + %main = OpFunction %void None %voidfn + %entry = OpLabel + %result = )" + << c.inst << " " << c.result_type << " "; + ss << c.op0_type << "_0 "; + ss << c.op1_type << "_1 "; + if (!c.acc_type.empty()) { + ss << c.acc_type << "_0 "; + } + if (c.packed) { + ss << "PackedVectorFormat4x8BitKHR"; + } + ss << "\nOpReturn\nOpFunctionEnd\n\n"; + return ss.str(); +} + +using ValidateSpvKHRIntegerDotProduct = spvtest::ValidateBase; + +TEST_P(ValidateSpvKHRIntegerDotProduct, Valid) { + const auto& c = GetParam(); + const auto& assembly = AssemblyForCase(c); + CompileSuccessfully(assembly); + if (c.expected_error.empty()) { + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()) << getDiagnosticString(); + } else { + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), HasSubstr(c.expected_error)); + } +} + +// UDot +INSTANTIATE_TEST_SUITE_P( + Valid_UDot, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpUDotKHR", + "%uint", + "%v2uint", + "%v2uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpUDotKHR", + "%uint", + "%v3uint", + "%v3uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpUDotKHR", + "%uint", + "%v4uint", + "%v4uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpUDotKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpUDotKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpUDotKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpUDotKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpUDotKHR", + "%uchar", // matches packed component type + "%uint", + "%uint", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpUDotKHR", + "%uint", + "%uint", + "%uint", + "", + true, + ""})); + +// SDot result signed args signed signed +INSTANTIATE_TEST_SUITE_P( + Valid_SDot_signed_signed_signed, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%int", + "%v2int", + "%v2int", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%int", + "%v3int", + "%v3int", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%int", + "%v4int", + "%v4int", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotKHR", + "%char", // match width + "%v4char", + "%v4char", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotKHR", + "%int", // wider width + "%v4char", + "%v4char", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotKHR", + "%char", // match width + "%v4char", + "%v4char", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotKHR", + "%int", // wider width + "%v4char", + "%v4char", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSDotKHR", + "%char", // matches packed component type + "%int", + "%int", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSDotKHR", + "%int", + "%int", + "%int", + "", + true, + ""})); + +// SDot result unsigned args signed unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SDot_unsigned_signed_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%uint", + "%v2int", + "%v2uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%uint", + "%v3int", + "%v3uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%uint", + "%v4int", + "%v4uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotKHR", + "%uchar", // match width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotKHR", + "%uint", // wider width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotKHR", + "%uchar", // match width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotKHR", + "%uint", // wider width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSDotKHR", + "%uchar", // matches packed component type + "%int", + "%uint", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSDotKHR", + "%uint", + "%int", + "%uint", + "", + true, + ""})); + +// SDot result signed args signed unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SDot_signed_signed_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%int", + "%v2int", + "%v2uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%int", + "%v3int", + "%v3uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotKHR", + "%int", + "%v4int", + "%v4uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSDotKHR", + "%char", // matches packed component type + "%int", + "%uint", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSDotKHR", + "%int", + "%int", + "%uint", + "", + true, + ""})); + +// SUDot result signed args unsigned unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SUDot_signed_unsigned_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%int", + "%v2uint", + "%v2uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%int", + "%v3uint", + "%v3uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%int", + "%v4uint", + "%v4uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotKHR", + "%char", // match width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotKHR", + "%int", // wider width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotKHR", + "%char", // match width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotKHR", + "%int", // wider width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSUDotKHR", + "%char", // matches packed component type + "%uint", + "%uint", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSUDotKHR", + "%int", + "%uint", + "%uint", + "", + true, + ""})); + +// SUDot result signed args signed unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SUDot_signed_signed_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%int", + "%v2int", + "%v2uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%int", + "%v3int", + "%v3uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%int", + "%v4int", + "%v4uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSUDotKHR", + "%char", // matches packed component type + "%int", + "%uint", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSUDotKHR", + "%int", + "%int", + "%uint", + "", + true, + ""})); + +// SUDot result unsigned args unsigned unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SUDot_unsigned_unsigned_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%uint", + "%v2uint", + "%v2uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%uint", + "%v3uint", + "%v3uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotKHR", + "%uint", + "%v4uint", + "%v4uint", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSUDotKHR", + "%uchar", // matches packed component type + "%uint", + "%uint", + "", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSUDotKHR", + "%uint", + "%uint", + "%uint", + "", + true, + ""})); + +// UDotAccSat +INSTANTIATE_TEST_SUITE_P( + Valid_UDotAccSat, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpUDotAccSatKHR", + "%uint", + "%v2uint", + "%v2uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpUDotAccSatKHR", + "%uint", + "%v3uint", + "%v3uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpUDotAccSatKHR", + "%uint", + "%v4uint", + "%v4uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpUDotAccSatKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpUDotAccSatKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpUDotAccSatKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "%uchar", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpUDotAccSatKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpUDotAccSatKHR", + "%uchar", // matches packed component type + "%uint", + "%uint", + "%uchar", + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpUDotAccSatKHR", + "%uint", + "%uint", + "%uint", + "%uint", + true, + ""})); + +// SDotAccSat result signed args signed signed +INSTANTIATE_TEST_SUITE_P( + Valid_SDotAccSat_signed_signed_signed, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%int", + "%v2int", + "%v2int", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%int", + "%v3int", + "%v3int", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%int", + "%v4int", + "%v4int", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotAccSatKHR", + "%char", // match width + "%v4char", + "%v4char", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotAccSatKHR", + "%int", // wider width + "%v4char", + "%v4char", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotAccSatKHR", + "%char", // match width + "%v4char", + "%v4char", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotAccSatKHR", + "%int", // wider width + "%v4char", + "%v4char", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSDotAccSatKHR", + "%char", // matches packed component type + "%int", + "%int", + "%char", // matches packed component type + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSDotAccSatKHR", + "%int", + "%int", + "%int", + "%int", + true, + ""})); + +// SDotAccSat result unsigned args signed unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SDotAccSat_unsigned_signed_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%uint", + "%v2int", + "%v2uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%uint", + "%v3int", + "%v3uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%uint", + "%v4int", + "%v4uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotAccSatKHR", + "%uchar", // match width + "%v4char", + "%v4uchar", + "%uchar", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotAccSatKHR", + "%uint", // wider width + "%v4char", + "%v4uchar", + "%uint", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotAccSatKHR", + "%uchar", // match width + "%v4char", + "%v4uchar", + "%uchar", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotAccSatKHR", + "%uint", // wider width + "%v4char", + "%v4uchar", + "%uint", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSDotAccSatKHR", + "%uchar", // matches packed component type + "%int", + "%uint", + "%uchar", // matches packed component type + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSDotAccSatKHR", + "%uint", + "%int", + "%uint", + "%uint", + true, + ""})); + +// SDotAccSat result signed args signed unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SDotAccSat_signed_signed_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%int", + "%v2int", + "%v2uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%int", + "%v3int", + "%v3uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSDotAccSatKHR", + "%int", + "%v4int", + "%v4uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotAccSatKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSDotAccSatKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotAccSatKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSDotAccSatKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSDotAccSatKHR", + "%char", // matches packed component type + "%int", + "%uint", + "%char", // matches packed component type + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSDotAccSatKHR", + "%int", + "%int", + "%uint", + "%int", + true, + ""})); + +// SUDotAccSat result signed args unsigned unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SUDotAccSat_signed_unsigned_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%v2uint", + "%v2uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%v3uint", + "%v3uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%v4uint", + "%v4uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotAccSatKHR", + "%char", // match width + "%v4uchar", + "%v4uchar", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotAccSatKHR", + "%int", // wider width + "%v4uchar", + "%v4uchar", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotAccSatKHR", + "%char", // match width + "%v4uchar", + "%v4uchar", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotAccSatKHR", + "%int", // wider width + "%v4uchar", + "%v4uchar", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSUDotAccSatKHR", + "%char", // matches packed component type + "%uint", + "%uint", + "%char", // matches packed component type + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%uint", + "%uint", + "%int", + true, + ""})); + +// SUDotAccSat result signed args signed unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SUDotAccSat_signed_signed_unsigned, ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%v2int", + "%v2uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%v3int", + "%v3uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%v4int", + "%v4uint", + "%int", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotAccSatKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotAccSatKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotAccSatKHR", + "%char", // match width + "%v4char", + "%v4uchar", + "%char", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotAccSatKHR", + "%int", // wider width + "%v4char", + "%v4uchar", + "%int", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSUDotAccSatKHR", + "%char", // matches packed component type + "%int", + "%uint", + "%char", // matches packed component type + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSUDotAccSatKHR", + "%int", + "%int", + "%uint", + "%int", + true, + ""})); + +// SUDotAccSat result unsigned args unsigned unsigned +INSTANTIATE_TEST_SUITE_P( + Valid_SUDotAccSat_unsigned_unsigned_unsigned, + ValidateSpvKHRIntegerDotProduct, + ::testing::Values(Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%uint", + "%v2uint", + "%v2uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%uint", + "%v3uint", + "%v3uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR"}, + "OpSUDotAccSatKHR", + "%uint", + "%v4uint", + "%v4uint", + "%uint", + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotAccSatKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "%uchar", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInputAllKHR", "Int8"}, + "OpSUDotAccSatKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "%uint", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotAccSatKHR", + "%uchar", // match width + "%v4uchar", + "%v4uchar", + "%uchar", // match width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitKHR"}, + "OpSUDotAccSatKHR", + "%uint", // wider width + "%v4uchar", + "%v4uchar", + "%uint", // wider width + false, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR", + "Int8"}, + "OpSUDotAccSatKHR", + "%uchar", // matches packed component type + "%uint", + "%uint", + "%uchar", // matches packed component type + true, + ""}, + Case{{"DotProductKHR", "DotProductInput4x8BitPackedKHR"}, + "OpSUDotAccSatKHR", + "%uint", + "%uint", + "%uint", + "%uint", + true, + ""})); + +using ValidateSpvKHRIntegerDotProductSimple = ::testing::Test; + +TEST(ValidateSpvKHRIntegerDotProductSimple, DISABLED_RequiresExtension) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, DISABLED_Invalid_ResultTooNarrow) { + // Test across all the instructions. + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_UDot_OperandTypesMatch) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_SDot_OperandTypesMatchExceptSignedness) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_SUDot_OperandTypesMatchExceptSignedness) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_UDotAccSat_OperandTypesMatch) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_SDotAccSat_OperandTypesMatchExceptSignedness) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_SUDotAccSat_OperandTypesMatchExceptSignedness) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_UDot_RequiresUnsigned) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_SUDot_RequiresUnsignedSecondArg) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_UDotAccSat_RequiresUnsigned) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_SUDotAccSat_RequiresUnsignedSecondArg) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_VectorOperandsDisallowPackedFormat) { + FAIL(); +} + +TEST(ValidateSpvKHRIntegerDotProductSimple, + DISABLED_Invalid_ScalarOperandsRequirePackedFormat) { + FAIL(); +} + +// TODO(dneto): Test valid cases with other scalar integer types +// TODO(dneto): Test valid cases of length-8 vectors +// TODO(dneto): Test valid cases of length-16 vectors + +} // namespace +} // namespace val +} // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_extension_spv_khr_linkonce_odr.cpp b/third_party/spirv-tools/test/val/val_extension_spv_khr_linkonce_odr.cpp new file mode 100644 index 0000000000..ac15558bef --- /dev/null +++ b/third_party/spirv-tools/test/val/val_extension_spv_khr_linkonce_odr.cpp @@ -0,0 +1,100 @@ +// Copyright (c) 2020 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Tests for OpExtension validator rules. + +#include +#include + +#include "gmock/gmock.h" +#include "source/enum_string_mapping.h" +#include "source/extensions.h" +#include "source/spirv_target_env.h" +#include "test/test_fixture.h" +#include "test/unit_spirv.h" +#include "test/val/val_fixtures.h" + +namespace spvtools { +namespace val { +namespace { + +using ::testing::HasSubstr; +using ::testing::Values; +using ::testing::ValuesIn; + +using ValidateSpvKHRLinkOnceODR = spvtest::ValidateBase; + +TEST_F(ValidateSpvKHRLinkOnceODR, Valid) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpExtension "SPV_KHR_linkonce_odr" + OpMemoryModel Physical32 OpenCL + OpDecorate %var LinkageAttributes "foobar" LinkOnceODR + + %uint = OpTypeInt 32 0 + %ptr = OpTypePointer CrossWorkgroup %uint + %var = OpVariable %ptr CrossWorkgroup + +)"; + CompileSuccessfully(str.c_str()); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateSpvKHRLinkOnceODR, RequiresExtension) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpMemoryModel Physical32 OpenCL + OpDecorate %var LinkageAttributes "foobar" LinkOnceODR + + %uint = OpTypeInt 32 0 + %ptr = OpTypePointer CrossWorkgroup %uint + %var = OpVariable %ptr CrossWorkgroup +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("4th operand of Decorate: operand LinkOnceODR(2) requires one " + "of these extensions: SPV_KHR_linkonce_odr \n" + " OpDecorate %1 LinkageAttributes \"foobar\" LinkOnceODR\n")); +} + +TEST_F(ValidateSpvKHRLinkOnceODR, RequiresLinkageCapability) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpExtension "SPV_KHR_linkonce_odr" + OpMemoryModel Physical32 OpenCL + OpDecorate %var LinkageAttributes "foobar" LinkOnceODR + + %uint = OpTypeInt 32 0 + %ptr = OpTypePointer CrossWorkgroup %uint + %var = OpVariable %ptr CrossWorkgroup +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "Operand 2 of Decorate requires one of these capabilities: Linkage \n" + " OpDecorate %1 LinkageAttributes \"foobar\" LinkOnceODR")); +} + +} // namespace +} // namespace val +} // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_extension_spv_khr_subgroup_uniform_control_flow.cpp b/third_party/spirv-tools/test/val/val_extension_spv_khr_subgroup_uniform_control_flow.cpp new file mode 100644 index 0000000000..f528cb9eef --- /dev/null +++ b/third_party/spirv-tools/test/val/val_extension_spv_khr_subgroup_uniform_control_flow.cpp @@ -0,0 +1,110 @@ +// Copyright (c) 2021 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Tests for OpExtension validator rules. + +#include +#include + +#include "gmock/gmock.h" +#include "source/enum_string_mapping.h" +#include "source/extensions.h" +#include "source/spirv_target_env.h" +#include "test/test_fixture.h" +#include "test/unit_spirv.h" +#include "test/val/val_fixtures.h" + +namespace spvtools { +namespace val { +namespace { + +using ::testing::HasSubstr; +using ::testing::Values; +using ::testing::ValuesIn; + +using ValidateSpvKHRSubgroupUniformControlFlow = spvtest::ValidateBase; + +TEST_F(ValidateSpvKHRSubgroupUniformControlFlow, Valid) { + const std::string str = R"( + OpCapability Shader + OpExtension "SPV_KHR_subgroup_uniform_control_flow" + OpMemoryModel Logical Simple + OpEntryPoint GLCompute %main "main" + OpExecutionMode %main LocalSize 1 1 1 + OpExecutionMode %main SubgroupUniformControlFlowKHR + + %void = OpTypeVoid + %void_fn = OpTypeFunction %void + + %main = OpFunction %void None %void_fn + %entry = OpLabel + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateSpvKHRSubgroupUniformControlFlow, RequiresExtension) { + const std::string str = R"( + OpCapability Shader + OpMemoryModel Logical Simple + OpEntryPoint GLCompute %main "main" + OpExecutionMode %main LocalSize 1 1 1 + OpExecutionMode %main SubgroupUniformControlFlowKHR + + %void = OpTypeVoid + %void_fn = OpTypeFunction %void + + %main = OpFunction %void None %void_fn + %entry = OpLabel + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("2nd operand of ExecutionMode: operand " + "SubgroupUniformControlFlowKHR(4421) " + "requires one of these extensions: " + "SPV_KHR_subgroup_uniform_control_flow")); +} + +TEST_F(ValidateSpvKHRSubgroupUniformControlFlow, RequiresShaderCapability) { + const std::string str = R"( + OpCapability Kernel + OpCapability Addresses + OpExtension "SPV_KHR_subgroup_uniform_control_flow" + OpMemoryModel Physical32 OpenCL + OpEntryPoint Kernel %main "main" + OpExecutionMode %main SubgroupUniformControlFlowKHR + + %void = OpTypeVoid + %void_fn = OpTypeFunction %void + + %main = OpFunction %void None %void_fn + %entry = OpLabel + OpReturn + OpFunctionEnd +)"; + CompileSuccessfully(str.c_str()); + EXPECT_NE(SPV_SUCCESS, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Operand 2 of ExecutionMode requires one of these " + "capabilities: Shader")); +} + +} // namespace +} // namespace val +} // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_fixtures.h b/third_party/spirv-tools/test/val/val_fixtures.h index 5635c7813f..acbe0e5775 100644 --- a/third_party/spirv-tools/test/val/val_fixtures.h +++ b/third_party/spirv-tools/test/val/val_fixtures.h @@ -183,4 +183,43 @@ spv_position_t ValidateBase::getErrorPosition() { } // namespace spvtest +// For Vulkan testing. +// Allows test parameter test to list all possible VUIDs with a delimiter that +// is then split here to check if one VUID was in the error message +MATCHER_P(AnyVUID, vuid_set, "VUID from the set is in error message") { + // use space as delimiter because clang-format will properly line break VUID + // strings which is important the entire VUID is in a single line for script + // to scan + std::string delimiter = " "; + std::string token; + std::string vuids = std::string(vuid_set); + size_t position; + + // Catch case were someone accidentally left spaces by trimming string + // clang-format off + vuids.erase(std::find_if(vuids.rbegin(), vuids.rend(), [](unsigned char c) { + return (c != ' '); + }).base(), vuids.end()); + vuids.erase(vuids.begin(), std::find_if(vuids.begin(), vuids.end(), [](unsigned char c) { + return (c != ' '); + })); + // clang-format on + + do { + position = vuids.find(delimiter); + if (position != std::string::npos) { + token = vuids.substr(0, position); + vuids.erase(0, position + delimiter.length()); + } else { + token = vuids.substr(0); // last item + } + + // arg contains diagnostic message + if (arg.find(token) != std::string::npos) { + return true; + } + } while (position != std::string::npos); + return false; +} + #endif // TEST_VAL_VAL_FIXTURES_H_ diff --git a/third_party/spirv-tools/test/val/val_id_test.cpp b/third_party/spirv-tools/test/val/val_id_test.cpp index adea5639b2..dd4c952cf9 100644 --- a/third_party/spirv-tools/test/val/val_id_test.cpp +++ b/third_party/spirv-tools/test/val/val_id_test.cpp @@ -411,10 +411,10 @@ TEST_F(ValidateIdWithMessage, OpEntryPointFunctionBad) { } TEST_F(ValidateIdWithMessage, OpEntryPointParameterCountBad) { std::string spirv = kGLSL450MemoryModel + R"( - OpEntryPoint GLCompute %3 "" -%1 = OpTypeVoid -%2 = OpTypeFunction %1 %1 -%3 = OpFunction %1 None %2 + OpEntryPoint GLCompute %1 "" +%2 = OpTypeVoid +%3 = OpTypeFunction %2 %2 +%1 = OpFunction %2 None %3 %4 = OpLabel OpReturn OpFunctionEnd)"; @@ -426,11 +426,11 @@ TEST_F(ValidateIdWithMessage, OpEntryPointParameterCountBad) { } TEST_F(ValidateIdWithMessage, OpEntryPointReturnTypeBad) { std::string spirv = kGLSL450MemoryModel + R"( - OpEntryPoint GLCompute %3 "" -%1 = OpTypeInt 32 0 -%ret = OpConstant %1 0 -%2 = OpTypeFunction %1 -%3 = OpFunction %1 None %2 + OpEntryPoint GLCompute %1 "" +%2 = OpTypeInt 32 0 +%ret = OpConstant %2 0 +%3 = OpTypeFunction %2 +%1 = OpFunction %2 None %3 %4 = OpLabel OpReturnValue %ret OpFunctionEnd)"; @@ -440,6 +440,45 @@ TEST_F(ValidateIdWithMessage, OpEntryPointReturnTypeBad) { HasSubstr("OpEntryPoint Entry Point '1[%1]'s function " "return type is not void.")); } +TEST_F(ValidateIdWithMessage, OpEntryPointParameterCountBadInVulkan) { + std::string spirv = R"( + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %1 "" +%2 = OpTypeVoid +%3 = OpTypeFunction %2 %2 +%1 = OpFunction %2 None %3 +%4 = OpLabel + OpReturn + OpFunctionEnd)"; + CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04633")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("OpEntryPoint Entry Point '1[%1]'s function " + "parameter count is not zero")); +} +TEST_F(ValidateIdWithMessage, OpEntryPointReturnTypeBadInVulkan) { + std::string spirv = R"( + OpCapability Shader + OpMemoryModel Logical GLSL450 + OpEntryPoint GLCompute %1 "" +%2 = OpTypeInt 32 0 +%ret = OpConstant %2 0 +%3 = OpTypeFunction %2 +%1 = OpFunction %2 None %3 +%4 = OpLabel + OpReturnValue %ret + OpFunctionEnd)"; + CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04633")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("OpEntryPoint Entry Point '1[%1]'s function " + "return type is not void.")); +} TEST_F(ValidateIdWithMessage, OpEntryPointInterfaceIsNotVariableTypeBad) { std::string spirv = R"( @@ -796,7 +835,7 @@ class OpTypeArrayLengthTest position_(spv_position_t{0, 0, 0}), diagnostic_(spvDiagnosticCreate(&position_, "")) {} - ~OpTypeArrayLengthTest() { spvDiagnosticDestroy(diagnostic_); } + ~OpTypeArrayLengthTest() override { spvDiagnosticDestroy(diagnostic_); } // Runs spvValidate() on v, printing any errors via spvDiagnosticPrint(). spv_result_t Val(const SpirvVector& v, const std::string& expected_err = "") { @@ -915,31 +954,6 @@ TEST_P(OpTypeArrayLengthTest, LengthPositiveHugeEnding1InVulkan) { } } -TEST_P(OpTypeArrayLengthTest, LengthPositiveHugeEnding0InWebGPU) { - env_ = SPV_ENV_WEBGPU_0; - const int width = GetParam(); - // WebGPU only has 32 bit integers. - if (width != 32) return; - const int max_int_width = 32; - const auto module = CompileSuccessfully(MakeArrayLength( - big_num_ending_0(width), kUnsigned, width, max_int_width, true)); - EXPECT_EQ(SPV_SUCCESS, Val(module)); -} - -TEST_P(OpTypeArrayLengthTest, LengthPositiveHugeEnding1InWebGPU) { - env_ = SPV_ENV_WEBGPU_0; - const int width = GetParam(); - // WebGPU only has 32 bit integers. - if (width != 32) return; - const int max_int_width = 32; - const auto module = CompileSuccessfully(MakeArrayLength( - big_num_ending_1(width), kUnsigned, width, max_int_width, true)); - EXPECT_EQ(SPV_ERROR_INVALID_ID, - Val(module, - "OpTypeArray Length '3\\[%.*\\]' size exceeds max value " - "2147483648 permitted by WebGPU: got 2147483649")); -} - // The only valid widths for integers are 8, 16, 32, and 64. // Since the Int8 capability requires the Kernel capability, and the Kernel // capability prohibits usage of signed integers, we can skip 8-bit integers @@ -1041,6 +1055,8 @@ TEST_F(ValidateIdWithMessage, OpTypeStructOpaqueTypeBad) { )"; CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_0); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04667")); EXPECT_THAT(getDiagnosticString(), HasSubstr("OpTypeStruct must not contain an opaque type")); } @@ -2749,9 +2765,13 @@ TEST_F(ValidateIdWithMessage, OpStoreObjectGood) { %6 = OpVariable %3 Uniform %7 = OpFunction %1 None %4 %8 = OpLabel -%9 = OpUndef %1 +%9 = OpFunctionCall %1 %10 OpStore %6 %9 OpReturn + OpFunctionEnd +%10 = OpFunction %1 None %4 +%11 = OpLabel + OpReturn OpFunctionEnd)"; CompileSuccessfully(spirv.c_str()); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); @@ -4688,39 +4708,6 @@ TEST_F(ValidateIdWithMessage, OpVectorShuffleLiterals) { "size of 5.")); } -TEST_F(ValidateIdWithMessage, WebGPUOpVectorShuffle0xFFFFFFFFLiteralBad) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR -%float = OpTypeFloat 32 -%vec2 = OpTypeVector %float 2 -%vec3 = OpTypeVector %float 3 -%vec4 = OpTypeVector %float 4 -%ptr_vec2 = OpTypePointer Function %vec2 -%ptr_vec3 = OpTypePointer Function %vec3 -%float_1 = OpConstant %float 1 -%float_2 = OpConstant %float 2 -%1 = OpConstantComposite %vec2 %float_2 %float_1 -%2 = OpConstantComposite %vec3 %float_1 %float_2 %float_2 -%3 = OpTypeFunction %vec4 -%4 = OpFunction %vec4 None %3 -%5 = OpLabel -%var = OpVariable %ptr_vec2 Function %1 -%var2 = OpVariable %ptr_vec3 Function %2 -%6 = OpLoad %vec2 %var -%7 = OpLoad %vec3 %var2 -%8 = OpVectorShuffle %vec4 %6 %7 4 3 1 0xffffffff - OpReturnValue %8 - OpFunctionEnd)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Component literal at operand 3 cannot be 0xFFFFFFFF in" - " WebGPU execution environment.")); -} - // TODO: OpCompositeConstruct // TODO: OpCompositeExtract // TODO: OpCompositeInsert diff --git a/third_party/spirv-tools/test/val/val_image_test.cpp b/third_party/spirv-tools/test/val/val_image_test.cpp index 2e84a29fac..701e35e132 100644 --- a/third_party/spirv-tools/test/val/val_image_test.cpp +++ b/third_party/spirv-tools/test/val/val_image_test.cpp @@ -66,9 +66,9 @@ OpCapability ImageBuffer %uniform_image_f32_1d_0001 %uniform_image_f32_1d_0002_rgba32f %uniform_image_f32_2d_0001 -%uniform_image_f32_2d_0010 +%uniform_image_f32_2d_0011 ; multisampled sampled %uniform_image_u32_2d_0001 -%uniform_image_u32_2d_0000 +%uniform_image_u32_2d_0002 %uniform_image_s32_3d_0001 %uniform_image_f32_2d_0002 %uniform_image_s32_2d_0002 @@ -80,6 +80,7 @@ OpCapability ImageBuffer %private_image_u32_buffer_0002_r32ui %private_image_u32_spd_0002 %private_image_f32_buffer_0002_r32ui +%input_flat_u32 )"; ss << capabilities_and_extensions; @@ -99,12 +100,12 @@ OpDecorate %uniform_image_f32_1d_0002_rgba32f DescriptorSet 0 OpDecorate %uniform_image_f32_1d_0002_rgba32f Binding 1 OpDecorate %uniform_image_f32_2d_0001 DescriptorSet 0 OpDecorate %uniform_image_f32_2d_0001 Binding 2 -OpDecorate %uniform_image_f32_2d_0010 DescriptorSet 0 -OpDecorate %uniform_image_f32_2d_0010 Binding 3 +OpDecorate %uniform_image_f32_2d_0011 DescriptorSet 0 +OpDecorate %uniform_image_f32_2d_0011 Binding 3 OpDecorate %uniform_image_u32_2d_0001 DescriptorSet 1 OpDecorate %uniform_image_u32_2d_0001 Binding 0 -OpDecorate %uniform_image_u32_2d_0000 DescriptorSet 1 -OpDecorate %uniform_image_u32_2d_0000 Binding 1 +OpDecorate %uniform_image_u32_2d_0002 DescriptorSet 1 +OpDecorate %uniform_image_u32_2d_0002 Binding 1 OpDecorate %uniform_image_s32_3d_0001 DescriptorSet 1 OpDecorate %uniform_image_s32_3d_0001 Binding 2 OpDecorate %uniform_image_f32_2d_0002 DescriptorSet 1 @@ -121,6 +122,8 @@ OpDecorate %uniform_image_f32_cube_0102_rgba32f DescriptorSet 2 OpDecorate %uniform_image_f32_cube_0102_rgba32f Binding 3 OpDecorate %uniform_sampler DescriptorSet 3 OpDecorate %uniform_sampler Binding 0 +OpDecorate %input_flat_u32 Flat +OpDecorate %input_flat_u32 Location 0 )"; } @@ -133,6 +136,7 @@ OpDecorate %uniform_sampler Binding 0 %u32 = OpTypeInt 32 0 %s32 = OpTypeInt 32 1 %u64 = OpTypeInt 64 0 +%s64 = OpTypeInt 64 1 %s32vec2 = OpTypeVector %s32 2 %u32vec2 = OpTypeVector %u32 2 %f32vec2 = OpTypeVector %f32 2 @@ -223,27 +227,25 @@ OpDecorate %uniform_sampler Binding 0 %type_image_f32_1d_0002_rgba32f = OpTypeImage %f32 1D 0 0 0 2 Rgba32f %ptr_image_f32_1d_0002_rgba32f = OpTypePointer UniformConstant %type_image_f32_1d_0002_rgba32f %uniform_image_f32_1d_0002_rgba32f = OpVariable %ptr_image_f32_1d_0002_rgba32f UniformConstant -%type_sampled_image_f32_1d_0002_rgba32f = OpTypeSampledImage %type_image_f32_1d_0002_rgba32f %type_image_f32_2d_0001 = OpTypeImage %f32 2D 0 0 0 1 Unknown %ptr_image_f32_2d_0001 = OpTypePointer UniformConstant %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 = OpVariable %ptr_image_f32_2d_0001 UniformConstant %type_sampled_image_f32_2d_0001 = OpTypeSampledImage %type_image_f32_2d_0001 -%type_image_f32_2d_0010 = OpTypeImage %f32 2D 0 0 1 0 Unknown -%ptr_image_f32_2d_0010 = OpTypePointer UniformConstant %type_image_f32_2d_0010 -%uniform_image_f32_2d_0010 = OpVariable %ptr_image_f32_2d_0010 UniformConstant -%type_sampled_image_f32_2d_0010 = OpTypeSampledImage %type_image_f32_2d_0010 +%type_image_f32_2d_0011 = OpTypeImage %f32 2D 0 0 1 1 Unknown +%ptr_image_f32_2d_0011 = OpTypePointer UniformConstant %type_image_f32_2d_0011 +%uniform_image_f32_2d_0011 = OpVariable %ptr_image_f32_2d_0011 UniformConstant +%type_sampled_image_f32_2d_0011 = OpTypeSampledImage %type_image_f32_2d_0011 %type_image_u32_2d_0001 = OpTypeImage %u32 2D 0 0 0 1 Unknown %ptr_image_u32_2d_0001 = OpTypePointer UniformConstant %type_image_u32_2d_0001 %uniform_image_u32_2d_0001 = OpVariable %ptr_image_u32_2d_0001 UniformConstant %type_sampled_image_u32_2d_0001 = OpTypeSampledImage %type_image_u32_2d_0001 -%type_image_u32_2d_0000 = OpTypeImage %u32 2D 0 0 0 0 Unknown -%ptr_image_u32_2d_0000 = OpTypePointer UniformConstant %type_image_u32_2d_0000 -%uniform_image_u32_2d_0000 = OpVariable %ptr_image_u32_2d_0000 UniformConstant -%type_sampled_image_u32_2d_0000 = OpTypeSampledImage %type_image_u32_2d_0000 +%type_image_u32_2d_0002 = OpTypeImage %u32 2D 0 0 0 2 Unknown +%ptr_image_u32_2d_0002 = OpTypePointer UniformConstant %type_image_u32_2d_0002 +%uniform_image_u32_2d_0002 = OpVariable %ptr_image_u32_2d_0002 UniformConstant %type_image_s32_3d_0001 = OpTypeImage %s32 3D 0 0 0 1 Unknown %ptr_image_s32_3d_0001 = OpTypePointer UniformConstant %type_image_s32_3d_0001 @@ -253,17 +255,14 @@ OpDecorate %uniform_sampler Binding 0 %type_image_f32_2d_0002 = OpTypeImage %f32 2D 0 0 0 2 Unknown %ptr_image_f32_2d_0002 = OpTypePointer UniformConstant %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 = OpVariable %ptr_image_f32_2d_0002 UniformConstant -%type_sampled_image_f32_2d_0002 = OpTypeSampledImage %type_image_f32_2d_0002 %type_image_s32_2d_0002 = OpTypeImage %s32 2D 0 0 0 2 Unknown %ptr_image_s32_2d_0002 = OpTypePointer UniformConstant %type_image_s32_2d_0002 %uniform_image_s32_2d_0002 = OpVariable %ptr_image_s32_2d_0002 UniformConstant -%type_sampled_image_s32_2d_0002 = OpTypeSampledImage %type_image_s32_2d_0002 %type_image_f32_spd_0002 = OpTypeImage %f32 SubpassData 0 0 0 2 Unknown %ptr_image_f32_spd_0002 = OpTypePointer UniformConstant %type_image_f32_spd_0002 %uniform_image_f32_spd_0002 = OpVariable %ptr_image_f32_spd_0002 UniformConstant -%type_sampled_image_f32_spd_0002 = OpTypeSampledImage %type_image_f32_spd_0002 %type_image_f32_3d_0111 = OpTypeImage %f32 3D 0 1 1 1 Unknown %ptr_image_f32_3d_0111 = OpTypePointer UniformConstant %type_image_f32_3d_0111 @@ -278,7 +277,6 @@ OpDecorate %uniform_sampler Binding 0 %type_image_f32_cube_0102_rgba32f = OpTypeImage %f32 Cube 0 1 0 2 Rgba32f %ptr_image_f32_cube_0102_rgba32f = OpTypePointer UniformConstant %type_image_f32_cube_0102_rgba32f %uniform_image_f32_cube_0102_rgba32f = OpVariable %ptr_image_f32_cube_0102_rgba32f UniformConstant -%type_sampled_image_f32_cube_0102_rgba32f = OpTypeSampledImage %type_image_f32_cube_0102_rgba32f %type_sampler = OpTypeSampler %ptr_sampler = OpTypePointer UniformConstant %type_sampler @@ -299,6 +297,9 @@ OpDecorate %uniform_sampler Binding 0 %ptr_Image_f32 = OpTypePointer Image %f32 %ptr_image_f32_buffer_0002_r32ui = OpTypePointer Private %type_image_f32_buffer_0002_r32ui %private_image_f32_buffer_0002_r32ui = OpVariable %ptr_image_f32_buffer_0002_r32ui Private + +%ptr_input_flat_u32 = OpTypePointer Input %u32 +%input_flat_u32 = OpVariable %ptr_input_flat_u32 Input )"; if (env == SPV_ENV_UNIVERSAL_1_0) { @@ -311,7 +312,6 @@ OpDecorate %uniform_sampler Binding 0 %type_image_void_2d_0002 = OpTypeImage %void 2D 0 0 0 2 Unknown %ptr_image_void_2d_0002 = OpTypePointer UniformConstant %type_image_void_2d_0002 %uniform_image_void_2d_0002 = OpVariable %ptr_image_void_2d_0002 UniformConstant -%type_sampled_image_void_2d_0002 = OpTypeSampledImage %type_image_void_2d_0002 %type_image_f32_rect_0001 = OpTypeImage %f32 Rect 0 0 0 1 Unknown %ptr_image_f32_rect_0001 = OpTypePointer UniformConstant %type_image_f32_rect_0001 @@ -400,15 +400,15 @@ OpMemoryModel Physical32 OpenCL %uniform_image_f32_2d_0001 = OpVariable %ptr_image_f32_2d_0001 UniformConstant %type_sampled_image_f32_2d_0001 = OpTypeSampledImage %type_image_f32_2d_0001 -%type_image_f32_2d_0010 = OpTypeImage %f32 2D 0 0 1 0 Unknown -%ptr_image_f32_2d_0010 = OpTypePointer UniformConstant %type_image_f32_2d_0010 -%uniform_image_f32_2d_0010 = OpVariable %ptr_image_f32_2d_0010 UniformConstant -%type_sampled_image_f32_2d_0010 = OpTypeSampledImage %type_image_f32_2d_0010 +%type_image_f32_2d_0011 = OpTypeImage %f32 2D 0 0 1 1 Unknown +%ptr_image_f32_2d_0011 = OpTypePointer UniformConstant %type_image_f32_2d_0011 +%uniform_image_f32_2d_0011 = OpVariable %ptr_image_f32_2d_0011 UniformConstant +%type_sampled_image_f32_2d_0011 = OpTypeSampledImage %type_image_f32_2d_0011 -%type_image_f32_3d_0010 = OpTypeImage %f32 3D 0 0 1 0 Unknown -%ptr_image_f32_3d_0010 = OpTypePointer UniformConstant %type_image_f32_3d_0010 -%uniform_image_f32_3d_0010 = OpVariable %ptr_image_f32_3d_0010 UniformConstant -%type_sampled_image_f32_3d_0010 = OpTypeSampledImage %type_image_f32_3d_0010 +%type_image_f32_3d_0011 = OpTypeImage %f32 3D 0 0 1 1 Unknown +%ptr_image_f32_3d_0011 = OpTypePointer UniformConstant %type_image_f32_3d_0011 +%uniform_image_f32_3d_0011 = OpVariable %ptr_image_f32_3d_0011 UniformConstant +%type_sampled_image_f32_3d_0011 = OpTypeSampledImage %type_image_f32_3d_0011 %type_image_f32_rect_0001 = OpTypeImage %f32 Rect 0 0 0 1 Unknown %ptr_image_f32_rect_0001 = OpTypePointer UniformConstant %type_image_f32_rect_0001 @@ -431,12 +431,35 @@ OpFunctionEnd)"; return ss.str(); } +std::string GetKernelHeader() { + return R"( + OpCapability Kernel + OpCapability Addresses + OpCapability Linkage + OpMemoryModel Physical32 OpenCL + %void = OpTypeVoid + %func = OpTypeFunction %void + %f32 = OpTypeFloat 32 + %u32 = OpTypeInt 32 0 + )"; +} + +std::string TrivialMain() { + return R"( + %main = OpFunction %void None %func + %entry = OpLabel + OpReturn + OpFunctionEnd + )"; +} + std::string GetShaderHeader(const std::string& capabilities_and_extensions = "", bool include_entry_point = true) { std::ostringstream ss; ss << R"( OpCapability Shader OpCapability Int64 +OpCapability Float64 )"; ss << capabilities_and_extensions; @@ -457,9 +480,11 @@ OpMemoryModel Logical GLSL450 %func = OpTypeFunction %void %bool = OpTypeBool %f32 = OpTypeFloat 32 +%f64 = OpTypeFloat 64 %u32 = OpTypeInt 32 0 %u64 = OpTypeInt 64 0 %s32 = OpTypeInt 32 1 +%s64 = OpTypeInt 64 1 )"; return ss.str(); @@ -481,8 +506,7 @@ TEST_F(ValidateImage, TypeImageWrongSampledType) { TEST_F(ValidateImage, TypeImageVoidSampledTypeVulkan) { const std::string code = GetShaderHeader() + R"( %img_type = OpTypeImage %void 2D 0 0 0 1 Unknown -%void_func = OpTypeFunction %void -%main = OpFunction %void None %void_func +%main = OpFunction %void None %func %main_lab = OpLabel OpReturn OpFunctionEnd @@ -492,15 +516,131 @@ OpFunctionEnd CompileSuccessfully(code, env); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Expected Sampled Type to be a 32-bit int " - "or float scalar type for Vulkan environment")); + AnyVUID("VUID-StandaloneSpirv-OpTypeImage-04656")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Sampled Type to be a 32-bit int, 64-bit int " + "or 32-bit float scalar type for Vulkan environment")); +} + +TEST_F(ValidateImage, TypeImageU32SampledTypeVulkan) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %u32 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImageI32SampledTypeVulkan) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %s32 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImageI64SampledTypeNoCapabilityVulkan) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %s64 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Capability Int64ImageEXT is required when using " + "Sampled Type of 64-bit int")); +} + +TEST_F(ValidateImage, TypeImageI64SampledTypeVulkan) { + const std::string code = GetShaderHeader( + "OpCapability Int64ImageEXT\nOpExtension " + "\"SPV_EXT_shader_image_int64\"\n") + + R"( +%img_type = OpTypeImage %s64 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImageU64SampledTypeNoCapabilityVulkan) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %u64 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Capability Int64ImageEXT is required when using " + "Sampled Type of 64-bit int")); } TEST_F(ValidateImage, TypeImageU64SampledTypeVulkan) { - const std::string code = GetShaderHeader() + R"( + const std::string code = GetShaderHeader( + "OpCapability Int64ImageEXT\nOpExtension " + "\"SPV_EXT_shader_image_int64\"\n") + + R"( %img_type = OpTypeImage %u64 2D 0 0 0 1 Unknown -%void_func = OpTypeFunction %void -%main = OpFunction %void None %void_func +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImageF32SampledTypeVulkan) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %f32 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImageF64SampledTypeVulkan) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %f64 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func %main_lab = OpLabel OpReturn OpFunctionEnd @@ -510,8 +650,32 @@ OpFunctionEnd CompileSuccessfully(code, env); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Expected Sampled Type to be a 32-bit int " - "or float scalar type for Vulkan environment")); + AnyVUID("VUID-StandaloneSpirv-OpTypeImage-04656")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Sampled Type to be a 32-bit int, 64-bit int " + "or 32-bit float scalar type for Vulkan environment")); +} + +TEST_F(ValidateImage, TypeImageF64SampledTypeWithInt64Vulkan) { + const std::string code = GetShaderHeader( + "OpCapability Int64ImageEXT\nOpExtension " + "\"SPV_EXT_shader_image_int64\"\n") + + R"( +%img_type = OpTypeImage %f64 2D 0 0 0 1 Unknown +%main = OpFunction %void None %func +%main_lab = OpLabel +OpReturn +OpFunctionEnd +)"; + + const spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(code, env); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpTypeImage-04656")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Sampled Type to be a 32-bit int, 64-bit int " + "or 32-bit float scalar type for Vulkan environment")); } TEST_F(ValidateImage, TypeImageWrongDepth) { @@ -571,6 +735,83 @@ TEST_F(ValidateImage, TypeImageWrongSampledForSubpassData) { HasSubstr("Dim SubpassData requires Sampled to be 2")); } +TEST_F(ValidateImage, TypeImage_OpenCL_Sampled0_OK) { + const std::string code = GetKernelHeader() + R"( +%img_type = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_OPENCL_2_1)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImage_OpenCL_Sampled1_Invalid) { + const std::string code = GetKernelHeader() + R"( +%img_type = OpTypeImage %void 2D 0 0 0 1 Unknown ReadOnly +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_2_1)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampled must be 0 in the OpenCL environment.")); +} + +TEST_F(ValidateImage, TypeImage_OpenCL_Sampled2_Invalid) { + const std::string code = GetKernelHeader() + R"( +%img_type = OpTypeImage %void 2D 0 0 0 2 Unknown ReadOnly +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_2_1)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampled must be 0 in the OpenCL environment.")); +} + +TEST_F(ValidateImage, TypeImage_OpenCL_AccessQualifierMissing) { + const std::string code = GetKernelHeader() + R"( +%img_type = OpTypeImage %void 2D 0 0 0 0 Unknown +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_2_1)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("In the OpenCL environment, the optional Access " + "Qualifier must be present")); +} + +TEST_F(ValidateImage, TypeImage_Vulkan_Sampled1_OK) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %f32 2D 0 0 0 1 Unknown +)" + TrivialMain(); + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImage_Vulkan_Sampled2_OK) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %f32 2D 0 0 0 2 Rgba32f +)" + TrivialMain(); + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImage_Vulkan_Sampled0_Invalid) { + const std::string code = GetShaderHeader() + R"( +%img_type = OpTypeImage %f32 2D 0 0 0 0 Unknown +)" + TrivialMain(); + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpTypeImage-04657")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampled must be 1 or 2 in the Vulkan environment.")); +} + TEST_F(ValidateImage, TypeImageWrongFormatForSubpassData) { const std::string code = GetShaderHeader("OpCapability InputAttachment\n", false) + @@ -584,7 +825,44 @@ TEST_F(ValidateImage, TypeImageWrongFormatForSubpassData) { HasSubstr("Dim SubpassData requires format Unknown")); } -TEST_F(ValidateImage, TypeSampledImageNotImage) { +TEST_F(ValidateImage, TypeImageMultisampleStorageImage_MissingCapability) { + const std::string code = GetShaderHeader("", false) + + R"( +%img_type = OpTypeImage %f32 2D 0 0 1 2 Rgba32f +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()) << code; + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Capability StorageImageMultisample is required when " + "using multisampled storage image")); +} + +TEST_F(ValidateImage, TypeImageMultisampleStorageImage_UsesCapability) { + const std::string code = + GetShaderHeader("OpCapability StorageImageMultisample\n", false) + + R"( +%img_type = OpTypeImage %f32 2D 0 0 1 2 Rgba32f +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()) << code; + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeImageMultisampleSubpassData_OK) { + const std::string code = + GetShaderHeader("OpCapability InputAttachment\n", false) + + R"( +%img_type = OpTypeImage %f32 SubpassData 0 0 1 2 Unknown +)"; + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()) << code; + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, TypeSampledImage_NotImage_Error) { const std::string code = GetShaderHeader("", false) + R"( %simg_type = OpTypeSampledImage %f32 )"; @@ -595,6 +873,43 @@ TEST_F(ValidateImage, TypeSampledImageNotImage) { HasSubstr("Expected Image to be of type OpTypeImage")); } +TEST_F(ValidateImage, TypeSampledImage_Sampled0_Success) { + // This is ok in the OpenCL and universal environments. + // Vulkan will reject an OpTypeImage with Sampled=0, checked elsewhere. + const std::string code = GetShaderHeader() + R"( +%imty = OpTypeImage %f32 2D 0 0 0 0 Unknown +%simg_type = OpTypeSampledImage %imty +)" + TrivialMain(); + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); + EXPECT_EQ(getDiagnosticString(), ""); +} + +TEST_F(ValidateImage, TypeSampledImage_Sampled2_Error) { + const std::string code = GetShaderHeader() + R"( +%storage_image = OpTypeImage %f32 2D 0 0 0 2 Rgba32f +%simg_type = OpTypeSampledImage %storage_image +)" + TrivialMain(); + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampled image type requires an image type with " + "\"Sampled\" operand set to 0 or 1")); +} + +TEST_F(ValidateImage, TypeSampledImage_Sampled1_Success) { + const std::string code = GetShaderHeader() + R"( +%im = OpTypeImage %f32 2D 0 0 0 1 Unknown +%simg_type = OpTypeSampledImage %im +)" + TrivialMain(); + + CompileSuccessfully(code.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); + EXPECT_EQ(getDiagnosticString(), ""); +} + TEST_F(ValidateImage, SampledImageSuccess) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -646,31 +961,32 @@ TEST_F(ValidateImage, SampledImageNotImage) { } TEST_F(ValidateImage, SampledImageImageNotForSampling) { - const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_2d_0002 %img %sampler + const std::string code = GetShaderHeader() + R"( +%im_ty = OpTypeImage %f32 2D 0 0 0 2 Unknown +%sampler_ty = OpTypeSampler +%sampled_image_ty = OpTypeSampledImage %im_ty ; will fail here first! + +%ptr_im_ty = OpTypePointer UniformConstant %im_ty +%var_im = OpVariable %ptr_im_ty UniformConstant + +%ptr_sampler_ty = OpTypePointer UniformConstant %sampler_ty +%var_sampler = OpVariable %ptr_sampler_ty UniformConstant + +%main = OpFunction %void None %func +%entry = OpLabel +%im = OpLoad %im_ty %var_im +%sampler = OpLoad %sampler_ty %var_sampler +%sampled_image = OpSampledImage %sampled_image_ty %im %sampler +OpReturn +OpFunctionEnd )"; - CompileSuccessfully(GenerateShaderCode(body).c_str()); + CompileSuccessfully(code.c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Expected Image 'Sampled' parameter to be 0 or 1")); -} - -TEST_F(ValidateImage, SampledImageVulkanUnknownSampled) { - const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_u32_2d_0000 %img %sampler -)"; - - const spv_target_env env = SPV_ENV_VULKAN_1_0; - CompileSuccessfully(GenerateShaderCode(body, "", "Fragment", "", env), env); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Expected Image 'Sampled' parameter to " - "be 1 for Vulkan environment.")); + HasSubstr("Sampled image type requires an image type with " + "\"Sampled\" operand set to 0 or 1")) + << code; } TEST_F(ValidateImage, SampledImageNotSampler) { @@ -743,7 +1059,7 @@ TEST_F(ValidateImage, ImageTexelPointerImageNotResultTypePointer) { CompileSuccessfully(GenerateShaderCode(body).c_str()); ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), HasSubstr("Operand 141[%141] cannot be a " + EXPECT_THAT(getDiagnosticString(), HasSubstr("Operand 136[%136] cannot be a " "type")); } @@ -801,7 +1117,7 @@ TEST_F(ValidateImage, ImageTexelPointerImageCoordTypeBad) { TEST_F(ValidateImage, ImageTexelPointerImageCoordSizeBad) { const std::string body = R"( -%texel_ptr = OpImageTexelPointer %ptr_Image_u32 %uniform_image_u32_2d_0000 %u32vec3_012 %u32_0 +%texel_ptr = OpImageTexelPointer %ptr_Image_u32 %uniform_image_u32_2d_0002 %u32vec3_012 %u32_0 %sum = OpAtomicIAdd %u32 %texel_ptr %u32_1 %u32_0 %u32_1 )"; @@ -902,6 +1218,20 @@ TEST_F(ValidateImage, SampleImplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleImplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleExplicitLod %f32vec4 %simg %f32vec2_hh Sample %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampling operation is invalid for multisample image")); +} + TEST_F(ValidateImage, SampleImplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -1050,6 +1380,20 @@ TEST_F(ValidateImage, SampleExplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleExplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec2_hh Lod|Sample %f32_0 %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampling operation is invalid for multisample image")); +} + TEST_F(ValidateImage, SampleExplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -1182,19 +1526,6 @@ TEST_F(ValidateImage, LodWrongDim) { "2D, 3D or Cube")); } -TEST_F(ValidateImage, LodMultisampled) { - const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_2d_0010 %img %sampler -%res1 = OpImageSampleExplicitLod %f32vec4 %simg %f32vec2_00 Lod %f32_0)"; - - CompileSuccessfully(GenerateShaderCode(body).c_str()); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Image Operand Lod requires 'MS' parameter to be 0")); -} - TEST_F(ValidateImage, MinLodIncompatible) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -1227,20 +1558,6 @@ TEST_F(ValidateImage, ImplicitLodWithGrad) { "Image Operand Grad can only be used with ExplicitLod opcodes")); } -TEST_F(ValidateImage, SampleImplicitLod3DArrayedMultisampledSuccess) { - const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res1 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 -%res2 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset %s32vec3_012 -%res3 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %s32vec3_012 -)"; - - CompileSuccessfully(GenerateShaderCode(body).c_str()); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); -} - TEST_F(ValidateImage, SampleImplicitLodCubeArrayedSuccess) { const std::string body = R"( %img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 @@ -1285,20 +1602,6 @@ TEST_F(ValidateImage, SampleImplicitLodBiasWrongDim) { "2D, 3D or Cube")); } -TEST_F(ValidateImage, SampleImplicitLodBiasMultisampled) { - const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res1 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Bias %f32_0_25 -)"; - - CompileSuccessfully(GenerateShaderCode(body).c_str()); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Image Operand Bias requires 'MS' parameter to be 0")); -} - TEST_F(ValidateImage, SampleExplicitLodGradDxWrongType) { const std::string body = R"( %img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 @@ -1361,20 +1664,6 @@ TEST_F(ValidateImage, SampleExplicitLodGradDyWrongSize) { "Expected Image Operand Grad dy to have 3 components, but given 2")); } -TEST_F(ValidateImage, SampleExplicitLodGradMultisampled) { - const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res1 = OpImageSampleExplicitLod %f32vec4 %simg %f32vec4_0000 Grad %f32vec3_000 %f32vec3_000 -)"; - - CompileSuccessfully(GenerateShaderCode(body).c_str()); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Image Operand Grad requires 'MS' parameter to be 0")); -} - TEST_F(ValidateImage, SampleImplicitLodConstOffsetCubeDim) { const std::string body = R"( %img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 @@ -1393,10 +1682,10 @@ TEST_F(ValidateImage, SampleImplicitLodConstOffsetCubeDim) { TEST_F(ValidateImage, SampleImplicitLodConstOffsetWrongType) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset %f32vec3_000 +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec2_00 ConstOffset %f32vec2_00 )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); @@ -1409,26 +1698,26 @@ TEST_F(ValidateImage, SampleImplicitLodConstOffsetWrongType) { TEST_F(ValidateImage, SampleImplicitLodConstOffsetWrongSize) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset %s32vec2_01 +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec2_00 ConstOffset %s32vec3_012 )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Expected Image Operand ConstOffset to have 3 " - "components, but given 2")); + HasSubstr("Expected Image Operand ConstOffset to have 2 " + "components, but given 3")); } TEST_F(ValidateImage, SampleImplicitLodConstOffsetNotConst) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler %offset = OpSNegate %s32vec3 %s32vec3_012 -%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset %offset +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec2_00 ConstOffset %offset )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); @@ -1455,10 +1744,10 @@ TEST_F(ValidateImage, SampleImplicitLodOffsetCubeDim) { TEST_F(ValidateImage, SampleImplicitLodOffsetWrongType) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %f32vec3_000 +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %f32vec2_00 )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); @@ -1470,10 +1759,10 @@ TEST_F(ValidateImage, SampleImplicitLodOffsetWrongType) { TEST_F(ValidateImage, SampleImplicitLodOffsetWrongSize) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %s32vec2_01 +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %s32vec3_012 )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); @@ -1481,15 +1770,47 @@ TEST_F(ValidateImage, SampleImplicitLodOffsetWrongSize) { EXPECT_THAT( getDiagnosticString(), HasSubstr( - "Expected Image Operand Offset to have 3 components, but given 2")); + "Expected Image Operand Offset to have 2 components, but given 3")); +} + +TEST_F(ValidateImage, SampleImplicitLodVulkanOffsetWrongSize) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %s32vec2_01 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", SPV_ENV_VULKAN_1_0).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-Offset-04663")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Image Operand Offset can only be used with " + "OpImage*Gather operations")); +} + +TEST_F(ValidateImage, SampleImplicitLodVulkanOffsetWrongBeforeLegalization) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 Offset %s32vec2_01 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", SPV_ENV_VULKAN_1_0).c_str()); + getValidatorOptions()->before_hlsl_legalization = true; + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); } TEST_F(ValidateImage, SampleImplicitLodMoreThanOneOffset) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset|Offset %s32vec3_012 %s32vec3_012 +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset|Offset %s32vec2_01 %s32vec2_01 )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); @@ -1499,6 +1820,24 @@ TEST_F(ValidateImage, SampleImplicitLodMoreThanOneOffset) { "cannot be used together")); } +TEST_F(ValidateImage, SampleImplicitLodVulkanMoreThanOneOffset) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler +%res4 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 ConstOffset|Offset %s32vec2_01 %s32vec2_01 +)"; + + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", SPV_ENV_VULKAN_1_0).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-Offset-04662")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Image Operands Offset, ConstOffset, ConstOffsets " + "cannot be used together")); +} + TEST_F(ValidateImage, SampleImplicitLodMinLodWrongType) { const std::string body = R"( %img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 @@ -1528,21 +1867,6 @@ TEST_F(ValidateImage, SampleImplicitLodMinLodWrongDim) { "1D, 2D, 3D or Cube")); } -TEST_F(ValidateImage, SampleImplicitLodMinLodMultisampled) { - const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0111 %uniform_image_f32_3d_0111 -%sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_3d_0111 %img %sampler -%res1 = OpImageSampleImplicitLod %f32vec4 %simg %f32vec4_0000 MinLod %f32_0_25 -)"; - - CompileSuccessfully(GenerateShaderCode(body).c_str()); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Image Operand MinLod requires 'MS' parameter to be 0")); -} - TEST_F(ValidateImage, SampleProjExplicitLodSuccess2D) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -1620,6 +1944,20 @@ TEST_F(ValidateImage, SampleProjExplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleProjExplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleProjExplicitLod %f32vec4 %simg %f32vec2_hh Lod|Sample %f32_1 %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Image 'MS' parameter to be 0")); +} + TEST_F(ValidateImage, SampleProjExplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -1741,6 +2079,20 @@ TEST_F(ValidateImage, SampleProjImplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleProjImplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleProjImplicitLod %f32vec4 %simg %f32vec2_hh Sample %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Image 'MS' parameter to be 0")); +} + TEST_F(ValidateImage, SampleProjImplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -1848,6 +2200,21 @@ TEST_F(ValidateImage, SampleDrefImplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleDrefImplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleDrefImplicitLod %f32 %simg %f32vec2_hh %f32_1 Sample %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Dref sampling operation is invalid for multisample image")); +} + TEST_F(ValidateImage, SampleDrefImplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_u32_2d_0001 %uniform_image_u32_2d_0001 @@ -1971,6 +2338,21 @@ TEST_F(ValidateImage, SampleDrefExplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleDrefExplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleDrefExplicitLod %f32 %simg %f32vec2_hh %f32_1 Lod|Sample %f32_1 %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Dref sampling operation is invalid for multisample image")); +} + TEST_F(ValidateImage, SampleDrefExplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_s32_3d_0001 %uniform_image_s32_3d_0001 @@ -2095,6 +2477,21 @@ TEST_F(ValidateImage, SampleProjDrefImplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleProjDrefImplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleDrefExplicitLod %f32 %simg %f32vec2_hh %f32_1 Sample %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Dref sampling operation is invalid for multisample image")); +} + TEST_F(ValidateImage, SampleProjDrefImplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -2218,6 +2615,21 @@ TEST_F(ValidateImage, SampleProjDrefExplicitLodNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, SampleProjDrefExplicitLodMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageSampleDrefExplicitLod %f32 %simg %f32vec2_hh %f32_1 Lod|Sample %f32_1 %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("Dref sampling operation is invalid for multisample image")); +} + TEST_F(ValidateImage, SampleProjDrefExplicitLodWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_1d_0001 %uniform_image_f32_1d_0001 @@ -2294,6 +2706,23 @@ OpExtension "SPV_KHR_vulkan_memory_model" ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); } +TEST_F(ValidateImage, FetchMultisampledSuccess) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%res1 = OpImageFetch %f32vec4 %img %u32vec2_01 Sample %u32_1 +%res2 = OpImageFetch %f32vec4 %img %u32vec2_01 Sample|NonPrivateTexelKHR %u32_1 +)"; + + const std::string extra = R"( +OpCapability VulkanMemoryModelKHR +OpExtension "SPV_KHR_vulkan_memory_model" +)"; + CompileSuccessfully(GenerateShaderCode(body, extra, "Fragment", "", + SPV_ENV_UNIVERSAL_1_3, "VulkanKHR") + .c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); +} + TEST_F(ValidateImage, FetchWrongResultType) { const std::string body = R"( %img = OpLoad %type_image_f32_rect_0001 %uniform_image_f32_rect_0001 @@ -2349,7 +2778,7 @@ TEST_F(ValidateImage, FetchSampledImageDirectly) { TEST_F(ValidateImage, FetchNotSampled) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageFetch %u32vec4 %img %u32vec2_01 )"; @@ -2433,6 +2862,21 @@ TEST_F(ValidateImage, FetchLodNotInt) { "with OpImageFetch")); } +TEST_F(ValidateImage, FetchMultisampledMissingSample) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%res1 = OpImageFetch %f32vec4 %img %u32vec2_01 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()) + << GenerateShaderCode(body); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Image Operand Sample is required for operation on " + "multi-sampled image")) + << getDiagnosticString(); +} + TEST_F(ValidateImage, GatherSuccess) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -2494,6 +2938,20 @@ TEST_F(ValidateImage, GatherNotSampledImage) { HasSubstr("Expected Sampled Image to be of type OpTypeSampledImage")); } +TEST_F(ValidateImage, GatherMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageGather %f32vec4 %simg %f32vec4_0000 %u32_1 Sample %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Gather operation is invalid for multisample image")); +} + TEST_F(ValidateImage, GatherWrongSampledType) { const std::string body = R"( %img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 @@ -2578,6 +3036,40 @@ TEST_F(ValidateImage, GatherComponentNot32Bit) { HasSubstr("Expected Component to be 32-bit int scalar")); } +TEST_F(ValidateImage, GatherComponentSuccessVulkan) { + const std::string body = R"( +%img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_cube_0101 %img %sampler +%res1 = OpImageGather %f32vec4 %simg %f32vec4_0000 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(GenerateShaderCode(body, "", "Fragment", "", env).c_str(), + env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); +} + +TEST_F(ValidateImage, GatherComponentNotConstantVulkan) { + const std::string body = R"( +%input_u32 = OpLoad %u32 %input_flat_u32 +%img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_cube_0101 %img %sampler +%res1 = OpImageGather %f32vec4 %simg %f32vec4_0000 %input_u32 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(GenerateShaderCode(body, "", "Fragment", "", env).c_str(), + env); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpImageGather-04664")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Component Operand to be a const object for " + "Vulkan environment")); +} + TEST_F(ValidateImage, GatherDimCube) { const std::string body = R"( %img = OpLoad %type_image_f32_cube_0101 %uniform_image_f32_cube_0101 @@ -2709,6 +3201,20 @@ OpExtension "SPV_KHR_vulkan_memory_model" ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); } +TEST_F(ValidateImage, DrefGatherMultisampleError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%sampler = OpLoad %type_sampler %uniform_sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler +%res1 = OpImageDrefGather %f32vec4 %simg %f32vec4_0000 %f32_1 Sample %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Gather operation is invalid for multisample image")); +} + TEST_F(ValidateImage, DrefGatherVoidSampledType) { const std::string body = R"( %img = OpLoad %type_image_void_2d_0001 %uniform_image_void_2d_0001 @@ -2740,7 +3246,7 @@ TEST_F(ValidateImage, DrefGatherWrongDrefType) { TEST_F(ValidateImage, ReadSuccess1) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 )"; @@ -2783,7 +3289,7 @@ TEST_F(ValidateImage, ReadSuccess4) { TEST_F(ValidateImage, ReadNeedCapabilityStorageImageReadWithoutFormat) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 )"; @@ -2793,7 +3299,7 @@ TEST_F(ValidateImage, ReadNeedCapabilityStorageImageReadWithoutFormat) { TEST_F(ValidateImage, ReadNeedCapabilityStorageImageReadWithoutFormatVulkan) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 )"; @@ -2836,7 +3342,7 @@ TEST_F(ValidateImage, ReadNeedCapabilityImageCubeArray) { // TODO(atgoo@github.com) Disabled until the spec is clarified. TEST_F(ValidateImage, DISABLED_ReadWrongResultType) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %f32 %img %u32vec2_01 )"; @@ -2847,16 +3353,43 @@ TEST_F(ValidateImage, DISABLED_ReadWrongResultType) { HasSubstr("Expected Result Type to be int or float vector type")); } -// TODO(atgoo@github.com) Disabled until the spec is clarified. -TEST_F(ValidateImage, DISABLED_ReadWrongNumComponentsResultType) { +TEST_F(ValidateImage, ReadScalarResultType_Universal) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 -%res1 = OpImageRead %f32vec3 %img %u32vec2_01 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 +%res1 = OpImageRead %u32 %img %u32vec2_01 )"; const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; CompileSuccessfully(GenerateShaderCode(body, extra).c_str()); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_0)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, ReadUnusualNumComponentsResultType_Universal) { + const std::string body = R"( +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 +%res1 = OpImageRead %u32vec3 %img %u32vec2_01 +)"; + + const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; + CompileSuccessfully(GenerateShaderCode(body, extra).c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_0)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateImage, ReadWrongNumComponentsResultType_Vulkan) { + const std::string body = R"( +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 +%res1 = OpImageRead %u32vec3 %img %u32vec2_01 +)"; + + const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; + CompileSuccessfully( + GenerateShaderCode(body, extra, "Fragment", "", SPV_ENV_VULKAN_1_0) + .c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-Result-04780")); EXPECT_THAT(getDiagnosticString(), HasSubstr("Expected Result Type to have 4 components")); } @@ -2889,7 +3422,7 @@ TEST_F(ValidateImage, ReadImageSampled) { TEST_F(ValidateImage, ReadWrongSampledType) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %f32vec4 %img %u32vec2_01 )"; @@ -2916,7 +3449,7 @@ TEST_F(ValidateImage, ReadVoidSampledType) { TEST_F(ValidateImage, ReadWrongCoordinateType) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %f32vec2_00 )"; @@ -2929,7 +3462,7 @@ TEST_F(ValidateImage, ReadWrongCoordinateType) { TEST_F(ValidateImage, ReadCoordinateSizeTooSmall) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32_1 )"; @@ -2943,7 +3476,7 @@ TEST_F(ValidateImage, ReadCoordinateSizeTooSmall) { TEST_F(ValidateImage, WriteSuccess1) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 )"; @@ -2976,14 +3509,24 @@ OpImageWrite %img %u32vec3_012 %f32vec4_0000 TEST_F(ValidateImage, WriteSuccess4) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 -;TODO(atgoo@github.com) Is it legal to write to MS image without sample index? -OpImageWrite %img %u32vec2_01 %f32vec4_0000 +%img = OpLoad %type_image_f32_2d_0012 %uniform_image_f32_2d_0012 OpImageWrite %img %u32vec2_01 %f32vec4_0000 Sample %u32_1 )"; - const std::string extra = "\nOpCapability StorageImageWriteWithoutFormat\n"; - CompileSuccessfully(GenerateShaderCode(body, extra).c_str()); + const std::string extra = R"( + OpCapability StorageImageWriteWithoutFormat + OpCapability StorageImageMultisample + )"; + + const std::string declarations = R"( +%type_image_f32_2d_0012 = OpTypeImage %f32 2D 0 0 1 2 Unknown +%ptr_image_f32_2d_0012 = OpTypePointer UniformConstant %type_image_f32_2d_0012 +%uniform_image_f32_2d_0012 = OpVariable %ptr_image_f32_2d_0012 UniformConstant + )"; + CompileSuccessfully(GenerateShaderCode(body, extra, "Fragment", "", + SPV_ENV_UNIVERSAL_1_0, "GLSL450", + declarations) + .c_str()); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } @@ -3001,7 +3544,7 @@ OpImageWrite %img %u32vec2_01 %f32vec4_0000 TEST_F(ValidateImage, WriteNeedCapabilityStorageImageWriteWithoutFormat) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 )"; @@ -3011,7 +3554,7 @@ OpImageWrite %img %u32vec2_01 %u32vec4_0123 TEST_F(ValidateImage, WriteNeedCapabilityStorageImageWriteWithoutFormatVulkan) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 )"; @@ -3080,7 +3623,7 @@ OpImageWrite %img %u32vec2_01 %f32vec4_0000 TEST_F(ValidateImage, WriteWrongCoordinateType) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %f32vec2_00 %u32vec4_0123 )"; @@ -3093,7 +3636,7 @@ OpImageWrite %img %f32vec2_00 %u32vec4_0123 TEST_F(ValidateImage, WriteCoordinateSizeTooSmall) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32_1 %u32vec4_0123 )"; @@ -3107,7 +3650,7 @@ OpImageWrite %img %u32_1 %u32vec4_0123 TEST_F(ValidateImage, WriteTexelWrongType) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %img )"; @@ -3120,7 +3663,7 @@ OpImageWrite %img %u32vec2_01 %img TEST_F(ValidateImage, DISABLED_WriteTexelNotVector4) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec3_012 )"; @@ -3133,7 +3676,7 @@ OpImageWrite %img %u32vec2_01 %u32vec3_012 TEST_F(ValidateImage, WriteTexelWrongComponentType) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %f32vec4_0000 )"; @@ -3148,18 +3691,29 @@ OpImageWrite %img %u32vec2_01 %f32vec4_0000 TEST_F(ValidateImage, WriteSampleNotInteger) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0012 %uniform_image_f32_2d_0012 OpImageWrite %img %u32vec2_01 %f32vec4_0000 Sample %f32_1 )"; - const std::string extra = "\nOpCapability StorageImageWriteWithoutFormat\n"; - CompileSuccessfully(GenerateShaderCode(body, extra).c_str()); + const std::string extra = R"( + OpCapability StorageImageWriteWithoutFormat + OpCapability StorageImageMultisample + )"; + const std::string declarations = R"( +%type_image_f32_2d_0012 = OpTypeImage %f32 2D 0 0 1 2 Unknown +%ptr_image_f32_2d_0012 = OpTypePointer UniformConstant %type_image_f32_2d_0012 +%uniform_image_f32_2d_0012 = OpVariable %ptr_image_f32_2d_0012 UniformConstant + )"; + CompileSuccessfully(GenerateShaderCode(body, extra, "Fragment", "", + SPV_ENV_UNIVERSAL_1_0, "GLSL450", + declarations) + .c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Expected Image Operand Sample to be int scalar")); } -TEST_F(ValidateImage, SampleNotMultisampled) { +TEST_F(ValidateImage, WriteSampleNotMultisampled) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 OpImageWrite %img %u32vec2_01 %f32vec4_0000 Sample %u32_1 @@ -3175,18 +3729,16 @@ OpImageWrite %img %u32vec2_01 %f32vec4_0000 Sample %u32_1 TEST_F(ValidateImage, SampleWrongOpcode) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 %sampler = OpLoad %type_sampler %uniform_sampler -%simg = OpSampledImage %type_sampled_image_f32_2d_0010 %img %sampler +%simg = OpSampledImage %type_sampled_image_f32_2d_0011 %img %sampler %res1 = OpImageSampleExplicitLod %f32vec4 %simg %f32vec2_00 Sample %u32_1 )"; CompileSuccessfully(GenerateShaderCode(body).c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Image Operand Sample can only be used with " - "OpImageFetch, OpImageRead, OpImageWrite, " - "OpImageSparseFetch and OpImageSparseRead")); + HasSubstr("Sampling operation is invalid for multisample image")); } TEST_F(ValidateImage, SampleImageToImageSuccess) { @@ -3379,6 +3931,69 @@ TEST_F(ValidateImage, QuerySizeLodSampledImageDirectly) { "for OpImageQuerySizeLod")); } +TEST_F(ValidateImage, QuerySizeLodMultisampledError) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 +%res1 = OpImageQuerySizeLod %u32vec2 %img %u32_1 +)"; + + CompileSuccessfully(GenerateKernelCode(body).c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), HasSubstr("Image 'MS' must be 0")); +} + +TEST_F(ValidateImage, QuerySizeLodNonSampledUniversalSuccess) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 +%res1 = OpImageQuerySizeLod %u32vec2 %img %u32_1 +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); + EXPECT_EQ(getDiagnosticString(), ""); +} + +TEST_F(ValidateImage, QuerySizeLodVulkanNonSampledError) { + // Create a whole shader module. Avoid Vulkan incompatibility with + // SampledRrect images inserted by helper function GenerateShaderCode. + const std::string body = R"( +OpCapability Shader +OpCapability ImageQuery +OpMemoryModel Logical Simple +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft + +%f32 = OpTypeFloat 32 +%u32 = OpTypeInt 32 0 +%u32_0 = OpConstant %u32 0 +%u32vec2 = OpTypeVector %u32 2 +%void = OpTypeVoid +%voidfn = OpTypeFunction %void + +; Test with a storage image. +%type_image_f32_2d_0002 = OpTypeImage %f32 2D 0 0 0 2 Rgba32f +%ptr_image_f32_2d_0002 = OpTypePointer UniformConstant %type_image_f32_2d_0002 +%uniform_image_f32_2d_0002 = OpVariable %ptr_image_f32_2d_0002 UniformConstant + +%main = OpFunction %void None %voidfn +%entry = OpLabel +%img = OpLoad %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 +%res1 = OpImageQuerySizeLod %u32vec2 %img %u32_0 +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(body.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpImageQuerySizeLod-04659")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "OpImageQuerySizeLod must only consume an \"Image\" operand whose " + "type has its \"Sampled\" operand set to 1")); +} + TEST_F(ValidateImage, QuerySizeLodWrongImageDim) { const std::string body = R"( %img = OpLoad %type_image_f32_rect_0001 %uniform_image_f32_rect_0001 @@ -3391,17 +4006,6 @@ TEST_F(ValidateImage, QuerySizeLodWrongImageDim) { HasSubstr("Image 'Dim' must be 1D, 2D, 3D or Cube")); } -TEST_F(ValidateImage, QuerySizeLodMultisampled) { - const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 -%res1 = OpImageQuerySizeLod %u32vec2 %img %u32_1 -)"; - - CompileSuccessfully(GenerateKernelCode(body).c_str()); - ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); - EXPECT_THAT(getDiagnosticString(), HasSubstr("Image 'MS' must be 0")); -} - TEST_F(ValidateImage, QuerySizeLodWrongLodType) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -3416,7 +4020,7 @@ TEST_F(ValidateImage, QuerySizeLodWrongLodType) { TEST_F(ValidateImage, QuerySizeSuccess) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 %res1 = OpImageQuerySize %u32vec2 %img )"; @@ -3426,7 +4030,7 @@ TEST_F(ValidateImage, QuerySizeSuccess) { TEST_F(ValidateImage, QuerySizeWrongResultType) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 %res1 = OpImageQuerySize %f32vec2 %img )"; @@ -3439,7 +4043,7 @@ TEST_F(ValidateImage, QuerySizeWrongResultType) { TEST_F(ValidateImage, QuerySizeNotImage) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 %sampler = OpLoad %type_sampler %uniform_sampler %simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler %res1 = OpImageQuerySize %u32vec2 %sampler @@ -3453,7 +4057,7 @@ TEST_F(ValidateImage, QuerySizeNotImage) { TEST_F(ValidateImage, QuerySizeSampledImageDirectly) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 %sampler = OpLoad %type_sampler %uniform_sampler %simg = OpSampledImage %type_sampled_image_f32_2d_0001 %img %sampler %res1 = OpImageQuerySize %u32vec2 %simg @@ -3676,9 +4280,58 @@ TEST_F(ValidateImage, QueryLevelsWrongDim) { HasSubstr("Image 'Dim' must be 1D, 2D, 3D or Cube")); } +TEST_F(ValidateImage, QuerySizeLevelsNonSampledUniversalSuccess) { + const std::string body = R"( +%img = OpLoad %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 +%res1 = OpImageQueryLevels %u32 %img +)"; + + CompileSuccessfully(GenerateShaderCode(body).c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); + EXPECT_EQ(getDiagnosticString(), ""); +} + +TEST_F(ValidateImage, QuerySizeLevelsVulkanNonSampledError) { + // Create a whole shader module. Avoid Vulkan incompatibility with + // SampledRrect images inserted by helper function GenerateShaderCode. + const std::string body = R"( +OpCapability Shader +OpCapability ImageQuery +OpMemoryModel Logical Simple +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft + +%f32 = OpTypeFloat 32 +%u32 = OpTypeInt 32 0 +%void = OpTypeVoid +%voidfn = OpTypeFunction %void + +; Test with a storage image. +%type_image_f32_2d_0002 = OpTypeImage %f32 2D 0 0 0 2 Rgba32f +%ptr_image_f32_2d_0002 = OpTypePointer UniformConstant %type_image_f32_2d_0002 +%uniform_image_f32_2d_0002 = OpVariable %ptr_image_f32_2d_0002 UniformConstant + +%main = OpFunction %void None %voidfn +%entry = OpLabel +%img = OpLoad %type_image_f32_2d_0002 %uniform_image_f32_2d_0002 +%res1 = OpImageQueryLevels %u32 %img +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(body.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpImageQuerySizeLod-04659")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("OpImageQueryLevels must only consume an \"Image\" operand " + "whose type has its \"Sampled\" operand set to 1")); +} + TEST_F(ValidateImage, QuerySamplesSuccess) { const std::string body = R"( -%img = OpLoad %type_image_f32_2d_0010 %uniform_image_f32_2d_0010 +%img = OpLoad %type_image_f32_2d_0011 %uniform_image_f32_2d_0011 %res1 = OpImageQuerySamples %u32 %img )"; @@ -3688,7 +4341,7 @@ TEST_F(ValidateImage, QuerySamplesSuccess) { TEST_F(ValidateImage, QuerySamplesNot2D) { const std::string body = R"( -%img = OpLoad %type_image_f32_3d_0010 %uniform_image_f32_3d_0010 +%img = OpLoad %type_image_f32_3d_0011 %uniform_image_f32_3d_0011 %res1 = OpImageQuerySamples %u32 %img )"; @@ -3766,6 +4419,102 @@ OpExecutionMode %main DerivativeGroupLinearNV ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } +TEST_F(ValidateImage, QueryLodUniversalSuccess) { + // Create a whole shader module. Avoid Vulkan incompatibility with + // SampledRrect images inserted by helper function GenerateShaderCode. + const std::string body = R"( +OpCapability Shader +OpCapability ImageQuery +OpMemoryModel Logical Simple +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft + +OpDecorate %uniform_image_f32_2d_0000 DescriptorSet 0 +OpDecorate %uniform_image_f32_2d_0000 Binding 0 +OpDecorate %sampler DescriptorSet 0 +OpDecorate %sampler Binding 1 + +%f32 = OpTypeFloat 32 +%f32vec2 = OpTypeVector %f32 2 +%f32vec2_null = OpConstantNull %f32vec2 +%u32 = OpTypeInt 32 0 +%u32vec2 = OpTypeVector %u32 2 +%void = OpTypeVoid +%voidfn = OpTypeFunction %void + +; Test with an image with sampled = 0 +%type_image_f32_2d_0000 = OpTypeImage %f32 2D 0 0 0 0 Rgba32f +%ptr_image_f32_2d_0000 = OpTypePointer UniformConstant %type_image_f32_2d_0000 +%uniform_image_f32_2d_0000 = OpVariable %ptr_image_f32_2d_0000 UniformConstant +%sampled_image_ty = OpTypeSampledImage %type_image_f32_2d_0000 + +%sampler_ty = OpTypeSampler +%ptr_sampler_ty = OpTypePointer UniformConstant %sampler_ty +%sampler = OpVariable %ptr_sampler_ty UniformConstant + + +%main = OpFunction %void None %voidfn +%entry = OpLabel +%img = OpLoad %type_image_f32_2d_0000 %uniform_image_f32_2d_0000 +%s = OpLoad %sampler_ty %sampler +%simg = OpSampledImage %sampled_image_ty %img %s +%res1 = OpImageQueryLod %f32vec2 %simg %f32vec2_null +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(body.c_str()); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); +} + +TEST_F(ValidateImage, QueryLodVulkanNonSampledError) { + // Create a whole shader module. Avoid Vulkan incompatibility with + // SampledRrect images inserted by helper function GenerateShaderCode. + const std::string body = R"( +OpCapability Shader +OpCapability ImageQuery +OpMemoryModel Logical Simple +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft + +OpDecorate %sampled_image DescriptorSet 0 +OpDecorate %sampled_image Binding 0 + +%f32 = OpTypeFloat 32 +%f32vec2 = OpTypeVector %f32 2 +%f32vec2_null = OpConstantNull %f32vec2 +%u32 = OpTypeInt 32 0 +%u32vec2 = OpTypeVector %u32 2 +%void = OpTypeVoid +%voidfn = OpTypeFunction %void + +; Test with an image with Sampled = 2 +; In Vulkan it Sampled must be 1 or 2, checked in another part of the +; validation flow. +%type_image_f32_2d_0002 = OpTypeImage %f32 2D 0 0 0 2 Rgba32f + +; Expect to fail here. +%sampled_image_ty = OpTypeSampledImage %type_image_f32_2d_0002 +%ptr_sampled_image_ty = OpTypePointer UniformConstant %sampled_image_ty +%sampled_image = OpVariable %ptr_sampled_image_ty UniformConstant + +%main = OpFunction %void None %voidfn +%entry = OpLabel +%simg = OpLoad %sampled_image_ty %sampled_image +%res1 = OpImageQueryLod %f32vec2 %simg %f32vec2_null +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(body.c_str()); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpTypeImage-04657")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Sampled image type requires an image type with " + "\"Sampled\" operand set to 0 or 1")); +} + TEST_F(ValidateImage, QueryLodComputeShaderDerivativesMissingMode) { const std::string body = R"( %img = OpLoad %type_image_f32_2d_0001 %uniform_image_f32_2d_0001 @@ -4453,7 +5202,7 @@ TEST_F(ValidateImage, SparseTexelsResidentResultTypeNotBool) { TEST_F(ValidateImage, MakeTexelVisibleKHRSuccessImageRead) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 MakeTexelVisibleKHR|NonPrivateTexelKHR %u32_2 )"; @@ -4511,7 +5260,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, MakeTexelVisibleKHRFailureMissingNonPrivate) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 MakeTexelVisibleKHR %u32_1 )"; @@ -4532,7 +5281,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, MakeTexelAvailableKHRSuccessImageWrite) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 MakeTexelAvailableKHR|NonPrivateTexelKHR %u32_2 )"; @@ -4572,7 +5321,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, MakeTexelAvailableKHRFailureMissingNonPrivate) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 MakeTexelAvailableKHR %u32_1 )"; @@ -4593,7 +5342,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, VulkanMemoryModelDeviceScopeImageWriteBad) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 MakeTexelAvailableKHR|NonPrivateTexelKHR %u32_1 )"; @@ -4615,7 +5364,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, VulkanMemoryModelDeviceScopeImageWriteGood) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 MakeTexelAvailableKHR|NonPrivateTexelKHR %u32_1 )"; @@ -4633,7 +5382,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, VulkanMemoryModelDeviceScopeImageReadBad) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 MakeTexelVisibleKHR|NonPrivateTexelKHR %u32_1 )"; @@ -4655,7 +5404,7 @@ OpExtension "SPV_KHR_vulkan_memory_model" TEST_F(ValidateImage, VulkanMemoryModelDeviceScopeImageReadGood) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 MakeTexelVisibleKHR|NonPrivateTexelKHR %u32_1 )"; @@ -4708,7 +5457,7 @@ TEST_F(ValidateImage, Issue2463NoSegFault) { TEST_F(ValidateImage, SignExtendV13Bad) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 SignExtend )"; @@ -4719,7 +5468,7 @@ TEST_F(ValidateImage, SignExtendV13Bad) { TEST_F(ValidateImage, ZeroExtendV13Bad) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 ZeroExtend )"; @@ -4731,7 +5480,7 @@ TEST_F(ValidateImage, ZeroExtendV13Bad) { TEST_F(ValidateImage, SignExtendScalarUIntTexelV14Good) { // Unsigned int sampled type const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32 %img %u32vec2_01 SignExtend )"; const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; @@ -4760,7 +5509,7 @@ TEST_F(ValidateImage, SignExtendScalarSIntTexelV14Good) { TEST_F(ValidateImage, SignExtendScalarVectorUIntTexelV14Good) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 SignExtend )"; const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; @@ -4792,7 +5541,7 @@ TEST_F(ValidateImage, SignExtendVectorSIntTexelV14Good) { TEST_F(ValidateImage, ZeroExtendScalarUIntTexelV14Good) { // Unsigned int sampled type const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32 %img %u32vec2_01 ZeroExtend )"; const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; @@ -4821,7 +5570,7 @@ TEST_F(ValidateImage, ZeroExtendScalarSIntTexelV14Good) { TEST_F(ValidateImage, ZeroExtendScalarVectorUIntTexelV14Good) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 ZeroExtend )"; const std::string extra = "\nOpCapability StorageImageReadWithoutFormat\n"; @@ -4849,7 +5598,7 @@ TEST_F(ValidateImage, ZeroExtendVectorSIntTexelV14Good) { TEST_F(ValidateImage, ReadLodAMDSuccess1) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 %res1 = OpImageRead %u32vec4 %img %u32vec2_01 Lod %u32_0 )"; @@ -4914,7 +5663,7 @@ TEST_F(ValidateImage, ReadLodAMDNeedCapability) { TEST_F(ValidateImage, WriteLodAMDSuccess1) { const std::string body = R"( -%img = OpLoad %type_image_u32_2d_0000 %uniform_image_u32_2d_0000 +%img = OpLoad %type_image_u32_2d_0002 %uniform_image_u32_2d_0002 OpImageWrite %img %u32vec2_01 %u32vec4_0123 Lod %u32_0 )"; @@ -5082,12 +5831,23 @@ static const std::string capabilities_and_extensions_image64 = R"( OpCapability Int64ImageEXT OpExtension "SPV_EXT_shader_image_int64" )"; +static const std::string capabilities_and_extensions_image64_atomic = R"( +OpCapability Int64Atomics +OpCapability Int64ImageEXT +OpExtension "SPV_EXT_shader_image_int64" +)"; static const std::string declarations_image64 = R"( %type_image_u64_buffer_0002_r64ui = OpTypeImage %u64 Buffer 0 0 0 2 R64ui %ptr_Image_u64 = OpTypePointer Image %u64 %ptr_image_u64_buffer_0002_r64ui = OpTypePointer Private %type_image_u64_buffer_0002_r64ui %private_image_u64_buffer_0002_r64ui = OpVariable %ptr_image_u64_buffer_0002_r64ui Private )"; +static const std::string declarations_image64i = R"( +%type_image_s64_buffer_0002_r64i = OpTypeImage %s64 Buffer 0 0 0 2 R64i +%ptr_Image_s64 = OpTypePointer Image %s64 +%ptr_image_s64_buffer_0002_r64i = OpTypePointer Private %type_image_s64_buffer_0002_r64i +%private_image_s64_buffer_0002_r64i = OpVariable %ptr_image_s64_buffer_0002_r64i Private +)"; TEST_F(ValidateImage, Image64MissingCapability) { CompileSuccessfully(GenerateShaderCode("", "", "Fragment", "", @@ -5115,11 +5875,11 @@ TEST_F(ValidateImage, ImageTexelPointer64Success) { %sum = OpAtomicIAdd %u64 %texel_ptr %u32_1 %u32_0 %u64_1 )"; - CompileSuccessfully(GenerateShaderCode(body, - capabilities_and_extensions_image64, - "Fragment", "", SPV_ENV_UNIVERSAL_1_3, - "GLSL450", declarations_image64) - .c_str()); + CompileSuccessfully( + GenerateShaderCode(body, capabilities_and_extensions_image64_atomic, + "Fragment", "", SPV_ENV_UNIVERSAL_1_3, "GLSL450", + declarations_image64) + .c_str()); ASSERT_EQ(SPV_SUCCESS, ValidateInstructions()); } @@ -5129,11 +5889,11 @@ TEST_F(ValidateImage, ImageTexelPointer64ResultTypeNotPointer) { %sum = OpAtomicIAdd %u64 %texel_ptr %u32_1 %u32_0 %u64_1 )"; - CompileSuccessfully(GenerateShaderCode(body, - capabilities_and_extensions_image64, - "Fragment", "", SPV_ENV_UNIVERSAL_1_3, - "GLSL450", declarations_image64) - .c_str()); + CompileSuccessfully( + GenerateShaderCode(body, capabilities_and_extensions_image64_atomic, + "Fragment", "", SPV_ENV_UNIVERSAL_1_3, "GLSL450", + declarations_image64) + .c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Expected Result Type to be OpTypePointer")); @@ -5145,11 +5905,11 @@ TEST_F(ValidateImage, ImageTexelPointer64ResultTypeNotImageClass) { %sum = OpAtomicIAdd %u64 %texel_ptr %u32_1 %u32_0 %u64_1 )"; - CompileSuccessfully(GenerateShaderCode(body, - capabilities_and_extensions_image64, - "Fragment", "", SPV_ENV_UNIVERSAL_1_3, - "GLSL450", declarations_image64) - .c_str()); + CompileSuccessfully( + GenerateShaderCode(body, capabilities_and_extensions_image64_atomic, + "Fragment", "", SPV_ENV_UNIVERSAL_1_3, "GLSL450", + declarations_image64) + .c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Expected Result Type to be OpTypePointer whose " @@ -5162,17 +5922,145 @@ TEST_F(ValidateImage, ImageTexelPointer64SampleNotZeroForImageWithMSZero) { %sum = OpAtomicIAdd %u64 %texel_ptr %u32_1 %u32_0 %u64_1 )"; - CompileSuccessfully(GenerateShaderCode(body, - capabilities_and_extensions_image64, - "Fragment", "", SPV_ENV_UNIVERSAL_1_3, - "GLSL450", declarations_image64) - .c_str()); + CompileSuccessfully( + GenerateShaderCode(body, capabilities_and_extensions_image64_atomic, + "Fragment", "", SPV_ENV_UNIVERSAL_1_3, "GLSL450", + declarations_image64) + .c_str()); ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Expected Sample for Image with MS 0 to be a valid " " for the value 0")); } +TEST_F(ValidateImage, ImageTexelPointerR32uiSuccessVulkan) { + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_u32 %private_image_u32_buffer_0002_r32ui %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully(GenerateShaderCode(body, "", "Fragment", "", env).c_str(), + env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); +} + +TEST_F(ValidateImage, ImageTexelPointerR32iSuccessVulkan) { + const std::string& declarations = R"( +%type_image_s32_buffer_0002_r32i = OpTypeImage %s32 Buffer 0 0 0 2 R32i +%ptr_Image_s32 = OpTypePointer Image %s32 +%ptr_image_s32_buffer_0002_r32i = OpTypePointer Private %type_image_s32_buffer_0002_r32i +%private_image_s32_buffer_0002_r32i = OpVariable %ptr_image_s32_buffer_0002_r32i Private +)"; + + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_s32 %private_image_s32_buffer_0002_r32i %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", env, "GLSL450", declarations) + .c_str(), + env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); +} + +TEST_F(ValidateImage, ImageTexelPointerR64uiSuccessVulkan) { + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_u64 %private_image_u64_buffer_0002_r64ui %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully( + GenerateShaderCode(body, capabilities_and_extensions_image64, "Fragment", + "", env, "GLSL450", declarations_image64) + .c_str(), + env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); +} + +TEST_F(ValidateImage, ImageTexelPointerR64iSuccessVulkan) { + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_s64 %private_image_s64_buffer_0002_r64i %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully( + GenerateShaderCode(body, capabilities_and_extensions_image64, "Fragment", + "", env, "GLSL450", declarations_image64i) + .c_str(), + env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); +} + +TEST_F(ValidateImage, ImageTexelPointerR32fSuccessVulkan) { + const std::string& declarations = R"( +%type_image_f32_buffer_0002_r32f = OpTypeImage %f32 Buffer 0 0 0 2 R32f +%ptr_image_f32_buffer_0002_r32f = OpTypePointer Private %type_image_f32_buffer_0002_r32f +%private_image_f32_buffer_0002_r32f = OpVariable %ptr_image_f32_buffer_0002_r32f Private +)"; + + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_f32 %private_image_f32_buffer_0002_r32f %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", env, "GLSL450", declarations) + .c_str(), + env); + ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(env)); +} + +TEST_F(ValidateImage, ImageTexelPointerRgba32iVulkan) { + const std::string& declarations = R"( +%type_image_s32_buffer_0002_rgba32i = OpTypeImage %s32 Buffer 0 0 0 2 Rgba32i +%ptr_Image_s32 = OpTypePointer Image %s32 +%ptr_image_s32_buffer_0002_rgba32i = OpTypePointer Private %type_image_s32_buffer_0002_rgba32i +%private_image_s32_buffer_0002_rgba32i = OpVariable %ptr_image_s32_buffer_0002_rgba32i Private +)"; + + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_s32 %private_image_s32_buffer_0002_rgba32i %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", env, "GLSL450", declarations) + .c_str(), + env); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpImageTexelPointer-04658")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected the Image Format in Image to be R64i, R64ui, " + "R32f, R32i, or R32ui for Vulkan environment")); +} + +TEST_F(ValidateImage, ImageTexelPointerRgba16fVulkan) { + const std::string& declarations = R"( +%type_image_s32_buffer_0002_rgba16f = OpTypeImage %s32 Buffer 0 0 0 2 Rgba16f +%ptr_Image_s32 = OpTypePointer Image %s32 +%ptr_image_s32_buffer_0002_rgba16f = OpTypePointer Private %type_image_s32_buffer_0002_rgba16f +%private_image_s32_buffer_0002_rgba16f = OpVariable %ptr_image_s32_buffer_0002_rgba16f Private +)"; + + const std::string body = R"( +%texel_ptr = OpImageTexelPointer %ptr_Image_s32 %private_image_s32_buffer_0002_rgba16f %u32_0 %u32_0 +)"; + + spv_target_env env = SPV_ENV_VULKAN_1_0; + CompileSuccessfully( + GenerateShaderCode(body, "", "Fragment", "", env, "GLSL450", declarations) + .c_str(), + env); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpImageTexelPointer-04658")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected the Image Format in Image to be R64i, R64ui, " + "R32f, R32i, or R32ui for Vulkan environment")); +} + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_layout_test.cpp b/third_party/spirv-tools/test/val/val_layout_test.cpp index 43fa0469b5..d34c97f9cf 100644 --- a/third_party/spirv-tools/test/val/val_layout_test.cpp +++ b/third_party/spirv-tools/test/val/val_layout_test.cpp @@ -667,57 +667,6 @@ TEST_F(ValidateLayout, ModuleProcessedInvalidInBasicBlock) { HasSubstr("ModuleProcessed cannot appear in a function declaration")); } -TEST_F(ValidateLayout, WebGPUCallerBeforeCalleeBad) { - char str[] = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint GLCompute %main "main" -%void = OpTypeVoid -%voidfn = OpTypeFunction %void -%main = OpFunction %void None %voidfn -%1 = OpLabel -%2 = OpFunctionCall %void %callee - OpReturn - OpFunctionEnd -%callee = OpFunction %void None %voidfn -%3 = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(str, SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, functions need to be defined before being " - "called.\n %5 = OpFunctionCall %void %6\n")); -} - -TEST_F(ValidateLayout, WebGPUCalleeBeforeCallerGood) { - char str[] = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint GLCompute %main "main" -%void = OpTypeVoid -%voidfn = OpTypeFunction %void -%callee = OpFunction %void None %voidfn -%3 = OpLabel - OpReturn - OpFunctionEnd -%main = OpFunction %void None %voidfn -%1 = OpLabel -%2 = OpFunctionCall %void %callee - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(str, SPV_ENV_WEBGPU_0); - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - // TODO(umar): Test optional instructions } // namespace diff --git a/third_party/spirv-tools/test/val/val_limits_test.cpp b/third_party/spirv-tools/test/val/val_limits_test.cpp index 0ef61e21bf..8fb80a46af 100644 --- a/third_party/spirv-tools/test/val/val_limits_test.cpp +++ b/third_party/spirv-tools/test/val/val_limits_test.cpp @@ -212,6 +212,7 @@ TEST_F(ValidateLimits, SwitchNumBranchesGood) { %5 = OpFunction %1 None %2 %7 = OpLabel %8 = OpIAdd %3 %4 %4 + OpSelectionMerge %10 None OpSwitch %4 %10)"; // Now add the (literal, label) pairs @@ -240,6 +241,7 @@ TEST_F(ValidateLimits, SwitchNumBranchesBad) { %5 = OpFunction %1 None %2 %7 = OpLabel %8 = OpIAdd %3 %4 %4 + OpSelectionMerge %10 None OpSwitch %4 %10)"; // Now add the (literal, label) pairs @@ -271,6 +273,7 @@ TEST_F(ValidateLimits, CustomizedSwitchNumBranchesGood) { %5 = OpFunction %1 None %2 %7 = OpLabel %8 = OpIAdd %3 %4 %4 + OpSelectionMerge %10 None OpSwitch %4 %10)"; // Now add the (literal, label) pairs @@ -301,6 +304,7 @@ TEST_F(ValidateLimits, CustomizedSwitchNumBranchesBad) { %5 = OpFunction %1 None %2 %7 = OpLabel %8 = OpIAdd %3 %4 %4 + OpSelectionMerge %10 None OpSwitch %4 %10)"; // Now add the (literal, label) pairs diff --git a/third_party/spirv-tools/test/val/val_memory_test.cpp b/third_party/spirv-tools/test/val/val_memory_test.cpp index b32867b16c..9799b404b0 100644 --- a/third_party/spirv-tools/test/val/val_memory_test.cpp +++ b/third_party/spirv-tools/test/val/val_memory_test.cpp @@ -22,6 +22,16 @@ #include "test/val/val_code_generator.h" #include "test/val/val_fixtures.h" +// For pretty-printing tuples with spv_target_env. +std::ostream& operator<<(std::ostream& stream, spv_target_env target) +{ + switch (target) { + case SPV_ENV_UNIVERSAL_1_3: return stream << "SPV_ENV_UNIVERSAL_1_3"; + case SPV_ENV_UNIVERSAL_1_4: return stream << "SPV_ENV_UNIVERSAL_1_4"; + default: return stream << (unsigned)target; + } +} + namespace spvtools { namespace val { namespace { @@ -51,14 +61,14 @@ OpFunctionEnd )"; CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_1); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-UniformConstant-04655")); EXPECT_THAT( getDiagnosticString(), - HasSubstr("From Vulkan spec, section 14.5.2:\n" - "Variables identified with the UniformConstant storage class " + HasSubstr("Variables identified with the UniformConstant storage class " "are used only as handles to refer to opaque resources. Such " "variables must be typed as OpTypeImage, OpTypeSampler, " - "OpTypeSampledImage, OpTypeAccelerationStructureNV, " - "OpTypeAccelerationStructureKHR, OpTypeRayQueryProvisionalKHR, " + "OpTypeSampledImage, OpTypeAccelerationStructureKHR, " "or an array of one of these types.")); } @@ -105,14 +115,14 @@ OpFunctionEnd )"; CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_1); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-UniformConstant-04655")); EXPECT_THAT( getDiagnosticString(), - HasSubstr("From Vulkan spec, section 14.5.2:\n" - "Variables identified with the UniformConstant storage class " + HasSubstr("Variables identified with the UniformConstant storage class " "are used only as handles to refer to opaque resources. Such " "variables must be typed as OpTypeImage, OpTypeSampler, " - "OpTypeSampledImage, OpTypeAccelerationStructureNV, " - "OpTypeAccelerationStructureKHR, OpTypeRayQueryProvisionalKHR, " + "OpTypeSampledImage, OpTypeAccelerationStructureKHR, " "or an array of one of these types.")); } @@ -362,192 +372,6 @@ OpFunctionEnd EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } -TEST_F(ValidateMemory, WebGPUInitializerWithOutputStorageClassesGood) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Output %float -%init_val = OpConstant %float 1.0 -%1 = OpVariable %float_ptr Output %init_val -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%2 = OpLabel -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateMemory, WebGPUInitializerWithFunctionStorageClassesGood) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Function %float -%init_val = OpConstant %float 1.0 -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%1 = OpLabel -%2 = OpVariable %float_ptr Function %init_val -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateMemory, WebGPUInitializerWithPrivateStorageClassesGood) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Private %float -%init_val = OpConstant %float 1.0 -%1 = OpVariable %float_ptr Private %init_val -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%2 = OpLabel -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateMemory, WebGPUInitializerWithDisallowedStorageClassesBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Uniform %float -%init_val = OpConstant %float 1.0 -%1 = OpVariable %float_ptr Uniform %init_val -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%2 = OpLabel -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("OpVariable, '5[%5]', has a disallowed initializer & " - "storage class combination.\nFrom WebGPU spec:\nVariable " - "declarations that include initializers must have one of the " - "following storage classes: Output, Private, or Function\n %5 " - "= OpVariable %_ptr_Uniform_float Uniform %float_1\n")); -} - -TEST_F(ValidateMemory, WebGPUOutputStorageClassWithoutInitializerBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Output %float -%1 = OpVariable %float_ptr Output -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%2 = OpLabel -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("OpVariable, '4[%4]', must have an initializer.\n" - "From WebGPU execution environment spec:\n" - "All variables in the following storage classes must have an " - "initializer: Output, Private, or Function\n" - " %4 = OpVariable %_ptr_Output_float Output\n")); -} - -TEST_F(ValidateMemory, WebGPUFunctionStorageClassWithoutInitializerBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Function %float -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%1 = OpLabel -%2 = OpVariable %float_ptr Function -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("OpVariable, '7[%7]', must have an initializer.\n" - "From WebGPU execution environment spec:\n" - "All variables in the following storage classes must have an " - "initializer: Output, Private, or Function\n" - " %7 = OpVariable %_ptr_Function_float Function\n")); -} - -TEST_F(ValidateMemory, WebGPUPrivateStorageClassWithoutInitializerBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%float = OpTypeFloat 32 -%float_ptr = OpTypePointer Private %float -%1 = OpVariable %float_ptr Private -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%2 = OpLabel -OpReturn -OpFunctionEnd -)"; - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("OpVariable, '4[%4]', must have an initializer.\n" - "From WebGPU execution environment spec:\n" - "All variables in the following storage classes must have an " - "initializer: Output, Private, or Function\n" - " %4 = OpVariable %_ptr_Private_float Private\n")); -} - TEST_F(ValidateMemory, VulkanInitializerWithOutputStorageClassesGood) { std::string spirv = R"( OpCapability Shader @@ -630,12 +454,15 @@ OpFunctionEnd )"; CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_1); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpVariable-04651")); EXPECT_THAT( getDiagnosticString(), HasSubstr("OpVariable, '5[%5]', has a disallowed initializer & " "storage class combination.\nFrom Vulkan spec:\nVariable " "declarations that include initializers must have one of the " - "following storage classes: Output, Private, or Function\n %5 " + "following storage classes: Output, Private, Function or " + "Workgroup\n %5 " "= OpVariable %_ptr_Input_float Input %float_1\n")); } @@ -2280,38 +2107,6 @@ OpFunctionEnd "%_ptr_UniformConstant__runtimearr_2 UniformConstant\n")); } -TEST_F(ValidateMemory, WebGPURTAOutsideOfStructBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%sampler_t = OpTypeSampler -%array_t = OpTypeRuntimeArray %sampler_t -%array_ptr = OpTypePointer UniformConstant %array_t -%2 = OpVariable %array_ptr UniformConstant -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr( - "OpVariable, '5[%5]', is attempting to create memory for an " - "illegal type, OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray " - "can only appear as the final member of an OpTypeStruct, thus cannot " - "be instantiated via OpVariable\n %5 = OpVariable " - "%_ptr_UniformConstant__runtimearr_2 UniformConstant\n")); -} - TEST_F(ValidateMemory, VulkanRTAOutsideOfStructWithRuntimeDescriptorArrayGood) { std::string spirv = R"( OpCapability Shader @@ -2401,34 +2196,6 @@ OpFunctionEnd EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_1)); } -TEST_F(ValidateMemory, WebGPURTAInsideStorageBufferStructGood) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -OpDecorate %array_t ArrayStride 4 -OpMemberDecorate %struct_t 0 Offset 0 -OpDecorate %struct_t Block -%uint_t = OpTypeInt 32 0 -%array_t = OpTypeRuntimeArray %uint_t -%struct_t = OpTypeStruct %array_t -%struct_ptr = OpTypePointer StorageBuffer %struct_t -%2 = OpVariable %struct_ptr StorageBuffer -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - TEST_F(ValidateMemory, VulkanRTAInsideWrongStorageClassStructBad) { std::string spirv = R"( OpCapability Shader @@ -2458,36 +2225,6 @@ OpFunctionEnd "OpVariable %_ptr_Workgroup__struct_4 Workgroup\n")); } -TEST_F(ValidateMemory, WebGPURTAInsideWrongStorageClassStructBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%uint_t = OpTypeInt 32 0 -%array_t = OpTypeRuntimeArray %uint_t -%struct_t = OpTypeStruct %array_t -%struct_ptr = OpTypePointer Workgroup %struct_t -%2 = OpVariable %struct_ptr Workgroup -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("For WebGPU, OpTypeStruct variables containing " - "OpTypeRuntimeArray must have storage class of StorageBuffer\n " - " %6 = OpVariable %_ptr_Workgroup__struct_4 Workgroup\n")); -} - TEST_F(ValidateMemory, VulkanRTAInsideStorageBufferStructWithoutBlockBad) { std::string spirv = R"( OpCapability Shader @@ -2516,36 +2253,6 @@ OpFunctionEnd "%_ptr_StorageBuffer__struct_4 StorageBuffer\n")); } -TEST_F(ValidateMemory, WebGPURTAInsideStorageBufferStructWithoutBlockBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%uint_t = OpTypeInt 32 0 -%array_t = OpTypeRuntimeArray %uint_t -%struct_t = OpTypeStruct %array_t -%struct_ptr = OpTypePointer StorageBuffer %struct_t -%2 = OpVariable %struct_ptr StorageBuffer -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, an OpTypeStruct variable containing an " - "OpTypeRuntimeArray must be decorated with Block if it " - "has storage class StorageBuffer.\n %6 = OpVariable " - "%_ptr_StorageBuffer__struct_4 StorageBuffer\n")); -} - TEST_F(ValidateMemory, VulkanRTAInsideUniformStructGood) { std::string spirv = R"( OpCapability Shader @@ -2572,39 +2279,6 @@ OpFunctionEnd EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_1)); } -TEST_F(ValidateMemory, WebGPURTAInsideUniformStructBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -OpDecorate %array_t ArrayStride 4 -OpMemberDecorate %struct_t 0 Offset 0 -OpDecorate %struct_t Block -%uint_t = OpTypeInt 32 0 -%array_t = OpTypeRuntimeArray %uint_t -%struct_t = OpTypeStruct %array_t -%struct_ptr = OpTypePointer Uniform %struct_t -%2 = OpVariable %struct_ptr Uniform -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("For WebGPU, OpTypeStruct variables containing " - "OpTypeRuntimeArray must have storage class of StorageBuffer\n " - " %6 = OpVariable %_ptr_Uniform__struct_3 Uniform\n")); -} - TEST_F(ValidateMemory, VulkanRTAInsideUniformStructWithoutBufferBlockBad) { std::string spirv = R"( OpCapability Shader @@ -2662,37 +2336,6 @@ OpFunctionEnd "OpTypeRuntimeArray %_runtimearr_2\n")); } -TEST_F(ValidateMemory, WebGPURTAInsideRTABad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%sampler_t = OpTypeSampler -%inner_array_t = OpTypeRuntimeArray %sampler_t -%array_t = OpTypeRuntimeArray %inner_array_t -%array_ptr = OpTypePointer UniformConstant %array_t -%2 = OpVariable %array_ptr UniformConstant -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr( - "OpTypeRuntimeArray Element Type '3[%_runtimearr_2]' is not " - "valid in WebGPU environments.\n %_runtimearr__runtimearr_2 = " - "OpTypeRuntimeArray %_runtimearr_2\n")); -} - TEST_F(ValidateMemory, VulkanRTAInsideRTAWithRuntimeDescriptorArrayBad) { std::string spirv = R"( OpCapability RuntimeDescriptorArrayEXT @@ -2853,38 +2496,6 @@ OpFunctionEnd "OpTypeArray %_runtimearr_4 %uint_1\n")); } -TEST_F(ValidateMemory, WebGPURTAInsideArrayBad) { - std::string spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%uint_t = OpTypeInt 32 0 -%dim = OpConstant %uint_t 1 -%sampler_t = OpTypeSampler -%inner_array_t = OpTypeRuntimeArray %sampler_t -%array_t = OpTypeArray %inner_array_t %dim -%array_ptr = OpTypePointer UniformConstant %array_t -%2 = OpVariable %array_ptr UniformConstant -%void = OpTypeVoid -%func_t = OpTypeFunction %void -%func = OpFunction %void None %func_t -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(spirv.c_str(), SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("OpTypeArray Element Type '5[%_runtimearr_4]' is not " - "valid in WebGPU environments.\n %_arr__runtimearr_4_uint_1 = " - "OpTypeArray %_runtimearr_4 %uint_1\n")); -} - TEST_F(ValidateMemory, VulkanRTAInsideArrayWithRuntimeDescriptorArrayBad) { std::string spirv = R"( OpCapability RuntimeDescriptorArrayEXT @@ -3843,9 +3454,10 @@ OpFunctionEnd } using ValidateSizedVariable = - spvtest::ValidateBase>; + spvtest::ValidateBase>; -CodeGenerator GetSizedVariableCodeGenerator(bool is_8bit) { +CodeGenerator GetSizedVariableCodeGenerator(bool is_8bit, bool buffer_block) { CodeGenerator generator; generator.capabilities_ = "OpCapability Shader\nOpCapability Linkage\n"; generator.extensions_ = @@ -3853,20 +3465,25 @@ CodeGenerator GetSizedVariableCodeGenerator(bool is_8bit) { "\"SPV_KHR_8bit_storage\"\n"; generator.memory_model_ = "OpMemoryModel Logical GLSL450\n"; if (is_8bit) { - generator.before_types_ = R"(OpDecorate %char_buffer_block BufferBlock -OpMemberDecorate %char_buffer_block 0 Offset 0 -)"; + generator.before_types_ = "OpMemberDecorate %char_buffer_block 0 Offset 0\n"; + if (buffer_block) + generator.before_types_ += "OpDecorate %char_buffer_block BufferBlock\n"; + generator.types_ = R"(%void = OpTypeVoid %char = OpTypeInt 8 0 %char4 = OpTypeVector %char 4 %char_buffer_block = OpTypeStruct %char )"; } else { - generator.before_types_ = R"(OpDecorate %half_buffer_block BufferBlock -OpDecorate %short_buffer_block BufferBlock -OpMemberDecorate %half_buffer_block 0 Offset 0 -OpMemberDecorate %short_buffer_block 0 Offset 0 -)"; + generator.before_types_ = + "OpMemberDecorate %half_buffer_block 0 Offset 0\n" + "OpMemberDecorate %short_buffer_block 0 Offset 0\n"; + if (buffer_block) { + generator.before_types_ += + "OpDecorate %half_buffer_block BufferBlock\n" + "OpDecorate %short_buffer_block BufferBlock\n"; + } + generator.types_ = R"(%void = OpTypeVoid %short = OpTypeInt 16 0 %half = OpTypeFloat 16 @@ -3889,6 +3506,10 @@ TEST_P(ValidateSizedVariable, Capability) { const std::string storage_class = std::get<0>(GetParam()); const std::string capability = std::get<1>(GetParam()); const std::string var_type = std::get<2>(GetParam()); + const spv_target_env target = std::get<3>(GetParam()); + + ASSERT_TRUE(target == SPV_ENV_UNIVERSAL_1_3 || + target == SPV_ENV_UNIVERSAL_1_4); bool type_8bit = false; if (var_type == "%char" || var_type == "%char4" || @@ -3896,7 +3517,16 @@ TEST_P(ValidateSizedVariable, Capability) { type_8bit = true; } - auto generator = GetSizedVariableCodeGenerator(type_8bit); + const bool buffer_block = var_type.find("buffer_block") != std::string::npos; + + auto generator = GetSizedVariableCodeGenerator(type_8bit, buffer_block); + + if (capability == "WorkgroupMemoryExplicitLayout8BitAccessKHR" || + capability == "WorkgroupMemoryExplicitLayout16BitAccessKHR") { + generator.extensions_ += + "OpExtension \"SPV_KHR_workgroup_memory_explicit_layout\"\n"; + } + generator.types_ += "%ptr_type = OpTypePointer " + storage_class + " " + var_type + "\n%var = OpVariable %ptr_type " + storage_class + "\n"; @@ -3926,7 +3556,6 @@ TEST_P(ValidateSizedVariable, Capability) { } storage_class_ok = true; } else if (storage_class == "Uniform") { - bool buffer_block = var_type.find("buffer_block") != std::string::npos; if (type_8bit) { capability_ok = capability == "UniformAndStorageBuffer8BitAccess" || (capability == "StorageBuffer8BitAccess" && buffer_block); @@ -3936,11 +3565,30 @@ TEST_P(ValidateSizedVariable, Capability) { (capability == "StorageBuffer16BitAccess" && buffer_block); } storage_class_ok = true; + } else if (storage_class == "Workgroup") { + if (type_8bit) { + capability_ok = + capability == "WorkgroupMemoryExplicitLayout8BitAccessKHR"; + } else { + capability_ok = + capability == "WorkgroupMemoryExplicitLayout16BitAccessKHR"; + } + storage_class_ok = true; } - CompileSuccessfully(generator.Build(), SPV_ENV_UNIVERSAL_1_3); - spv_result_t result = ValidateInstructions(SPV_ENV_UNIVERSAL_1_3); - if (capability_ok) { + CompileSuccessfully(generator.Build(), target); + spv_result_t result = ValidateInstructions(target); + if (target < SPV_ENV_UNIVERSAL_1_4 && + (capability == "WorkgroupMemoryExplicitLayout8BitAccessKHR" || + capability == "WorkgroupMemoryExplicitLayout16BitAccessKHR")) { + EXPECT_EQ(SPV_ERROR_WRONG_VERSION, result); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("requires SPIR-V version 1.4 or later")); + } else if (buffer_block && target > SPV_ENV_UNIVERSAL_1_3) { + EXPECT_EQ(SPV_ERROR_WRONG_VERSION, result); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("requires SPIR-V version 1.3 or earlier")); + } else if (capability_ok) { EXPECT_EQ(SPV_SUCCESS, result); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, result); @@ -3965,8 +3613,10 @@ INSTANTIATE_TEST_SUITE_P( Combine(Values("UniformConstant", "Input", "Output", "Workgroup", "CrossWorkgroup", "Private", "StorageBuffer", "Uniform"), Values("StorageBuffer8BitAccess", - "UniformAndStorageBuffer8BitAccess", "StoragePushConstant8"), - Values("%char", "%char4", "%char_buffer_block"))); + "UniformAndStorageBuffer8BitAccess", "StoragePushConstant8", + "WorkgroupMemoryExplicitLayout8BitAccessKHR"), + Values("%char", "%char4", "%char_buffer_block"), + Values(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_4))); INSTANTIATE_TEST_SUITE_P( Storage16, ValidateSizedVariable, @@ -3974,9 +3624,11 @@ INSTANTIATE_TEST_SUITE_P( "CrossWorkgroup", "Private", "StorageBuffer", "Uniform"), Values("StorageBuffer16BitAccess", "UniformAndStorageBuffer16BitAccess", - "StoragePushConstant16", "StorageInputOutput16"), + "StoragePushConstant16", "StorageInputOutput16", + "WorkgroupMemoryExplicitLayout16BitAccessKHR"), Values("%short", "%half", "%short4", "%half4", "%mat4x4", - "%short_buffer_block", "%half_buffer_block"))); + "%short_buffer_block", "%half_buffer_block"), + Values(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_4))); using ValidateSizedLoadStore = spvtest::ValidateBase>; @@ -4390,6 +4042,109 @@ OpFunctionEnd "typed as OpTypeStruct, or an array of this type")); } +TEST_F(ValidateMemory, VulkanInvariantOutputSuccess) { + const std::string spirv = R"( +OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %main "main" +OpDecorate %var Location 0 +OpDecorate %var Invariant +%void = OpTypeVoid +%f32 = OpTypeFloat 32 +%ptr_output = OpTypePointer Output %f32 +%var = OpVariable %ptr_output Output +%void_fn = OpTypeFunction %void +%main = OpFunction %void None %void_fn +%entry = OpLabel +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateMemory, VulkanInvariantInputStructSuccess) { + const std::string spirv = R"( +OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +OpDecorate %var Location 0 +OpMemberDecorate %struct 1 Invariant +%void = OpTypeVoid +%f32 = OpTypeFloat 32 +%struct = OpTypeStruct %f32 %f32 +%ptr_input = OpTypePointer Input %struct +%var = OpVariable %ptr_input Input +%void_fn = OpTypeFunction %void +%main = OpFunction %void None %void_fn +%entry = OpLabel +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + +TEST_F(ValidateMemory, VulkanInvariantWrongStorageClass) { + const std::string spirv = R"( +OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %main "main" +OpDecorate %var Invariant +%void = OpTypeVoid +%f32 = OpTypeFloat 32 +%ptr_private = OpTypePointer Private %f32 +%var = OpVariable %ptr_private Private +%void_fn = OpTypeFunction %void +%main = OpFunction %void None %void_fn +%entry = OpLabel +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-Invariant-04677")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "Variable decorated with Invariant must only be identified with the " + "Input or Output storage class in Vulkan environment.")); +} + +TEST_F(ValidateMemory, VulkanInvariantMemberWrongStorageClass) { + const std::string spirv = R"( +OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +OpMemberDecorate %struct 1 Invariant +%void = OpTypeVoid +%f32 = OpTypeFloat 32 +%struct = OpTypeStruct %f32 %f32 +%ptr_private = OpTypePointer Private %struct +%var = OpVariable %ptr_private Private +%void_fn = OpTypeFunction %void +%main = OpFunction %void None %void_fn +%entry = OpLabel +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-Invariant-04677")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Variable struct member decorated with Invariant must " + "only be identified with the Input or Output storage " + "class in Vulkan environment.")); +} + TEST_F(ValidateMemory, PhysicalStorageBufferPtrEqual) { const std::string spirv = R"( OpCapability Shader @@ -4480,6 +4235,55 @@ OpFunctionEnd "Cannot use a pointer in the PhysicalStorageBuffer storage class")); } +TEST_F(ValidateMemory, VulkanInitializerWithWorkgroupStorageClassBad) { + std::string spirv = R"( +OpCapability Shader +OpCapability VulkanMemoryModelKHR +OpExtension "SPV_KHR_vulkan_memory_model" +OpMemoryModel Logical VulkanKHR +OpEntryPoint Fragment %func "func" +OpExecutionMode %func OriginUpperLeft +%float = OpTypeFloat 32 +%float_ptr = OpTypePointer Workgroup %float +%init_val = OpConstant %float 1.0 +%1 = OpVariable %float_ptr Workgroup %init_val +%void = OpTypeVoid +%functy = OpTypeFunction %void +%func = OpFunction %void None %functy +%2 = OpLabel +OpReturn +OpFunctionEnd +)"; + CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Variable initializers in Workgroup storage class are " + "limited to OpConstantNull")); +} + +TEST_F(ValidateMemory, VulkanInitializerWithWorkgroupStorageClassGood) { + std::string spirv = R"( +OpCapability Shader +OpCapability VulkanMemoryModelKHR +OpExtension "SPV_KHR_vulkan_memory_model" +OpMemoryModel Logical VulkanKHR +OpEntryPoint Fragment %func "func" +OpExecutionMode %func OriginUpperLeft +%float = OpTypeFloat 32 +%float_ptr = OpTypePointer Workgroup %float +%init_val = OpConstantNull %float +%1 = OpVariable %float_ptr Workgroup %init_val +%void = OpTypeVoid +%functy = OpTypeFunction %void +%func = OpFunction %void None %functy +%2 = OpLabel +OpReturn +OpFunctionEnd +)"; + CompileSuccessfully(spirv.c_str(), SPV_ENV_VULKAN_1_0); + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_VULKAN_1_0)); +} + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_misc_test.cpp b/third_party/spirv-tools/test/val/val_misc_test.cpp index 93954844e9..b0e46bf95c 100644 --- a/third_party/spirv-tools/test/val/val_misc_test.cpp +++ b/third_party/spirv-tools/test/val/val_misc_test.cpp @@ -226,6 +226,77 @@ OpFunctionEnd)"; EXPECT_THAT(getDiagnosticString(), HasSubstr("Scope must be Subgroup or Device")); } + +TEST_F(ValidateMisc, VulkanShaderClockWorkgroupScope) { + const std::string spirv = ShaderClockSpriv + R"( +%3 = OpTypeFunction %void +%ulong = OpTypeInt 64 0 +%uint = OpTypeInt 32 0 +%_ptr_Function_ulong = OpTypePointer Function %ulong +%workgroup = OpConstant %uint 2 +%uint_1 = OpConstant %uint 1 +%main = OpFunction %void None %3 +%5 = OpLabel +%time1 = OpVariable %_ptr_Function_ulong Function +%11 = OpReadClockKHR %ulong %workgroup +OpStore %time1 %11 +OpReturn +OpFunctionEnd)"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpReadClockKHR-04652")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Scope must be Subgroup or Device")); +} + +TEST_F(ValidateMisc, UndefVoid) { + const std::string spirv = R"( + OpCapability Shader + %1 = OpExtInstImport "GLSL.std.450" + OpMemoryModel Logical GLSL450 + OpEntryPoint Fragment %4 "main" + OpExecutionMode %4 OriginUpperLeft + OpSource ESSL 320 + %2 = OpTypeVoid + %10 = OpUndef %2 + %3 = OpTypeFunction %2 + %4 = OpFunction %2 None %3 + %5 = OpLabel + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Cannot create undefined values with void type")); +} + +TEST_F(ValidateMisc, VulkanInvalidStorageClass) { + const std::string spirv = R"( +OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Vertex %func "shader" +%int = OpTypeInt 32 0 +%ptr = OpTypePointer CrossWorkgroup %int +%var = OpVariable %ptr CrossWorkgroup +%void = OpTypeVoid +%void_f = OpTypeFunction %void +%func = OpFunction %void None %void_f +%label = OpLabel + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04643")); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Invalid storage class for target environment")); +} } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_modes_test.cpp b/third_party/spirv-tools/test/val/val_modes_test.cpp index 0a1476ee4a..99f5c9cfae 100644 --- a/third_party/spirv-tools/test/val/val_modes_test.cpp +++ b/third_party/spirv-tools/test/val/val_modes_test.cpp @@ -62,6 +62,8 @@ OpEntryPoint GLCompute %main "main" spv_target_env env = SPV_ENV_VULKAN_1_0; CompileSuccessfully(spirv, env); EXPECT_THAT(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-LocalSize-04683")); EXPECT_THAT( getDiagnosticString(), HasSubstr("In the Vulkan environment, GLCompute execution model entry " @@ -110,6 +112,8 @@ OpExecutionMode %main OriginLowerLeft spv_target_env env = SPV_ENV_VULKAN_1_0; CompileSuccessfully(spirv, env); EXPECT_THAT(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OriginLowerLeft-04653")); EXPECT_THAT(getDiagnosticString(), HasSubstr("In the Vulkan environment, the OriginLowerLeft " "execution mode must not be used.")); @@ -127,6 +131,8 @@ OpExecutionMode %main PixelCenterInteger spv_target_env env = SPV_ENV_VULKAN_1_0; CompileSuccessfully(spirv, env); EXPECT_THAT(SPV_ERROR_INVALID_DATA, ValidateInstructions(env)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-PixelCenterInteger-04654")); EXPECT_THAT(getDiagnosticString(), HasSubstr("In the Vulkan environment, the PixelCenterInteger " "execution mode must not be used.")); @@ -531,24 +537,16 @@ TEST_P(ValidateModeExecution, ExecutionMode) { std::ostringstream sstr; sstr << "OpCapability Shader\n"; - if (!spvIsWebGPUEnv(env)) { - sstr << "OpCapability Geometry\n"; - sstr << "OpCapability Tessellation\n"; - sstr << "OpCapability TransformFeedback\n"; - } - if (!spvIsVulkanOrWebGPUEnv(env)) { + sstr << "OpCapability Geometry\n"; + sstr << "OpCapability Tessellation\n"; + sstr << "OpCapability TransformFeedback\n"; + if (!spvIsVulkanEnv(env)) { sstr << "OpCapability Kernel\n"; if (env == SPV_ENV_UNIVERSAL_1_3) { sstr << "OpCapability SubgroupDispatch\n"; } } - if (spvIsWebGPUEnv(env)) { - sstr << "OpCapability VulkanMemoryModelKHR\n"; - sstr << "OpExtension \"SPV_KHR_vulkan_memory_model\"\n"; - sstr << "OpMemoryModel Logical VulkanKHR\n"; - } else { - sstr << "OpMemoryModel Logical GLSL450\n"; - } + sstr << "OpMemoryModel Logical GLSL450\n"; sstr << "OpEntryPoint " << model << " %main \"main\"\n"; if (mode.find("LocalSizeId") == 0 || mode.find("LocalSizeHintId") == 0 || mode.find("SubgroupsPerWorkgroupId") == 0) { @@ -714,39 +712,6 @@ INSTANTIATE_TEST_SUITE_P( "SubgroupsPerWorkgroup 1", "SubgroupsPerWorkgroupId %int1"), Values(SPV_ENV_UNIVERSAL_1_3))); -INSTANTIATE_TEST_SUITE_P(ValidateModeGLComputeWebGPUAllowListGood, - ValidateModeExecution, - Combine(Values(SPV_SUCCESS), Values(""), - Values("GLCompute"), Values("LocalSize 1 1 1"), - Values(SPV_ENV_WEBGPU_0))); - -INSTANTIATE_TEST_SUITE_P( - ValidateModeGLComputeWebGPUAllowListBad, ValidateModeExecution, - Combine(Values(SPV_ERROR_INVALID_DATA), - Values("Execution mode must be one of OriginUpperLeft, " - "DepthReplacing, DepthGreater, DepthLess, DepthUnchanged, " - "LocalSize, or LocalSizeHint for WebGPU environment"), - Values("GLCompute"), Values("LocalSizeId %int1 %int1 %int1"), - Values(SPV_ENV_WEBGPU_0))); - -INSTANTIATE_TEST_SUITE_P( - ValidateModeFragmentWebGPUAllowListGood, ValidateModeExecution, - Combine(Values(SPV_SUCCESS), Values(""), Values("Fragment"), - Values("OriginUpperLeft", "DepthReplacing", "DepthGreater", - "DepthLess", "DepthUnchanged"), - Values(SPV_ENV_WEBGPU_0))); - -INSTANTIATE_TEST_SUITE_P( - ValidateModeFragmentWebGPUAllowListBad, ValidateModeExecution, - Combine(Values(SPV_ERROR_INVALID_DATA), - Values("Execution mode must be one of OriginUpperLeft, " - "DepthReplacing, DepthGreater, DepthLess, DepthUnchanged, " - "LocalSize, or LocalSizeHint for WebGPU environment"), - Values("Fragment"), - Values("PixelCenterInteger", "OriginLowerLeft", - "EarlyFragmentTests"), - Values(SPV_ENV_WEBGPU_0))); - TEST_F(ValidateModeExecution, MeshNVLocalSize) { const std::string spirv = R"( OpCapability Shader diff --git a/third_party/spirv-tools/test/val/val_non_uniform_test.cpp b/third_party/spirv-tools/test/val/val_non_uniform_test.cpp index fbd11a9ef2..3840eec6a7 100644 --- a/third_party/spirv-tools/test/val/val_non_uniform_test.cpp +++ b/third_party/spirv-tools/test/val/val_non_uniform_test.cpp @@ -100,6 +100,7 @@ OpFunctionEnd)"; SpvScope scopes[] = {SpvScopeCrossDevice, SpvScopeDevice, SpvScopeWorkgroup, SpvScopeSubgroup, SpvScopeInvocation}; +using ValidateGroupNonUniform = spvtest::ValidateBase; using GroupNonUniform = spvtest::ValidateBase< std::tuple>; @@ -140,6 +141,8 @@ TEST_P(GroupNonUniform, Vulkan1p1) { EXPECT_EQ(SPV_SUCCESS, result); } else { EXPECT_EQ(SPV_ERROR_INVALID_DATA, result); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04642")); EXPECT_THAT( getDiagnosticString(), HasSubstr( @@ -288,6 +291,41 @@ INSTANTIATE_TEST_SUITE_P(GroupNonUniformBallotBitCountBadValue, GroupNonUniform, Values("Expected Value to be a vector of four " "components of integer type scalar"))); +TEST_F(ValidateGroupNonUniform, VulkanGroupNonUniformBallotBitCountOperation) { + std::string test = R"( +OpCapability Shader +OpCapability GroupNonUniform +OpCapability GroupNonUniformBallot +OpCapability GroupNonUniformClustered +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize 1 1 1 +%void = OpTypeVoid +%func = OpTypeFunction %void +%u32 = OpTypeInt 32 0 +%u32vec4 = OpTypeVector %u32 4 +%u32_0 = OpConstant %u32 0 +%u32vec4_null = OpConstantComposite %u32vec4 %u32_0 %u32_0 %u32_0 %u32_0 +%subgroup = OpConstant %u32 3 +%main = OpFunction %void None %func +%main_entry = OpLabel +%result = OpGroupNonUniformBallotBitCount %u32 %subgroup ClusteredReduce %u32vec4_null +OpReturn +OpFunctionEnd +)"; + + CompileSuccessfully(test, SPV_ENV_VULKAN_1_1); + ASSERT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT( + getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-OpGroupNonUniformBallotBitCount-04685")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr( + "In Vulkan: The OpGroupNonUniformBallotBitCount group operation must " + "be only: Reduce, InclusiveScan, or ExclusiveScan.")); +} + } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_opencl_test.cpp b/third_party/spirv-tools/test/val/val_opencl_test.cpp index 10641587fe..9dab931abc 100644 --- a/third_party/spirv-tools/test/val/val_opencl_test.cpp +++ b/third_party/spirv-tools/test/val/val_opencl_test.cpp @@ -23,6 +23,7 @@ namespace spvtools { namespace val { namespace { +using testing::Eq; using testing::HasSubstr; using ValidateOpenCL = spvtest::ValidateBase; @@ -91,7 +92,7 @@ TEST_F(ValidateOpenCL, NonZeroMSImageBad) { EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_1_2)); EXPECT_THAT( getDiagnosticString(), - HasSubstr("MS must be 0 in the OpenCL environement." + HasSubstr("MS must be 0 in the OpenCL environment." "\n %2 = OpTypeImage %void 2D 0 0 1 0 Unknown ReadOnly\n")); } @@ -224,6 +225,264 @@ TEST_F(ValidateOpenCL, ImageReadWithConstOffsetBad) { "\n %call = OpImageRead %v4uint %img %coord ConstOffset %coord\n")); } +TEST_F(ValidateOpenCL, ImageRead_NonDepthScalarFloatResult_Bad) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %3 = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %float %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Result Type to have 4 components")); +} + +TEST_F(ValidateOpenCL, ImageRead_NonDepthScalarIntResult_Bad) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %3 = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %uint %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Result Type to have 4 components")); +} + +TEST_F(ValidateOpenCL, ImageRead_NonDepthVector3FloatResult_Bad) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %v3float = OpTypeVector %float 3 + %3 = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %v3float %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Result Type to have 4 components")); +} + +TEST_F(ValidateOpenCL, ImageRead_NonDepthVector4FloatResult_Ok) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %3 = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %v4float %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateOpenCL, ImageRead_NonDepthVector4IntResult_Ok) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %v4uint = OpTypeVector %uint 4 + %3 = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %v4uint %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateOpenCL, ImageRead_DepthScalarFloatResult_Ok) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %3 = OpTypeImage %void 2D 1 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %float %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), Eq("")); +} + +TEST_F(ValidateOpenCL, ImageRead_DepthScalarIntResult_Bad) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %3 = OpTypeImage %void 2D 1 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %uint %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Result Type from a depth image " + "read to result in a scalar float value")); +} + +TEST_F(ValidateOpenCL, ImageRead_DepthVectorFloatResult_Bad) { + std::string spirv = R"( + OpCapability Addresses + OpCapability Kernel + OpCapability ImageBasic + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %5 "image_kernel" + OpName %img "img" + OpName %coord "coord" + OpName %call "call" + %uint = OpTypeInt 32 0 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint + %void = OpTypeVoid + %float = OpTypeFloat 32 + %v4float = OpTypeVector %float 4 + %3 = OpTypeImage %void 2D 1 0 0 0 Unknown ReadOnly + %4 = OpTypeFunction %void %3 + %5 = OpFunction %void None %4 + %img = OpFunctionParameter %3 + %entry = OpLabel + %call = OpImageRead %v4float %img %coord + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(spirv); + + EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_OPENCL_1_2)); + EXPECT_THAT(getDiagnosticString(), + HasSubstr("Expected Result Type from a depth image " + "read to result in a scalar float value")); +} + TEST_F(ValidateOpenCL, ImageSampleExplicitLodWithConstOffsetBad) { std::string spirv = R"( OpCapability Addresses @@ -236,18 +495,16 @@ TEST_F(ValidateOpenCL, ImageSampleExplicitLodWithConstOffsetBad) { OpName %coord "coord" OpName %call "call" %uint = OpTypeInt 32 0 - %uint_7 = OpConstant %uint 7 - %uint_3 = OpConstant %uint 3 + %v2uint = OpTypeVector %uint 2 + %coord = OpConstantNull %v2uint %void = OpTypeVoid %3 = OpTypeImage %void 2D 0 0 0 0 Unknown ReadOnly %4 = OpTypeFunction %void %3 %8 = OpTypeSampler %10 = OpTypeSampledImage %3 %v4uint = OpTypeVector %uint 4 - %v2uint = OpTypeVector %uint 2 %float = OpTypeFloat 32 %9 = OpConstantSampler %8 None 0 Nearest - %coord = OpConstantComposite %v2uint %uint_7 %uint_3 %float_0 = OpConstant %float 0 %5 = OpFunction %void None %4 %6 = OpFunctionParameter %3 diff --git a/third_party/spirv-tools/test/val/val_state_test.cpp b/third_party/spirv-tools/test/val/val_state_test.cpp index b2d2604501..65cb1c3adc 100644 --- a/third_party/spirv-tools/test/val/val_state_test.cpp +++ b/third_party/spirv-tools/test/val/val_state_test.cpp @@ -43,7 +43,7 @@ class ValidationStateTest : public testing::Test { options_(spvValidatorOptionsCreate()), state_(context_, options_, kFakeBinary, 0, 1) {} - ~ValidationStateTest() { + ~ValidationStateTest() override { spvContextDestroy(context_); spvValidatorOptionsDestroy(options_); } diff --git a/third_party/spirv-tools/test/val/val_storage_test.cpp b/third_party/spirv-tools/test/val/val_storage_test.cpp index fe37a93c6d..35f6a8d5ec 100644 --- a/third_party/spirv-tools/test/val/val_storage_test.cpp +++ b/third_party/spirv-tools/test/val/val_storage_test.cpp @@ -30,6 +30,7 @@ using ::testing::Values; using ValidateStorage = spvtest::ValidateBase; using ValidateStorageClass = spvtest::ValidateBase>; +using ValidateStorageExecutionModel = spvtest::ValidateBase; TEST_F(ValidateStorage, FunctionStorageInsideFunction) { char str[] = R"( @@ -250,69 +251,45 @@ TEST_F(ValidateStorage, RelaxedLogicalPointerFunctionParamBad) { HasSubstr("OpFunctionCall Argument '")); } -std::string GetVarDeclStr(const std::string& storage_class) { - if (storage_class != "Output" && storage_class != "Private" && - storage_class != "Function") { - return "%var = OpVariable %ptrt " + storage_class + "\n"; - } else { - return "%var = OpVariable %ptrt " + storage_class + " %null\n"; - } +TEST_P(ValidateStorageExecutionModel, VulkanOutsideStoreFailure) { + std::stringstream ss; + ss << R"( + OpCapability Shader + OpCapability RayTracingKHR + OpExtension "SPV_KHR_ray_tracing" + OpMemoryModel Logical GLSL450 + OpEntryPoint )" + << GetParam() << R"( %func "func" %output + OpDecorate %output Location 0 +%intt = OpTypeInt 32 0 +%int0 = OpConstant %intt 0 +%voidt = OpTypeVoid +%vfunct = OpTypeFunction %voidt +%outputptrt = OpTypePointer Output %intt +%output = OpVariable %outputptrt Output +%func = OpFunction %voidt None %vfunct +%funcl = OpLabel + OpStore %output %int0 + OpReturn + OpFunctionEnd +)"; + + CompileSuccessfully(ss.str(), SPV_ENV_VULKAN_1_0); + ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions(SPV_ENV_VULKAN_1_0)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04644")); + EXPECT_THAT( + getDiagnosticString(), + HasSubstr("in Vulkan evironment, Output Storage Class must not be used " + "in GLCompute, RayGenerationKHR, IntersectionKHR, AnyHitKHR, " + "ClosestHitKHR, MissKHR, or CallableKHR execution models")); } -TEST_P(ValidateStorageClass, WebGPU) { - std::string storage_class = std::get<0>(GetParam()); - bool is_local = std::get<1>(GetParam()); - bool is_valid = std::get<2>(GetParam()); - std::string error = std::get<3>(GetParam()); - - std::string str = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Fragment %func "func" - OpExecutionMode %func OriginUpperLeft -%intt = OpTypeInt 32 1 -%voidt = OpTypeVoid -%vfunct = OpTypeFunction %voidt -%null = OpConstantNull %intt -)"; - str += "%ptrt = OpTypePointer " + storage_class + " %intt\n"; - if (!is_local) str += GetVarDeclStr(storage_class); - str += R"( -%func = OpFunction %voidt None %vfunct -%funcl = OpLabel -)"; - if (is_local) str += GetVarDeclStr(storage_class); - str += R"( -OpReturn -OpFunctionEnd -)"; - - CompileSuccessfully(str, SPV_ENV_WEBGPU_0); - if (is_valid) { - ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); - } else { - ASSERT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), HasSubstr(error)); - } -} - -INSTANTIATE_TEST_SUITE_P( - StorageClass, ValidateStorageClass, - Values(std::make_tuple("UniformConstant", false, true, ""), - std::make_tuple("Uniform", false, true, ""), - std::make_tuple("StorageBuffer", false, true, ""), - std::make_tuple("Input", false, true, ""), - std::make_tuple("Output", false, true, ""), - std::make_tuple("Image", false, true, ""), - std::make_tuple("Workgroup", false, true, ""), - std::make_tuple("Private", false, true, ""), - std::make_tuple("Function", true, true, ""), - std::make_tuple("CrossWorkgroup", false, false, - "Invalid storage class for target environment"), - std::make_tuple("PushConstant", false, false, - "Invalid storage class for target environment"))); +INSTANTIATE_TEST_SUITE_P(MatrixExecutionModel, ValidateStorageExecutionModel, + ::testing::Values("RayGenerationKHR", + "IntersectionKHR", "AnyHitKHR", + "ClosestHitKHR", "MissKHR", + "CallableKHR")); } // namespace } // namespace val diff --git a/third_party/spirv-tools/test/val/val_validation_state_test.cpp b/third_party/spirv-tools/test/val/val_validation_state_test.cpp index 458157902e..3dd9e64a60 100644 --- a/third_party/spirv-tools/test/val/val_validation_state_test.cpp +++ b/third_party/spirv-tools/test/val/val_validation_state_test.cpp @@ -245,12 +245,6 @@ TEST_F(ValidationStateTest, CheckVulkanNonRecursiveBodyGood) { ValidateAndRetrieveValidationState(SPV_ENV_VULKAN_1_1)); } -TEST_F(ValidationStateTest, CheckWebGPUNonRecursiveBodyGood) { - std::string spirv = std::string(kVulkanMemoryHeader) + kNonRecursiveBody; - CompileSuccessfully(spirv, SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_SUCCESS, ValidateAndRetrieveValidationState(SPV_ENV_WEBGPU_0)); -} - TEST_F(ValidationStateTest, CheckDirectlyRecursiveBodyGood) { std::string spirv = std::string(kHeader) + kDirectlyRecursiveBody; CompileSuccessfully(spirv); @@ -263,15 +257,7 @@ TEST_F(ValidationStateTest, CheckVulkanDirectlyRecursiveBodyBad) { EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateAndRetrieveValidationState(SPV_ENV_VULKAN_1_1)); EXPECT_THAT(getDiagnosticString(), - HasSubstr("Entry points may not have a call graph with cycles.\n " - " %1 = OpFunction %void Pure|Const %3\n")); -} - -TEST_F(ValidationStateTest, CheckWebGPUDirectlyRecursiveBodyBad) { - std::string spirv = std::string(kVulkanMemoryHeader) + kDirectlyRecursiveBody; - CompileSuccessfully(spirv, SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_BINARY, - ValidateAndRetrieveValidationState(SPV_ENV_WEBGPU_0)); + AnyVUID("VUID-StandaloneSpirv-None-04634")); EXPECT_THAT(getDiagnosticString(), HasSubstr("Entry points may not have a call graph with cycles.\n " " %1 = OpFunction %void Pure|Const %3\n")); @@ -289,73 +275,13 @@ TEST_F(ValidationStateTest, CheckVulkanIndirectlyRecursiveBodyBad) { CompileSuccessfully(spirv, SPV_ENV_VULKAN_1_1); EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateAndRetrieveValidationState(SPV_ENV_VULKAN_1_1)); + EXPECT_THAT(getDiagnosticString(), + AnyVUID("VUID-StandaloneSpirv-None-04634")); EXPECT_THAT(getDiagnosticString(), HasSubstr("Entry points may not have a call graph with cycles.\n " " %1 = OpFunction %void Pure|Const %3\n")); } -// Indirectly recursive functions are caught by the function definition layout -// rules, because they cause a situation where there are 2 functions that have -// to be before each other, and layout is checked earlier. -TEST_F(ValidationStateTest, CheckWebGPUIndirectlyRecursiveBodyBad) { - std::string spirv = - std::string(kVulkanMemoryHeader) + kIndirectlyRecursiveBody; - CompileSuccessfully(spirv, SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_LAYOUT, - ValidateAndRetrieveValidationState(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, functions need to be defined before being " - "called.\n %10 = OpFunctionCall %_struct_5 %11\n")); -} - -TEST_F(ValidationStateTest, - CheckWebGPUDuplicateEntryNamesDifferentFunctionsBad) { - std::string spirv = std::string(kVulkanMemoryHeader) + R"( -OpEntryPoint Fragment %func_1 "main" -OpEntryPoint Vertex %func_2 "main" -OpExecutionMode %func_1 OriginUpperLeft -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func_1 = OpFunction %void None %void_f -%label_1 = OpLabel - OpReturn - OpFunctionEnd -%func_2 = OpFunction %void None %void_f -%label_2 = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv, SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_BINARY, - ValidateAndRetrieveValidationState(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Entry point name \"main\" is not unique, which is not allow " - "in WebGPU env.\n %1 = OpFunction %void None %4\n")); -} - -TEST_F(ValidationStateTest, CheckWebGPUDuplicateEntryNamesSameFunctionBad) { - std::string spirv = std::string(kVulkanMemoryHeader) + R"( -OpEntryPoint GLCompute %func_1 "main" -OpEntryPoint Vertex %func_1 "main" -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func_1 = OpFunction %void None %void_f -%label_1 = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv, SPV_ENV_WEBGPU_0); - EXPECT_EQ(SPV_ERROR_INVALID_BINARY, - ValidateAndRetrieveValidationState(SPV_ENV_WEBGPU_0)); - EXPECT_THAT( - getDiagnosticString(), - HasSubstr("Entry point name \"main\" is not unique, which is not allow " - "in WebGPU env.\n %1 = OpFunction %void None %3\n")); -} - } // namespace } // namespace val } // namespace spvtools diff --git a/third_party/spirv-tools/test/val/val_version_test.cpp b/third_party/spirv-tools/test/val/val_version_test.cpp index 2b9542a126..98565ddb8b 100644 --- a/third_party/spirv-tools/test/val/val_version_test.cpp +++ b/third_party/spirv-tools/test/val/val_version_test.cpp @@ -40,21 +40,6 @@ OpReturn OpFunctionEnd )"; -const std::string webgpu_spirv = R"( -OpCapability Shader -OpCapability VulkanMemoryModelKHR -OpExtension "SPV_KHR_vulkan_memory_model" -OpMemoryModel Logical VulkanKHR -OpEntryPoint Fragment %func "func" -OpExecutionMode %func OriginUpperLeft -%void = OpTypeVoid -%functy = OpTypeFunction %void -%func = OpFunction %void None %functy -%1 = OpLabel -OpReturn -OpFunctionEnd -)"; - const std::string opencl_spirv = R"( OpCapability Addresses OpCapability Kernel @@ -85,7 +70,6 @@ std::string version(spv_target_env env) { return "1.2"; case SPV_ENV_UNIVERSAL_1_3: case SPV_ENV_VULKAN_1_1: - case SPV_ENV_WEBGPU_0: return "1.3"; case SPV_ENV_UNIVERSAL_1_4: case SPV_ENV_VULKAN_1_1_SPIRV_1_4: @@ -126,7 +110,6 @@ INSTANTIATE_TEST_SUITE_P(Universal, ValidateVersion, std::make_tuple(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_OPENGL_4_2, vulkan_spirv, true), std::make_tuple(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_OPENGL_4_3, vulkan_spirv, true), std::make_tuple(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_OPENGL_4_5, vulkan_spirv, true), - std::make_tuple(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_WEBGPU_0, webgpu_spirv, true), std::make_tuple(SPV_ENV_UNIVERSAL_1_1, SPV_ENV_UNIVERSAL_1_0, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_1, SPV_ENV_UNIVERSAL_1_1, vulkan_spirv, true), @@ -139,7 +122,6 @@ INSTANTIATE_TEST_SUITE_P(Universal, ValidateVersion, std::make_tuple(SPV_ENV_UNIVERSAL_1_1, SPV_ENV_OPENGL_4_2, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_1, SPV_ENV_OPENGL_4_3, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_1, SPV_ENV_OPENGL_4_5, vulkan_spirv, false), - std::make_tuple(SPV_ENV_UNIVERSAL_1_1, SPV_ENV_WEBGPU_0, webgpu_spirv, true), std::make_tuple(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_0, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_UNIVERSAL_1_1, vulkan_spirv, false), @@ -152,7 +134,6 @@ INSTANTIATE_TEST_SUITE_P(Universal, ValidateVersion, std::make_tuple(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_OPENGL_4_2, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_OPENGL_4_3, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_OPENGL_4_5, vulkan_spirv, false), - std::make_tuple(SPV_ENV_UNIVERSAL_1_2, SPV_ENV_WEBGPU_0, webgpu_spirv, true), std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_0, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_UNIVERSAL_1_1, vulkan_spirv, false), @@ -164,8 +145,7 @@ INSTANTIATE_TEST_SUITE_P(Universal, ValidateVersion, std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_OPENGL_4_1, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_OPENGL_4_2, vulkan_spirv, false), std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_OPENGL_4_3, vulkan_spirv, false), - std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_OPENGL_4_5, vulkan_spirv, false), - std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_WEBGPU_0, webgpu_spirv, true) + std::make_tuple(SPV_ENV_UNIVERSAL_1_3, SPV_ENV_OPENGL_4_5, vulkan_spirv, false) ) ); diff --git a/third_party/spirv-tools/test/val/val_webgpu_test.cpp b/third_party/spirv-tools/test/val/val_webgpu_test.cpp deleted file mode 100644 index 62fa6a7a83..0000000000 --- a/third_party/spirv-tools/test/val/val_webgpu_test.cpp +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright (c) 2018 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Validation tests for WebGPU env specific checks - -#include - -#include "gmock/gmock.h" -#include "test/val/val_fixtures.h" - -namespace spvtools { -namespace val { -namespace { - -using testing::HasSubstr; - -using ValidateWebGPU = spvtest::ValidateBase; - -TEST_F(ValidateWebGPU, OpUndefIsDisallowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" -%float = OpTypeFloat 32 -%1 = OpUndef %float -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func = OpFunction %void None %void_f -%label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - - // Control case: OpUndef is allowed in SPIR-V 1.3 - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_3)); - - // Control case: OpUndef is disallowed in the WebGPU env - EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), HasSubstr("OpUndef is disallowed")); -} - -TEST_F(ValidateWebGPU, OpNameIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - OpName %1 "foo" - %1 = OpTypeFloat 32 - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpMemberNameIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - OpMemberName %2 0 "foo" - %1 = OpTypeFloat 32 - %2 = OpTypeStruct %1 - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd - -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpSourceIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - OpSource GLSL 450 - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpSourceContinuedIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - OpSource GLSL 450 - OpSourceContinued "I am a happy shader! Yay! ;" - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpSourceExtensionIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - OpSourceExtension "bar" - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpStringIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - %1 = OpString "foo" - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpLineIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - %1 = OpString "minimal.vert" - OpLine %1 1 1 - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, OpNoLineIsAllowed) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" - OpNoLine - %void = OpTypeVoid - %void_f = OpTypeFunction %void - %func = OpFunction %void None %void_f - %label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, LogicalAddressingVulkanKHRMemoryGood) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func = OpFunction %void None %void_f -%label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, LogicalAddressingGLSL450MemoryGood) { - std::string spirv = R"( - OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Vertex %func "shader" -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func = OpFunction %void None %void_f -%label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, LogicalAddressingSimpleMemoryGood) { - std::string spirv = R"( - OpCapability Shader - OpMemoryModel Logical Simple - OpEntryPoint Vertex %func "shader" -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func = OpFunction %void None %void_f -%label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, KernelIsBad) { - std::string spirv = R"( - OpCapability Kernel - OpMemoryModel Logical Simple - OpNoLine -)"; - - CompileSuccessfully(spirv); - - EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Capability Kernel is not allowed by WebGPU " - "specification (or requires extension)")); -} - -TEST_F(ValidateWebGPU, OpenCLMemoryModelBad) { - std::string spirv = R"( - OpCapability Shader - OpMemoryModel Logical OpenCL - OpNoLine -)"; - - CompileSuccessfully(spirv); - - EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, - ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("Operand 2 of MemoryModel requires one of these " - "capabilities: Kernel")); -} - -TEST_F(ValidateWebGPU, AllowListedExtendedInstructionsImportGood) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" -%1 = OpExtInstImport "GLSL.std.450" - OpMemoryModel Logical VulkanKHR - OpEntryPoint Vertex %func "shader" -%void = OpTypeVoid -%void_f = OpTypeFunction %void -%func = OpFunction %void None %void_f -%label = OpLabel - OpReturn - OpFunctionEnd -)"; - - CompileSuccessfully(spirv); - - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, NonAllowListedExtendedInstructionsImportBad) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_vulkan_memory_model" -%1 = OpExtInstImport "OpenCL.std" - OpMemoryModel Logical VulkanKHR -)"; - - CompileSuccessfully(spirv); - - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, the only valid parameter to " - "OpExtInstImport is \"GLSL.std.450\".\n %1 = " - "OpExtInstImport \"OpenCL.std\"\n")); -} - -TEST_F(ValidateWebGPU, NonVulkanKHRMemoryModelExtensionBad) { - std::string spirv = R"( - OpCapability Shader - OpCapability VulkanMemoryModelKHR - OpExtension "SPV_KHR_8bit_storage" - OpExtension "SPV_KHR_vulkan_memory_model" - OpMemoryModel Logical VulkanKHR -)"; - - CompileSuccessfully(spirv); - - EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("For WebGPU, the only valid parameter to OpExtension " - "is \"SPV_KHR_vulkan_memory_model\".\n OpExtension " - "\"SPV_KHR_8bit_storage\"\n")); -} - -spv_binary GenerateTrivialBinary(bool need_little_endian) { - // Smallest possible valid WebGPU SPIR-V binary in little endian. Contains all - // the required boilerplate and a trivial entry point function. - static const uint8_t binary_bytes[] = { - // clang-format off - 0x03, 0x02, 0x23, 0x07, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0xE1, 0x14, 0x00, 0x00, - 0x0A, 0x00, 0x08, 0x00, 0x53, 0x50, 0x56, 0x5F, 0x4B, 0x48, 0x52, 0x5F, - 0x76, 0x75, 0x6C, 0x6B, 0x61, 0x6E, 0x5F, 0x6D, 0x65, 0x6D, 0x6F, 0x72, - 0x79, 0x5F, 0x6D, 0x6F, 0x64, 0x65, 0x6C, 0x00, 0x0E, 0x00, 0x03, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x05, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x73, 0x68, 0x61, 0x64, - 0x65, 0x72, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, - 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, - 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xF8, 0x00, 0x02, 0x00, - 0x04, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 - // clang-format on - }; - static const size_t word_count = sizeof(binary_bytes) / sizeof(uint32_t); - std::unique_ptr result(new spv_binary_t); - if (!result) return nullptr; - - result->wordCount = word_count; - result->code = new uint32_t[word_count]; - if (!result->code) return nullptr; - - if (need_little_endian) { - memcpy(result->code, binary_bytes, sizeof(binary_bytes)); - } else { - uint8_t* code_bytes = reinterpret_cast(result->code); - for (size_t word = 0; word < word_count; ++word) { - code_bytes[4 * word] = binary_bytes[4 * word + 3]; - code_bytes[4 * word + 1] = binary_bytes[4 * word + 2]; - code_bytes[4 * word + 2] = binary_bytes[4 * word + 1]; - code_bytes[4 * word + 3] = binary_bytes[4 * word]; - } - } - - return result.release(); -} - -TEST_F(ValidateWebGPU, LittleEndianGood) { - DestroyBinary(); - binary_ = GenerateTrivialBinary(true); - EXPECT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_WEBGPU_0)); -} - -TEST_F(ValidateWebGPU, BigEndianBad) { - DestroyBinary(); - binary_ = GenerateTrivialBinary(false); - EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions(SPV_ENV_WEBGPU_0)); - EXPECT_THAT(getDiagnosticString(), - HasSubstr("WebGPU requires SPIR-V to be little endian.")); -} - -} // namespace -} // namespace val -} // namespace spvtools diff --git a/third_party/spirv-tools/tools/as/as.cpp b/third_party/spirv-tools/tools/as/as.cpp index f6e9629441..c8a44456a9 100644 --- a/third_party/spirv-tools/tools/as/as.cpp +++ b/third_party/spirv-tools/tools/as/as.cpp @@ -129,7 +129,7 @@ int main(int argc, char** argv) { } std::vector contents; - if (!ReadFile(inFile, "r", &contents)) return 1; + if (!ReadTextFile(inFile, &contents)) return 1; spv_binary binary; spv_diagnostic diagnostic = nullptr; diff --git a/third_party/spirv-tools/tools/cfg/cfg.cpp b/third_party/spirv-tools/tools/cfg/cfg.cpp index ce7f1c2241..a93488d545 100644 --- a/third_party/spirv-tools/tools/cfg/cfg.cpp +++ b/third_party/spirv-tools/tools/cfg/cfg.cpp @@ -104,7 +104,7 @@ int main(int argc, char** argv) { // Read the input binary. std::vector contents; - if (!ReadFile(inFile, "rb", &contents)) return 1; + if (!ReadBinaryFile(inFile, &contents)) return 1; spv_context context = spvContextCreate(kDefaultEnvironment); spv_diagnostic diagnostic = nullptr; diff --git a/third_party/spirv-tools/tools/dis/dis.cpp b/third_party/spirv-tools/tools/dis/dis.cpp index bdeeef11b0..64380db06f 100644 --- a/third_party/spirv-tools/tools/dis/dis.cpp +++ b/third_party/spirv-tools/tools/dis/dis.cpp @@ -180,7 +180,7 @@ int main(int argc, char** argv) { // Read the input binary. std::vector contents; - if (!ReadFile(inFile, "rb", &contents)) return 1; + if (!ReadBinaryFile(inFile, &contents)) return 1; // If printing to standard output, then spvBinaryToText should // do the printing. In particular, colour printing on Windows is diff --git a/third_party/spirv-tools/tools/fuzz/fuzz.cpp b/third_party/spirv-tools/tools/fuzz/fuzz.cpp index 5ee0fb18e7..422bea53b1 100644 --- a/third_party/spirv-tools/tools/fuzz/fuzz.cpp +++ b/third_party/spirv-tools/tools/fuzz/fuzz.cpp @@ -39,6 +39,8 @@ namespace { +enum class FuzzingTarget { kSpirv, kWgsl }; + // Check that the std::system function can actually be used. bool CheckExecuteCommand() { int res = std::system(nullptr); @@ -141,6 +143,12 @@ Options (in lexicographical order): that was used previously. - simple: each time a fuzzer pass is requested, one is provided at random from the set of enabled passes. + --fuzzing-target= + This option will adjust probabilities of applying certain + transformations s.t. the module always remains valid according + to the semantics of some fuzzing target. Available targets: + - spir-v - module is valid according to the SPIR-V spec. + - wgsl - module is valid according to the WGSL spec. --replay File from which to read a sequence of transformations to replay (instead of fuzzing) @@ -204,15 +212,15 @@ FuzzStatus ParseFlags( std::vector* interestingness_test, std::string* shrink_transformations_file, std::string* shrink_temp_file_prefix, - spvtools::fuzz::Fuzzer::RepeatedPassStrategy* repeated_pass_strategy, - spvtools::FuzzerOptions* fuzzer_options, + spvtools::fuzz::RepeatedPassStrategy* repeated_pass_strategy, + FuzzingTarget* fuzzing_target, spvtools::FuzzerOptions* fuzzer_options, spvtools::ValidatorOptions* validator_options) { uint32_t positional_arg_index = 0; bool only_positional_arguments_remain = false; bool force_render_red = false; *repeated_pass_strategy = - spvtools::fuzz::Fuzzer::RepeatedPassStrategy::kLoopedWithRecommendations; + spvtools::fuzz::RepeatedPassStrategy::kLoopedWithRecommendations; for (int argi = 1; argi < argc; ++argi) { const char* cur_arg = argv[argi]; @@ -250,14 +258,14 @@ FuzzStatus ParseFlags( sizeof("--repeated-pass-strategy=") - 1)) { std::string strategy = spvtools::utils::SplitFlagArgs(cur_arg).second; if (strategy == "looped") { - *repeated_pass_strategy = spvtools::fuzz::Fuzzer:: - RepeatedPassStrategy::kLoopedWithRecommendations; + *repeated_pass_strategy = + spvtools::fuzz::RepeatedPassStrategy::kLoopedWithRecommendations; } else if (strategy == "random") { - *repeated_pass_strategy = spvtools::fuzz::Fuzzer:: - RepeatedPassStrategy::kRandomWithRecommendations; + *repeated_pass_strategy = + spvtools::fuzz::RepeatedPassStrategy::kRandomWithRecommendations; } else if (strategy == "simple") { *repeated_pass_strategy = - spvtools::fuzz::Fuzzer::RepeatedPassStrategy::kSimple; + spvtools::fuzz::RepeatedPassStrategy::kSimple; } else { std::stringstream ss; ss << "Unknown repeated pass strategy '" << strategy << "'" @@ -266,6 +274,20 @@ FuzzStatus ParseFlags( spvtools::Error(FuzzDiagnostic, nullptr, {}, ss.str().c_str()); return {FuzzActions::STOP, 1}; } + } else if (0 == strncmp(cur_arg, "--fuzzing-target=", + sizeof("--fuzzing-target=") - 1)) { + std::string target = spvtools::utils::SplitFlagArgs(cur_arg).second; + if (target == "spir-v") { + *fuzzing_target = FuzzingTarget::kSpirv; + } else if (target == "wgsl") { + *fuzzing_target = FuzzingTarget::kWgsl; + } else { + std::stringstream ss; + ss << "Unknown fuzzing target '" << target << "'" << std::endl; + ss << "Valid options are 'spir-v' and 'wgsl'."; + spvtools::Error(FuzzDiagnostic, nullptr, {}, ss.str().c_str()); + return {FuzzActions::STOP, 1}; + } } else if (0 == strncmp(cur_arg, "--replay-range=", sizeof("--replay-range=") - 1)) { const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg); @@ -549,8 +571,8 @@ bool Fuzz(const spv_target_env& target_env, const std::vector& binary_in, const spvtools::fuzz::protobufs::FactSequence& initial_facts, const std::string& donors, - spvtools::fuzz::Fuzzer::RepeatedPassStrategy repeated_pass_strategy, - std::vector* binary_out, + spvtools::fuzz::RepeatedPassStrategy repeated_pass_strategy, + FuzzingTarget fuzzing_target, std::vector* binary_out, spvtools::fuzz::protobufs::TransformationSequence* transformations_applied) { auto message_consumer = spvtools::utils::CLIMessageConsumer; @@ -568,8 +590,8 @@ bool Fuzz(const spv_target_env& target_env, [donor_filename, message_consumer, target_env]() -> std::unique_ptr { std::vector donor_binary; - if (!ReadFile(donor_filename.c_str(), "rb", - &donor_binary)) { + if (!ReadBinaryFile(donor_filename.c_str(), + &donor_binary)) { return nullptr; } return spvtools::BuildModule(target_env, message_consumer, @@ -578,24 +600,46 @@ bool Fuzz(const spv_target_env& target_env, }); } - auto fuzz_result = - spvtools::fuzz::Fuzzer( - target_env, message_consumer, binary_in, initial_facts, - donor_suppliers, - spvtools::MakeUnique( - fuzzer_options->has_random_seed - ? fuzzer_options->random_seed - : static_cast(std::random_device()())), - fuzzer_options->all_passes_enabled, repeated_pass_strategy, - fuzzer_options->fuzzer_pass_validation_enabled, validator_options) - .Run(); - *binary_out = std::move(fuzz_result.transformed_binary); - *transformations_applied = std::move(fuzz_result.applied_transformations); - if (fuzz_result.status != - spvtools::fuzz::Fuzzer::FuzzerResultStatus::kComplete) { + std::unique_ptr ir_context; + if (!spvtools::fuzz::fuzzerutil::BuildIRContext(target_env, message_consumer, + binary_in, validator_options, + &ir_context)) { + spvtools::Error(FuzzDiagnostic, nullptr, {}, "Initial binary is invalid"); + return false; + } + + assert((fuzzing_target == FuzzingTarget::kWgsl || + fuzzing_target == FuzzingTarget::kSpirv) && + "Not all fuzzing targets are handled"); + auto fuzzer_context = spvtools::MakeUnique( + spvtools::MakeUnique( + fuzzer_options->has_random_seed + ? fuzzer_options->random_seed + : static_cast(std::random_device()())), + spvtools::fuzz::FuzzerContext::GetMinFreshId(ir_context.get()), + fuzzing_target == FuzzingTarget::kWgsl); + + auto transformation_context = + spvtools::MakeUnique( + spvtools::MakeUnique(ir_context.get()), + validator_options); + transformation_context->GetFactManager()->AddInitialFacts(message_consumer, + initial_facts); + + spvtools::fuzz::Fuzzer fuzzer( + std::move(ir_context), std::move(transformation_context), + std::move(fuzzer_context), message_consumer, donor_suppliers, + fuzzer_options->all_passes_enabled, repeated_pass_strategy, + fuzzer_options->fuzzer_pass_validation_enabled, validator_options); + auto fuzz_result = fuzzer.Run(0); + if (fuzz_result.status == + spvtools::fuzz::Fuzzer::Status::kFuzzerPassLedToInvalidModule) { spvtools::Error(FuzzDiagnostic, nullptr, {}, "Error running fuzzer"); return false; } + + fuzzer.GetIRContext()->module()->ToBinary(binary_out, true); + *transformations_applied = fuzzer.GetTransformationSequence(); return true; } @@ -656,7 +700,8 @@ int main(int argc, const char** argv) { std::vector interestingness_test; std::string shrink_transformations_file; std::string shrink_temp_file_prefix = "temp_"; - spvtools::fuzz::Fuzzer::RepeatedPassStrategy repeated_pass_strategy; + spvtools::fuzz::RepeatedPassStrategy repeated_pass_strategy; + auto fuzzing_target = FuzzingTarget::kSpirv; spvtools::FuzzerOptions fuzzer_options; spvtools::ValidatorOptions validator_options; @@ -665,14 +710,15 @@ int main(int argc, const char** argv) { ParseFlags(argc, argv, &in_binary_file, &out_binary_file, &donors_file, &replay_transformations_file, &interestingness_test, &shrink_transformations_file, &shrink_temp_file_prefix, - &repeated_pass_strategy, &fuzzer_options, &validator_options); + &repeated_pass_strategy, &fuzzing_target, &fuzzer_options, + &validator_options); if (status.action == FuzzActions::STOP) { return status.code; } std::vector binary_in; - if (!ReadFile(in_binary_file.c_str(), "rb", &binary_in)) { + if (!ReadBinaryFile(in_binary_file.c_str(), &binary_in)) { return 1; } @@ -703,16 +749,16 @@ int main(int argc, const char** argv) { switch (status.action) { case FuzzActions::FORCE_RENDER_RED: - if (!spvtools::fuzz::ForceRenderRed(target_env, validator_options, - binary_in, initial_facts, - &binary_out)) { + if (!spvtools::fuzz::ForceRenderRed( + target_env, validator_options, binary_in, initial_facts, + spvtools::utils::CLIMessageConsumer, &binary_out)) { return 1; } break; case FuzzActions::FUZZ: if (!Fuzz(target_env, fuzzer_options, validator_options, binary_in, - initial_facts, donors_file, repeated_pass_strategy, &binary_out, - &transformations_applied)) { + initial_facts, donors_file, repeated_pass_strategy, + fuzzing_target, &binary_out, &transformations_applied)) { return 1; } break; diff --git a/third_party/spirv-tools/tools/io.h b/third_party/spirv-tools/tools/io.h index f9cfd9d182..aff9eabd97 100644 --- a/third_party/spirv-tools/tools/io.h +++ b/third_party/spirv-tools/tools/io.h @@ -20,45 +20,101 @@ #include #include -// Appends the content from the file named as |filename| to |data|, assuming -// each element in the file is of type |T|. The file is opened with the given -// |mode|. If |filename| is nullptr or "-", reads from the standard input, but -// reopened with the given mode. If any error occurs, writes error messages to -// standard error and returns false. +#if defined(SPIRV_WINDOWS) +#include +#include + +#define SET_STDIN_TO_BINARY_MODE() _setmode(_fileno(stdin), O_BINARY); +#define SET_STDIN_TO_TEXT_MODE() _setmode(_fileno(stdin), O_TEXT); +#else +#define SET_STDIN_TO_BINARY_MODE() +#define SET_STDIN_TO_TEXT_MODE() +#endif + +// Appends the contents of the |file| to |data|, assuming each element in the +// file is of type |T|. template -bool ReadFile(const char* filename, const char* mode, std::vector* data) { +void ReadFile(FILE* file, std::vector* data) { + if (file == nullptr) return; + const int buf_size = 1024; - const bool use_file = filename && strcmp("-", filename); - if (FILE* fp = - (use_file ? fopen(filename, mode) : freopen(nullptr, mode, stdin))) { - T buf[buf_size]; - while (size_t len = fread(buf, sizeof(T), buf_size, fp)) { - data->insert(data->end(), buf, buf + len); - } - if (ftell(fp) == -1L) { - if (ferror(fp)) { - fprintf(stderr, "error: error reading file '%s'\n", filename); - if (use_file) fclose(fp); - return false; - } - } else { - if (sizeof(T) != 1 && (ftell(fp) % sizeof(T))) { - fprintf( - stderr, - "error: file size should be a multiple of %zd; file '%s' corrupt\n", - sizeof(T), filename); - if (use_file) fclose(fp); - return false; - } - } - if (use_file) fclose(fp); - } else { + T buf[buf_size]; + while (size_t len = fread(buf, sizeof(T), buf_size, file)) { + data->insert(data->end(), buf, buf + len); + } +} + +// Returns true if |file| has encountered an error opening the file or reading +// the file as a series of element of type |T|. If there was an error, writes an +// error message to standard error. +template +bool WasFileCorrectlyRead(FILE* file, const char* filename) { + if (file == nullptr) { fprintf(stderr, "error: file does not exist '%s'\n", filename); return false; } + + if (ftell(file) == -1L) { + if (ferror(file)) { + fprintf(stderr, "error: error reading file '%s'\n", filename); + return false; + } + } else { + if (sizeof(T) != 1 && (ftell(file) % sizeof(T))) { + fprintf( + stderr, + "error: file size should be a multiple of %zd; file '%s' corrupt\n", + sizeof(T), filename); + return false; + } + } return true; } +// Appends the contents of the file named |filename| to |data|, assuming +// each element in the file is of type |T|. The file is opened as a binary file +// If |filename| is nullptr or "-", reads from the standard input, but +// reopened as a binary file. If any error occurs, writes error messages to +// standard error and returns false. +template +bool ReadBinaryFile(const char* filename, std::vector* data) { + const bool use_file = filename && strcmp("-", filename); + FILE* fp = nullptr; + if (use_file) { + fp = fopen(filename, "rb"); + } else { + SET_STDIN_TO_BINARY_MODE(); + fp = stdin; + } + + ReadFile(fp, data); + bool succeeded = WasFileCorrectlyRead(fp, filename); + if (use_file) fclose(fp); + return succeeded; +} + +// Appends the contents of the file named |filename| to |data|, assuming +// each element in the file is of type |T|. The file is opened as a text file +// If |filename| is nullptr or "-", reads from the standard input, but +// reopened as a text file. If any error occurs, writes error messages to +// standard error and returns false. +template +bool ReadTextFile(const char* filename, std::vector* data) { + const bool use_file = filename && strcmp("-", filename); + FILE* fp = nullptr; + if (use_file) { + fp = fopen(filename, "r"); + } else { + SET_STDIN_TO_TEXT_MODE(); + fp = stdin; + } + + ReadFile(fp, data); + bool succeeded = WasFileCorrectlyRead(fp, filename); + if (use_file) fclose(fp); + return succeeded; +} + // Writes the given |data| into the file named as |filename| using the given // |mode|, assuming |data| is an array of |count| elements of type |T|. If // |filename| is nullptr or "-", writes to standard output. If any error occurs, diff --git a/third_party/spirv-tools/tools/link/linker.cpp b/third_party/spirv-tools/tools/link/linker.cpp index 82d430ebb7..359e803015 100644 --- a/third_party/spirv-tools/tools/link/linker.cpp +++ b/third_party/spirv-tools/tools/link/linker.cpp @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "spirv-tools/linker.hpp" + #include #include #include @@ -19,42 +21,56 @@ #include "source/spirv_target_env.h" #include "source/table.h" #include "spirv-tools/libspirv.hpp" -#include "spirv-tools/linker.hpp" #include "tools/io.h" -void print_usage(char* argv0) { - std::string target_env_list = spvTargetEnvList(27, 95); +namespace { + +const auto kDefaultEnvironment = SPV_ENV_UNIVERSAL_1_5; + +void print_usage(const char* program) { + std::string target_env_list = spvTargetEnvList(16, 80); + // NOTE: Please maintain flags in lexicographical order. printf( R"(%s - Link SPIR-V binary files together. -USAGE: %s [options] [ ...] +USAGE: %s [options] [-o ] ... -The SPIR-V binaries are read from the different . +The SPIR-V binaries are read from the different (s). +The SPIR-V resulting linked binary module is written to the file "out.spv" +unless the -o option is used; if is "-", it is written to the standard +output. NOTE: The linker is a work in progress. -Options: - -h, --help Print this help. - -o Name of the resulting linked SPIR-V binary. - --create-library Link the binaries into a library, keeping all exported symbols. - --allow-partial-linkage Allow partial linkage by accepting imported symbols to be unresolved. - --verify-ids Verify that IDs in the resulting modules are truly unique. - --version Display linker version information - --target-env {%s} - Use validation rules from the specified environment. +Options (in lexicographical order): + --allow-partial-linkage + Allow partial linkage by accepting imported symbols to be + unresolved. + --create-library + Link the binaries into a library, keeping all exported symbols. + -h, --help + Print this help. + --target-env + Set the target environment. Without this flag the target + environment defaults to spv1.5. must be one of + {%s} + --verify-ids + Verify that IDs in the resulting modules are truly unique. + --version + Display linker version information )", - argv0, argv0, target_env_list.c_str()); + program, program, target_env_list.c_str()); } +} // namespace + int main(int argc, char** argv) { std::vector inFiles; const char* outFile = nullptr; - spv_target_env target_env = SPV_ENV_UNIVERSAL_1_0; + spv_target_env target_env = kDefaultEnvironment; spvtools::LinkerOptions options; - bool continue_processing = true; - int return_code = 0; - for (int argi = 1; continue_processing && argi < argc; ++argi) { + for (int argi = 1; argi < argc; ++argi) { const char* cur_arg = argv[argi]; if ('-' == cur_arg[0]) { if (0 == strcmp(cur_arg, "-o")) { @@ -63,55 +79,48 @@ int main(int argc, char** argv) { outFile = argv[++argi]; } else { fprintf(stderr, "error: More than one output file specified\n"); - continue_processing = false; - return_code = 1; + return 1; } } else { fprintf(stderr, "error: Missing argument to %s\n", cur_arg); - continue_processing = false; - return_code = 1; + return 1; } - } else if (0 == strcmp(cur_arg, "--create-library")) { - options.SetCreateLibrary(true); - } else if (0 == strcmp(cur_arg, "--verify-ids")) { - options.SetVerifyIds(true); } else if (0 == strcmp(cur_arg, "--allow-partial-linkage")) { options.SetAllowPartialLinkage(true); - } else if (0 == strcmp(cur_arg, "--version")) { - printf("%s\n", spvSoftwareVersionDetailsString()); - // TODO(dneto): Add OpenCL 2.2 at least. - printf("Targets:\n %s\n %s\n %s\n", - spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_1), - spvTargetEnvDescription(SPV_ENV_VULKAN_1_0), - spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_2)); - continue_processing = false; - return_code = 0; + } else if (0 == strcmp(cur_arg, "--create-library")) { + options.SetCreateLibrary(true); } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) { print_usage(argv[0]); - continue_processing = false; - return_code = 0; + return 0; } else if (0 == strcmp(cur_arg, "--target-env")) { if (argi + 1 < argc) { const auto env_str = argv[++argi]; if (!spvParseTargetEnv(env_str, &target_env)) { fprintf(stderr, "error: Unrecognized target env: %s\n", env_str); - continue_processing = false; - return_code = 1; + return 1; } } else { fprintf(stderr, "error: Missing argument to --target-env\n"); - continue_processing = false; - return_code = 1; + return 1; } + } else if (0 == strcmp(cur_arg, "--verify-ids")) { + options.SetVerifyIds(true); + } else if (0 == strcmp(cur_arg, "--version")) { + printf("%s\n", spvSoftwareVersionDetailsString()); + printf("Target: %s\n", spvTargetEnvDescription(target_env)); + return 0; + } else { + fprintf(stderr, "error: Unrecognized option: %s\n\n", argv[argi]); + print_usage(argv[0]); + return 1; } } else { inFiles.push_back(cur_arg); } } - // Exit if command line parsing was not successful. - if (!continue_processing) { - return return_code; + if (!outFile) { + outFile = "out.spv"; } if (inFiles.empty()) { @@ -121,7 +130,7 @@ int main(int argc, char** argv) { std::vector> contents(inFiles.size()); for (size_t i = 0u; i < inFiles.size(); ++i) { - if (!ReadFile(inFiles[i], "rb", &contents[i])) return 1; + if (!ReadBinaryFile(inFiles[i], &contents[i])) return 1; } const spvtools::MessageConsumer consumer = [](spv_message_level_t level, diff --git a/third_party/spirv-tools/tools/opt/opt.cpp b/third_party/spirv-tools/tools/opt/opt.cpp index 66f9228632..53bf31d6d9 100644 --- a/third_party/spirv-tools/tools/opt/opt.cpp +++ b/third_party/spirv-tools/tools/opt/opt.cpp @@ -79,18 +79,6 @@ std::string GetSizePasses() { return GetListOfPassesAsString(optimizer); } -std::string GetVulkanToWebGPUPasses() { - spvtools::Optimizer optimizer(SPV_ENV_VULKAN_1_1); - optimizer.RegisterVulkanToWebGPUPasses(); - return GetListOfPassesAsString(optimizer); -} - -std::string GetWebGPUToVulkanPasses() { - spvtools::Optimizer optimizer(SPV_ENV_WEBGPU_0); - optimizer.RegisterWebGPUToVulkanPasses(); - return GetListOfPassesAsString(optimizer); -} - void PrintUsage(const char* program) { std::string target_env_list = spvTargetEnvList(16, 80); // NOTE: Please maintain flags in lexicographical order. @@ -239,10 +227,6 @@ Options (in lexicographical order):)", values, providing guarantees that satisfy Vulkan's robustBufferAccess rules.)"); printf(R"( - --generate-webgpu-initializers - Adds initial values to OpVariable instructions that are missing - them, due to their storage type requiring them for WebGPU.)"); - printf(R"( --if-conversion Convert if-then-else like assignments into OpSelect.)"); printf(R"( @@ -261,11 +245,6 @@ Options (in lexicographical order):)", option --relax-logical-pointer to the validator.)", GetLegalizationPasses().c_str()); printf(R"( - --legalize-vector-shuffle - Converts any usages of 0xFFFFFFFF for the literals in - OpVectorShuffle to a literal 0. This is done since 0xFFFFFFFF is - forbidden in WebGPU.)"); - printf(R"( --local-redundancy-elimination Looks for instructions in the same basic block that compute the same value, and deletes the redundant ones.)"); @@ -427,6 +406,12 @@ Options (in lexicographical order):)", Removes duplicate types, decorations, capabilities and extension instructions.)"); printf(R"( + --remove-unused-interface-variables + Removes variables referenced on the |OpEntryPoint| instruction + that are not referenced in the entry point function or any function + in its call tree. Note that this could cause the shader interface + to no longer match other shader stages.)"); + printf(R"( --replace-invalid-opcode Replaces instructions whose opcode is valid for shader modules, but not for the current shader stage. To have an effect, all @@ -463,13 +448,6 @@ Options (in lexicographical order):)", Forwards this option to the validator. See the validator help for details.)"); printf(R"( - --split-invalid-unreachable - Attempts to legalize for WebGPU cases where an unreachable - merge-block is also a continue-target by splitting it into two - separate blocks. There exist legal, for Vulkan, instances of this - pattern that cannot be converted into legal WebGPU, so this - conversion may not succeed.)"); - printf(R"( --skip-validation Will not validate the SPIR-V before optimizing. If the SPIR-V is invalid, the optimizer may fail or generate incorrect code. @@ -513,39 +491,15 @@ Options (in lexicographical order):)", removes them from the vector. Note this would still leave around lots of dead code that a pass of ADCE will be able to remove.)"); printf(R"( - --vulkan-to-webgpu - Turns on the prescribed passes for converting from Vulkan to - WebGPU and sets the target environment to webgpu0. Other passes - may be turned on via additional flags, but such combinations are - not tested. - Using --target-env with this flag is not allowed. - - This flag is the equivalent of passing in --target-env=webgpu0 - and specifying the following optimization code names: - %s - - NOTE: This flag is a WIP and its behaviour is subject to change.)", - GetVulkanToWebGPUPasses().c_str()); - printf(R"( - --webgpu-to-vulkan - Turns on the prescribed passes for converting from WebGPU to - Vulkan and sets the target environment to vulkan1.1. Other passes - may be turned on via additional flags, but such combinations are - not tested. - Using --target-env with this flag is not allowed. - - This flag is the equivalent of passing in --target-env=vulkan1.1 - and specifying the following optimization code names: - %s - - NOTE: This flag is a WIP and its behaviour is subject to change.)", - GetWebGPUToVulkanPasses().c_str()); - printf(R"( --workaround-1209 Rewrites instructions for which there are known driver bugs to avoid triggering those bugs. Current workarounds: Avoid OpUnreachable in loops.)"); printf(R"( + --workgroup-scalar-block-layout + Forwards this option to the validator. See the validator help + for details.)"); + printf(R"( --wrap-opkill Replaces all OpKill instructions in functions that can be called from a continue construct with a function call to a function @@ -714,9 +668,6 @@ OptStatus ParseFlags(int argc, const char** argv, spvtools::ValidatorOptions* validator_options, spvtools::OptimizerOptions* optimizer_options) { std::vector pass_flags; - bool target_env_set = false; - bool vulkan_to_webgpu_set = false; - bool webgpu_to_vulkan_set = false; for (int argi = 1; argi < argc; ++argi) { const char* cur_arg = argv[argi]; if ('-' == cur_arg[0]) { @@ -781,19 +732,6 @@ OptStatus ParseFlags(int argc, const char** argv, max_id_bound); } else if (0 == strncmp(cur_arg, "--target-env=", sizeof("--target-env=") - 1)) { - target_env_set = true; - if (vulkan_to_webgpu_set) { - spvtools::Error(opt_diagnostic, nullptr, {}, - "--vulkan-to-webgpu defines the target environment, " - "so --target-env cannot be set at the same time"); - return {OPT_STOP, 1}; - } - if (webgpu_to_vulkan_set) { - spvtools::Error(opt_diagnostic, nullptr, {}, - "--webgpu-to-vulkan defines the target environment, " - "so --target-env cannot be set at the same time"); - return {OPT_STOP, 1}; - } const auto split_flag = spvtools::utils::SplitFlagArgs(cur_arg); const auto target_env_str = split_flag.second.c_str(); spv_target_env target_env; @@ -803,42 +741,6 @@ OptStatus ParseFlags(int argc, const char** argv, return {OPT_STOP, 1}; } optimizer->SetTargetEnv(target_env); - } else if (0 == strcmp(cur_arg, "--vulkan-to-webgpu")) { - vulkan_to_webgpu_set = true; - if (target_env_set) { - spvtools::Error(opt_diagnostic, nullptr, {}, - "--vulkan-to-webgpu defines the target environment, " - "so --target-env cannot be set at the same time"); - return {OPT_STOP, 1}; - } - if (webgpu_to_vulkan_set) { - spvtools::Error(opt_diagnostic, nullptr, {}, - "Cannot use both --webgpu-to-vulkan and " - "--vulkan-to-webgpu at the same time, invoke twice " - "if you are wanting to go to and from"); - return {OPT_STOP, 1}; - } - - optimizer->SetTargetEnv(SPV_ENV_VULKAN_1_1); - optimizer->RegisterVulkanToWebGPUPasses(); - } else if (0 == strcmp(cur_arg, "--webgpu-to-vulkan")) { - webgpu_to_vulkan_set = true; - if (target_env_set) { - spvtools::Error(opt_diagnostic, nullptr, {}, - "--webgpu-to-vulkan defines the target environment, " - "so --target-env cannot be set at the same time"); - return {OPT_STOP, 1}; - } - if (vulkan_to_webgpu_set) { - spvtools::Error(opt_diagnostic, nullptr, {}, - "Cannot use both --webgpu-to-vulkan and " - "--vulkan-to-webgpu at the same time, invoke twice " - "if you are wanting to go to and from"); - return {OPT_STOP, 1}; - } - - optimizer->SetTargetEnv(SPV_ENV_WEBGPU_0); - optimizer->RegisterWebGPUToVulkanPasses(); } else if (0 == strcmp(cur_arg, "--validate-after-all")) { optimizer->SetValidateAfterAll(true); } else if (0 == strcmp(cur_arg, "--before-hlsl-legalization")) { @@ -849,6 +751,8 @@ OptStatus ParseFlags(int argc, const char** argv, validator_options->SetRelaxBlockLayout(true); } else if (0 == strcmp(cur_arg, "--scalar-block-layout")) { validator_options->SetScalarBlockLayout(true); + } else if (0 == strcmp(cur_arg, "--workgroup-scalar-block-layout")) { + validator_options->SetWorkgroupScalarBlockLayout(true); } else if (0 == strcmp(cur_arg, "--skip-block-layout")) { validator_options->SetSkipBlockLayout(true); } else if (0 == strcmp(cur_arg, "--relax-struct-store")) { @@ -909,7 +813,7 @@ int main(int argc, const char** argv) { } std::vector binary; - if (!ReadFile(in_file, "rb", &binary)) { + if (!ReadBinaryFile(in_file, &binary)) { return 1; } diff --git a/third_party/spirv-tools/tools/reduce/reduce.cpp b/third_party/spirv-tools/tools/reduce/reduce.cpp index 49a5efef5e..4447b3569e 100644 --- a/third_party/spirv-tools/tools/reduce/reduce.cpp +++ b/third_party/spirv-tools/tools/reduce/reduce.cpp @@ -318,7 +318,7 @@ int main(int argc, const char** argv) { reducer.SetMessageConsumer(spvtools::utils::CLIMessageConsumer); std::vector binary_in; - if (!ReadFile(in_binary_file.c_str(), "rb", &binary_in)) { + if (!ReadBinaryFile(in_binary_file.c_str(), &binary_in)) { return 1; } diff --git a/third_party/spirv-tools/tools/sva/yarn.lock b/third_party/spirv-tools/tools/sva/yarn.lock index 34a1808e22..afa11f6c5a 100644 --- a/third_party/spirv-tools/tools/sva/yarn.lock +++ b/third_party/spirv-tools/tools/sva/yarn.lock @@ -694,9 +694,9 @@ get-stream@^4.0.0: pump "^3.0.0" glob-parent@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.0.0.tgz#1dc99f0f39b006d3e92c2c284068382f0c20e954" - integrity sha512-Z2RwiujPRGluePM6j699ktJYxmPpJKCfpGA13jz2hmFZC7gKetzrWvg5KN3+OsIFmydGyZ1AVwERCq1w/ZZwRg== + version "5.1.2" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4" + integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow== dependencies: is-glob "^4.0.1" @@ -795,9 +795,9 @@ inherits@2: integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@~1.3.0: - version "1.3.5" - resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927" - integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw== + version "1.3.7" + resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.7.tgz#a09363e1911972ea16d7a8851005d84cf09a9a84" + integrity sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ== inquirer@^6.4.1: version "6.5.2" @@ -938,9 +938,9 @@ locate-path@^3.0.0: path-exists "^3.0.0" lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.14: - version "4.17.19" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" - integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== + version "4.17.21" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" + integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== log-symbols@2.2.0: version "2.2.0" diff --git a/third_party/spirv-tools/tools/val/val.cpp b/third_party/spirv-tools/tools/val/val.cpp index 19b8c776a8..21a7d8f435 100644 --- a/third_party/spirv-tools/tools/val/val.cpp +++ b/third_party/spirv-tools/tools/val/val.cpp @@ -58,6 +58,7 @@ Options: uniform, storage buffer, and push constant layouts. Scalar layout rules are more permissive than relaxed block layout so in effect this will override the --relax-block-layout option. + --workgroup-scalar-block-layout Enable scalar block layout when checking Workgroup block layouts. --skip-block-layout Skip checking standard uniform/storage buffer layout. Overrides any --relax-block-layout or --scalar-block-layout option. --relax-struct-store Allow store from one struct type to a @@ -108,7 +109,7 @@ int main(int argc, char** argv) { printf("%s\n", spvSoftwareVersionDetailsString()); printf( "Targets:\n %s\n %s\n %s\n %s\n %s\n %s\n %s\n %s\n %s\n " - "%s\n %s\n", + "%s\n", spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_0), spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_1), spvTargetEnvDescription(SPV_ENV_UNIVERSAL_1_2), @@ -118,8 +119,7 @@ int main(int argc, char** argv) { spvTargetEnvDescription(SPV_ENV_OPENCL_2_2), spvTargetEnvDescription(SPV_ENV_VULKAN_1_0), spvTargetEnvDescription(SPV_ENV_VULKAN_1_1), - spvTargetEnvDescription(SPV_ENV_VULKAN_1_1_SPIRV_1_4), - spvTargetEnvDescription(SPV_ENV_WEBGPU_0)); + spvTargetEnvDescription(SPV_ENV_VULKAN_1_1_SPIRV_1_4)); continue_processing = false; return_code = 0; } else if (0 == strcmp(cur_arg, "--help") || 0 == strcmp(cur_arg, "-h")) { @@ -149,6 +149,8 @@ int main(int argc, char** argv) { options.SetUniformBufferStandardLayout(true); } else if (0 == strcmp(cur_arg, "--scalar-block-layout")) { options.SetScalarBlockLayout(true); + } else if (0 == strcmp(cur_arg, "--workgroup-scalar-block-layout")) { + options.SetWorkgroupScalarBlockLayout(true); } else if (0 == strcmp(cur_arg, "--skip-block-layout")) { options.SetSkipBlockLayout(true); } else if (0 == strcmp(cur_arg, "--relax-struct-store")) { @@ -184,7 +186,7 @@ int main(int argc, char** argv) { } std::vector contents; - if (!ReadFile(inFile, "rb", &contents)) return 1; + if (!ReadBinaryFile(inFile, &contents)) return 1; spvtools::SpirvTools tools(target_env); tools.SetMessageConsumer(spvtools::utils::CLIMessageConsumer); diff --git a/third_party/spirv-tools/utils/check_copyright.py b/third_party/spirv-tools/utils/check_copyright.py index 39d27cb7dd..49892ee6ea 100755 --- a/third_party/spirv-tools/utils/check_copyright.py +++ b/third_party/spirv-tools/utils/check_copyright.py @@ -36,10 +36,14 @@ AUTHORS = ['The Khronos Group Inc.', 'André Perez Maselco', 'Vasyl Teliman', 'Advanced Micro Devices, Inc.', - 'Stefano Milizia'] -CURRENT_YEAR='2020' + 'Stefano Milizia', + 'Alastair F. Donaldson', + 'Mostafa Ashraf', + 'Shiyu Liu', + 'ZHOU He'] +CURRENT_YEAR='2021' -YEARS = '(2014-2016|2015-2016|2015-2020|2016|2016-2017|2017|2017-2019|2018|2019|2020)' +YEARS = '(2014-2016|2015-2016|2015-2020|2016|2016-2017|2017|2017-2019|2018|2019|2020|2021)' COPYRIGHT_RE = re.compile( 'Copyright \(c\) {} ({})'.format(YEARS, '|'.join(AUTHORS))) @@ -128,7 +132,7 @@ def insert_copyright(author, glob, comment_prefix): update_file = False for line in fileinput.input(file, inplace=1): emit = True - if state is 0: + if state == 0: if COPYRIGHT_RE.search(line): state = 1 elif skip(line): @@ -139,7 +143,7 @@ def insert_copyright(author, glob, comment_prefix): sys.stdout.write(licensed) # Assume there isn't a previous license notice. state = 1 - elif state is 1: + elif state == 1: if MIT_BEGIN_RE.search(line): state = 2 emit = False @@ -147,7 +151,7 @@ def insert_copyright(author, glob, comment_prefix): # Assume an Apache license is preceded by a copyright # notice. So just emit it like the rest of the file. state = 9 - elif state is 2: + elif state == 2: # Replace the MIT license with Apache 2 emit = False if MIT_END_RE.search(line): diff --git a/third_party/spirv-tools/utils/check_symbol_exports.py b/third_party/spirv-tools/utils/check_symbol_exports.py index bcd77da687..7795d72bc9 100755 --- a/third_party/spirv-tools/utils/check_symbol_exports.py +++ b/third_party/spirv-tools/utils/check_symbol_exports.py @@ -12,7 +12,13 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. -"""Checks names of global exports from a library.""" +"""Ensures that all externally visible functions in the library have an appropriate name + +Appropriate function names are: + - names starting with spv, + - anything in a namespace, + - functions added by the protobuf compiler, + - and weak definitions of new and delete.""" import os.path import re @@ -46,14 +52,16 @@ def check_library(library): exports are namespaced or begin with spv (in either C or C++ styles) then return 0. Otherwise emit a message and return 1.""" - # The pattern for a global symbol record - symbol_pattern = re.compile(r'^[0-aA-Fa-f]+ g *F \.text.*[0-9A-Fa-f]+ +(.*)') + # The pattern for an externally visible symbol record + symbol_pattern = re.compile(r'^[0-aA-Fa-f]+ +([wg]) *F \.text.*[0-9A-Fa-f]+ +(.*)') # Ok patterns are as follows, assuming Itanium name mangling: # spv[A-Z] : extern "C" symbol starting with spv # _ZN : something in a namespace + # _ZSt : something in the standard namespace + # _ZZN : something in a local scope and namespace # _Z[0-9]+spv[A-Z_] : C++ symbol starting with spv[A-Z_] - symbol_ok_pattern = re.compile(r'^(spv[A-Z]|_ZN|_Z[0-9]+spv[A-Z_])') + symbol_ok_pattern = re.compile(r'^(spv[A-Z]|_ZN|_ZSt|_ZZN|_Z[0-9]+spv[A-Z_])') # In addition, the following pattern allowlists global functions that are added # by the protobuf compiler: @@ -61,18 +69,31 @@ def check_library(library): # - InitDefaults_spvtoolsfuzz_2eproto() symbol_allowlist_pattern = re.compile(r'_Z[0-9]+(InitDefaults|AddDescriptors)_spvtoolsfuzz_2eprotov') + symbol_is_new_or_delete = re.compile(r'^(_Zna|_Znw|_Zdl|_Zda)') + # Compilaion for Arm has various thunks for constructors, destructors, vtables. + # They are weak. + symbol_is_thunk = re.compile(r'^_ZT') + + # This occurs in NDK builds. + symbol_is_hidden = re.compile(r'^\.hidden ') + seen = set() result = 0 for line in command_output(['objdump', '-t', library], '.').split('\n'): match = symbol_pattern.search(line) if match: - symbol = match.group(1) + linkage = match.group(1) + symbol = match.group(2) if symbol not in seen: seen.add(symbol) #print("look at '{}'".format(symbol)) - if not (symbol_allowlist_pattern.match(symbol) or symbol_ok_pattern.match(symbol)): - print('{}: error: Unescaped exported symbol: {}'.format(PROG, symbol)) - result = 1 + if not (symbol_is_new_or_delete.match(symbol) and linkage == 'w'): + if not (symbol_is_thunk.match(symbol) and linkage == 'w'): + if not (symbol_allowlist_pattern.match(symbol) or + symbol_ok_pattern.match(symbol) or + symbol_is_hidden.match(symbol)): + print('{}: error: Unescaped exported symbol: {}'.format(PROG, symbol)) + result = 1 return result diff --git a/third_party/spirv-tools/utils/generate_grammar_tables.py b/third_party/spirv-tools/utils/generate_grammar_tables.py index 2a67733697..9ccf410b9f 100755 --- a/third_party/spirv-tools/utils/generate_grammar_tables.py +++ b/third_party/spirv-tools/utils/generate_grammar_tables.py @@ -523,17 +523,17 @@ def generate_operand_kind_table(enums): enums = [generate_enum_operand_kind(e, exts) for e in enums] exts_arrays = generate_extension_arrays(exts) - # We have three operand kinds that requires their optional counterpart to + # We have a few operand kinds that require their optional counterpart to # exist in the operand info table. - three_optional_enums = ['ImageOperands', 'AccessQualifier', 'MemoryAccess'] - three_optional_enums = [e for e in enums if e[0] in three_optional_enums] - enums.extend(three_optional_enums) + optional_enums = ['ImageOperands', 'AccessQualifier', 'MemoryAccess', 'PackedVectorFormat'] + optional_enums = [e for e in enums if e[0] in optional_enums] + enums.extend(optional_enums) enum_kinds, enum_names, enum_entries = zip(*enums) - # Mark the last three as optional ones. - enum_quantifiers = [''] * (len(enums) - 3) + ['?'] * 3 + # Mark the last few as optional ones. + enum_quantifiers = [''] * (len(enums) - len(optional_enums)) + ['?'] * len(optional_enums) # And we don't want redefinition of them. - enum_entries = enum_entries[:-3] + enum_entries = enum_entries[:-len(optional_enums)] enum_kinds = [convert_operand_kind(e) for e in zip(enum_kinds, enum_quantifiers)] table_entries = zip(enum_kinds, enum_names, enum_names) @@ -601,7 +601,7 @@ def generate_extension_to_string_mapping(extensions): ' return "{extension}";\n' function += ''.join([template.format(extension=extension) for extension in extensions]) - function += ' };\n\n return "";\n}' + function += ' }\n\n return "";\n}' return function @@ -647,7 +647,7 @@ def generate_capability_to_string_mapping(operand_kinds): function += ' case SpvCapabilityMax:\n' \ ' assert(0 && "Attempting to convert SpvCapabilityMax to string");\n' \ ' return "";\n' - function += ' };\n\n return "";\n}' + function += ' }\n\n return "";\n}' return function diff --git a/third_party/spirv-tools/utils/git-sync-deps b/third_party/spirv-tools/utils/git-sync-deps index 0575641324..eecfbe93bb 100755 --- a/third_party/spirv-tools/utils/git-sync-deps +++ b/third_party/spirv-tools/utils/git-sync-deps @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # Copyright 2014 Google Inc. # # Redistribution and use in source and binary forms, with or without diff --git a/third_party/spirv-tools/utils/vscode/README.md b/third_party/spirv-tools/utils/vscode/README.md index bc022112bf..d7aa2b4132 100644 --- a/third_party/spirv-tools/utils/vscode/README.md +++ b/third_party/spirv-tools/utils/vscode/README.md @@ -1,12 +1,20 @@ # Visual Studio Code extension for SPIR-V disassembly files -This directory holds a Visual Studio Code extension adding syntax highlighting for SPIR-V assembly files (`.spvasm`) +This directory holds a Visual Studio Code language server extension for SPIR-V assembly files (`.spvasm`) + +The extension supports: +* Syntax highlighting +* Jump to definition +* Find all references +* Symbol renaming +* Operand hover information +* Formatting ## Dependencies In order to build and install the Visual Studio Code language server extension, you will need to install and have on your `PATH` the following dependencies: * [`npm`](https://www.npmjs.com/) -* [`golang`](https://golang.org/) +* [`golang 1.16+`](https://golang.org/) ## Installing (macOS / Linux) diff --git a/third_party/spirv-tools/utils/vscode/go.mod b/third_party/spirv-tools/utils/vscode/go.mod new file mode 100644 index 0000000000..ea4901a448 --- /dev/null +++ b/third_party/spirv-tools/utils/vscode/go.mod @@ -0,0 +1,8 @@ +module github.com/KhronosGroup/SPIRV-Tools/utils/vscode + +go 1.16 + +require ( + github.com/pkg/errors v0.9.1 + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 +) diff --git a/third_party/spirv-tools/utils/vscode/go.sum b/third_party/spirv-tools/utils/vscode/go.sum new file mode 100644 index 0000000000..328c85785e --- /dev/null +++ b/third_party/spirv-tools/utils/vscode/go.sum @@ -0,0 +1,4 @@ +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/third_party/spirv-tools/utils/vscode/install.bat b/third_party/spirv-tools/utils/vscode/install.bat index 21a52ecdd6..aa06fa91a0 100644 --- a/third_party/spirv-tools/utils/vscode/install.bat +++ b/third_party/spirv-tools/utils/vscode/install.bat @@ -23,7 +23,7 @@ copy %ROOT_PATH%\extension.js %EXT_PATH% copy %ROOT_PATH%\package.json %EXT_PATH% copy %ROOT_PATH%\spirv.json %EXT_PATH% -go build -o %EXT_PATH%\langsvr %ROOT_PATH%\src\langsvr.go +go build -o %EXT_PATH%\langsvr.exe %ROOT_PATH%\src\langsvr.go @pushd %EXT_PATH% call npm install diff --git a/third_party/spirv-tools/utils/vscode/install.sh b/third_party/spirv-tools/utils/vscode/install.sh index 01fc914068..de54c62396 100755 --- a/third_party/spirv-tools/utils/vscode/install.sh +++ b/third_party/spirv-tools/utils/vscode/install.sh @@ -18,15 +18,17 @@ set -e # Fail on any error. EXT_PATH=~/.vscode/extensions/google.spirvls-0.0.1 ROOT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" -go run ${ROOT_PATH}/src/tools/gen-grammar.go --cache ${ROOT_PATH}/cache --template ${ROOT_PATH}/spirv.json.tmpl --out ${ROOT_PATH}/spirv.json -go run ${ROOT_PATH}/src/tools/gen-grammar.go --cache ${ROOT_PATH}/cache --template ${ROOT_PATH}/src/schema/schema.go.tmpl --out ${ROOT_PATH}/src/schema/schema.go +pushd ${ROOT_PATH} + go run ./src/tools/gen-grammar.go --cache ./cache --template ./spirv.json.tmpl --out ./spirv.json + go run ./src/tools/gen-grammar.go --cache ./cache --template ./src/schema/schema.go.tmpl --out ./src/schema/schema.go -mkdir -p ${EXT_PATH} -cp ${ROOT_PATH}/extension.js ${EXT_PATH} -cp ${ROOT_PATH}/package.json ${EXT_PATH} -cp ${ROOT_PATH}/spirv.json ${EXT_PATH} + mkdir -p ${EXT_PATH} + cp ./extension.js ${EXT_PATH} + cp ./package.json ${EXT_PATH} + cp ./spirv.json ${EXT_PATH} -go build -o ${EXT_PATH}/langsvr ${ROOT_PATH}/src/langsvr.go + go build -o ${EXT_PATH}/langsvr ./src/langsvr.go +popd cd ${EXT_PATH} npm install diff --git a/third_party/spirv-tools/utils/vscode/spirv.json b/third_party/spirv-tools/utils/vscode/spirv.json index 7999b523ab..2e88296e0b 100644 --- a/third_party/spirv-tools/utils/vscode/spirv.json +++ b/third_party/spirv-tools/utils/vscode/spirv.json @@ -1,7 +1,7 @@ { "scopeName": "source.spirv", "name": "SPIR-V", - "comment": "Generated by gen-grammar.go --template=../../spirv.json.tmpl --out=../../spirv.json. Do not modify this file directly.", + "comment": "Generated by gen-grammar.go --template=./spirv.json.tmpl --out=./spirv.json. Do not modify this file directly.", "patterns": [ { "include": "#BitEnum_ImageOperands" }, { "include": "#BitEnum_FPFastMathMode" }, @@ -11,6 +11,7 @@ { "include": "#BitEnum_MemorySemantics" }, { "include": "#BitEnum_MemoryAccess" }, { "include": "#BitEnum_KernelProfilingInfo" }, + { "include": "#BitEnum_RayFlags" }, { "include": "#ValueEnum_SourceLanguage" }, { "include": "#ValueEnum_ExecutionModel" }, { "include": "#ValueEnum_AddressingModel" }, @@ -33,6 +34,9 @@ { "include": "#ValueEnum_GroupOperation" }, { "include": "#ValueEnum_KernelEnqueueFlags" }, { "include": "#ValueEnum_Capability" }, + { "include": "#ValueEnum_RayQueryIntersection" }, + { "include": "#ValueEnum_RayQueryCommittedIntersectionType" }, + { "include": "#ValueEnum_RayQueryCandidateIntersectionType" }, { "include": "#BitEnum_DebugInfoFlags" }, { "include": "#ValueEnum_DebugBaseTypeAttributeEncoding" }, { "include": "#ValueEnum_DebugCompositeType" }, @@ -80,12 +84,16 @@ "match": "\\b(None|CmdExecTime)\\b", "name": "keyword.spirv" }, + "BitEnum_RayFlags": { + "match": "\\b(NoneKHR|OpaqueKHR|NoOpaqueKHR|TerminateOnFirstHitKHR|SkipClosestHitShaderKHR|CullBackFacingTrianglesKHR|CullFrontFacingTrianglesKHR|CullOpaqueKHR|CullNoOpaqueKHR|SkipTrianglesKHR|SkipAABBsKHR)\\b", + "name": "keyword.spirv" + }, "ValueEnum_SourceLanguage": { "match": "\\b(Unknown|ESSL|GLSL|OpenCL_C|OpenCL_CPP|HLSL)\\b", "name": "keyword.spirv" }, "ValueEnum_ExecutionModel": { - "match": "\\b(Vertex|TessellationControl|TessellationEvaluation|Geometry|Fragment|GLCompute|Kernel|TaskNV|MeshNV|RayGenerationNV|IntersectionNV|AnyHitNV|ClosestHitNV|MissNV|CallableNV)\\b", + "match": "\\b(Vertex|TessellationControl|TessellationEvaluation|Geometry|Fragment|GLCompute|Kernel|TaskNV|MeshNV|RayGenerationNV|RayGenerationKHR|IntersectionNV|IntersectionKHR|AnyHitNV|AnyHitKHR|ClosestHitNV|ClosestHitKHR|MissNV|MissKHR|CallableNV|CallableKHR)\\b", "name": "keyword.spirv" }, "ValueEnum_AddressingModel": { @@ -101,7 +109,7 @@ "name": "keyword.spirv" }, "ValueEnum_StorageClass": { - "match": "\\b(UniformConstant|Input|Uniform|Output|Workgroup|CrossWorkgroup|Private|Function|Generic|PushConstant|AtomicCounter|Image|StorageBuffer|CallableDataNV|IncomingCallableDataNV|RayPayloadNV|HitAttributeNV|IncomingRayPayloadNV|ShaderRecordBufferNV|PhysicalStorageBuffer|PhysicalStorageBufferEXT)\\b", + "match": "\\b(UniformConstant|Input|Uniform|Output|Workgroup|CrossWorkgroup|Private|Function|Generic|PushConstant|AtomicCounter|Image|StorageBuffer|CallableDataNV|CallableDataKHR|IncomingCallableDataNV|IncomingCallableDataKHR|RayPayloadNV|RayPayloadKHR|HitAttributeNV|HitAttributeKHR|IncomingRayPayloadNV|IncomingRayPayloadKHR|ShaderRecordBufferNV|ShaderRecordBufferKHR|PhysicalStorageBuffer|PhysicalStorageBufferEXT)\\b", "name": "keyword.spirv" }, "ValueEnum_Dim": { @@ -149,11 +157,11 @@ "name": "keyword.spirv" }, "ValueEnum_BuiltIn": { - "match": "\\b(Position|PointSize|ClipDistance|CullDistance|VertexId|InstanceId|PrimitiveId|InvocationId|Layer|ViewportIndex|TessLevelOuter|TessLevelInner|TessCoord|PatchVertices|FragCoord|PointCoord|FrontFacing|SampleId|SamplePosition|SampleMask|FragDepth|HelperInvocation|NumWorkgroups|WorkgroupSize|WorkgroupId|LocalInvocationId|GlobalInvocationId|LocalInvocationIndex|WorkDim|GlobalSize|EnqueuedWorkgroupSize|GlobalOffset|GlobalLinearId|SubgroupSize|SubgroupMaxSize|NumSubgroups|NumEnqueuedSubgroups|SubgroupId|SubgroupLocalInvocationId|VertexIndex|InstanceIndex|SubgroupEqMask|SubgroupGeMask|SubgroupGtMask|SubgroupLeMask|SubgroupLtMask|SubgroupEqMaskKHR|SubgroupGeMaskKHR|SubgroupGtMaskKHR|SubgroupLeMaskKHR|SubgroupLtMaskKHR|BaseVertex|BaseInstance|DrawIndex|DeviceIndex|ViewIndex|BaryCoordNoPerspAMD|BaryCoordNoPerspCentroidAMD|BaryCoordNoPerspSampleAMD|BaryCoordSmoothAMD|BaryCoordSmoothCentroidAMD|BaryCoordSmoothSampleAMD|BaryCoordPullModelAMD|FragStencilRefEXT|ViewportMaskNV|SecondaryPositionNV|SecondaryViewportMaskNV|PositionPerViewNV|ViewportMaskPerViewNV|FullyCoveredEXT|TaskCountNV|PrimitiveCountNV|PrimitiveIndicesNV|ClipDistancePerViewNV|CullDistancePerViewNV|LayerPerViewNV|MeshViewCountNV|MeshViewIndicesNV|BaryCoordNV|BaryCoordNoPerspNV|FragSizeEXT|FragmentSizeNV|FragInvocationCountEXT|InvocationsPerPixelNV|LaunchIdNV|LaunchSizeNV|WorldRayOriginNV|WorldRayDirectionNV|ObjectRayOriginNV|ObjectRayDirectionNV|RayTminNV|RayTmaxNV|InstanceCustomIndexNV|ObjectToWorldNV|WorldToObjectNV|HitTNV|HitKindNV|IncomingRayFlagsNV|WarpsPerSMNV|SMCountNV|WarpIDNV|SMIDNV)\\b", + "match": "\\b(Position|PointSize|ClipDistance|CullDistance|VertexId|InstanceId|PrimitiveId|InvocationId|Layer|ViewportIndex|TessLevelOuter|TessLevelInner|TessCoord|PatchVertices|FragCoord|PointCoord|FrontFacing|SampleId|SamplePosition|SampleMask|FragDepth|HelperInvocation|NumWorkgroups|WorkgroupSize|WorkgroupId|LocalInvocationId|GlobalInvocationId|LocalInvocationIndex|WorkDim|GlobalSize|EnqueuedWorkgroupSize|GlobalOffset|GlobalLinearId|SubgroupSize|SubgroupMaxSize|NumSubgroups|NumEnqueuedSubgroups|SubgroupId|SubgroupLocalInvocationId|VertexIndex|InstanceIndex|SubgroupEqMask|SubgroupGeMask|SubgroupGtMask|SubgroupLeMask|SubgroupLtMask|SubgroupEqMaskKHR|SubgroupGeMaskKHR|SubgroupGtMaskKHR|SubgroupLeMaskKHR|SubgroupLtMaskKHR|BaseVertex|BaseInstance|DrawIndex|DeviceIndex|ViewIndex|BaryCoordNoPerspAMD|BaryCoordNoPerspCentroidAMD|BaryCoordNoPerspSampleAMD|BaryCoordSmoothAMD|BaryCoordSmoothCentroidAMD|BaryCoordSmoothSampleAMD|BaryCoordPullModelAMD|FragStencilRefEXT|ViewportMaskNV|SecondaryPositionNV|SecondaryViewportMaskNV|PositionPerViewNV|ViewportMaskPerViewNV|FullyCoveredEXT|TaskCountNV|PrimitiveCountNV|PrimitiveIndicesNV|ClipDistancePerViewNV|CullDistancePerViewNV|LayerPerViewNV|MeshViewCountNV|MeshViewIndicesNV|BaryCoordNV|BaryCoordNoPerspNV|FragSizeEXT|FragmentSizeNV|FragInvocationCountEXT|InvocationsPerPixelNV|LaunchIdNV|LaunchIdKHR|LaunchSizeNV|LaunchSizeKHR|WorldRayOriginNV|WorldRayOriginKHR|WorldRayDirectionNV|WorldRayDirectionKHR|ObjectRayOriginNV|ObjectRayOriginKHR|ObjectRayDirectionNV|ObjectRayDirectionKHR|RayTminNV|RayTminKHR|RayTmaxNV|RayTmaxKHR|InstanceCustomIndexNV|InstanceCustomIndexKHR|ObjectToWorldNV|ObjectToWorldKHR|WorldToObjectNV|WorldToObjectKHR|HitTNV|HitTKHR|HitKindNV|HitKindKHR|IncomingRayFlagsNV|IncomingRayFlagsKHR|RayGeometryIndexKHR|WarpsPerSMNV|SMCountNV|WarpIDNV|SMIDNV)\\b", "name": "keyword.spirv" }, "ValueEnum_Scope": { - "match": "\\b(CrossDevice|Device|Workgroup|Subgroup|Invocation|QueueFamily|QueueFamilyKHR)\\b", + "match": "\\b(CrossDevice|Device|Workgroup|Subgroup|Invocation|QueueFamily|QueueFamilyKHR|ShaderCallKHR)\\b", "name": "keyword.spirv" }, "ValueEnum_GroupOperation": { @@ -165,7 +173,19 @@ "name": "keyword.spirv" }, "ValueEnum_Capability": { - "match": "\\b(Matrix|Shader|Geometry|Tessellation|Addresses|Linkage|Kernel|Vector16|Float16Buffer|Float16|Float64|Int64|Int64Atomics|ImageBasic|ImageReadWrite|ImageMipmap|Pipes|Groups|DeviceEnqueue|LiteralSampler|AtomicStorage|Int16|TessellationPointSize|GeometryPointSize|ImageGatherExtended|StorageImageMultisample|UniformBufferArrayDynamicIndexing|SampledImageArrayDynamicIndexing|StorageBufferArrayDynamicIndexing|StorageImageArrayDynamicIndexing|ClipDistance|CullDistance|ImageCubeArray|SampleRateShading|ImageRect|SampledRect|GenericPointer|Int8|InputAttachment|SparseResidency|MinLod|Sampled1D|Image1D|SampledCubeArray|SampledBuffer|ImageBuffer|ImageMSArray|StorageImageExtendedFormats|ImageQuery|DerivativeControl|InterpolationFunction|TransformFeedback|GeometryStreams|StorageImageReadWithoutFormat|StorageImageWriteWithoutFormat|MultiViewport|SubgroupDispatch|NamedBarrier|PipeStorage|GroupNonUniform|GroupNonUniformVote|GroupNonUniformArithmetic|GroupNonUniformBallot|GroupNonUniformShuffle|GroupNonUniformShuffleRelative|GroupNonUniformClustered|GroupNonUniformQuad|ShaderLayer|ShaderViewportIndex|SubgroupBallotKHR|DrawParameters|SubgroupVoteKHR|StorageBuffer16BitAccess|StorageUniformBufferBlock16|UniformAndStorageBuffer16BitAccess|StorageUniform16|StoragePushConstant16|StorageInputOutput16|DeviceGroup|MultiView|VariablePointersStorageBuffer|VariablePointers|AtomicStorageOps|SampleMaskPostDepthCoverage|StorageBuffer8BitAccess|UniformAndStorageBuffer8BitAccess|StoragePushConstant8|DenormPreserve|DenormFlushToZero|SignedZeroInfNanPreserve|RoundingModeRTE|RoundingModeRTZ|Float16ImageAMD|ImageGatherBiasLodAMD|FragmentMaskAMD|StencilExportEXT|ImageReadWriteLodAMD|ShaderClockKHR|SampleMaskOverrideCoverageNV|GeometryShaderPassthroughNV|ShaderViewportIndexLayerEXT|ShaderViewportIndexLayerNV|ShaderViewportMaskNV|ShaderStereoViewNV|PerViewAttributesNV|FragmentFullyCoveredEXT|MeshShadingNV|ImageFootprintNV|FragmentBarycentricNV|ComputeDerivativeGroupQuadsNV|FragmentDensityEXT|ShadingRateNV|GroupNonUniformPartitionedNV|ShaderNonUniform|ShaderNonUniformEXT|RuntimeDescriptorArray|RuntimeDescriptorArrayEXT|InputAttachmentArrayDynamicIndexing|InputAttachmentArrayDynamicIndexingEXT|UniformTexelBufferArrayDynamicIndexing|UniformTexelBufferArrayDynamicIndexingEXT|StorageTexelBufferArrayDynamicIndexing|StorageTexelBufferArrayDynamicIndexingEXT|UniformBufferArrayNonUniformIndexing|UniformBufferArrayNonUniformIndexingEXT|SampledImageArrayNonUniformIndexing|SampledImageArrayNonUniformIndexingEXT|StorageBufferArrayNonUniformIndexing|StorageBufferArrayNonUniformIndexingEXT|StorageImageArrayNonUniformIndexing|StorageImageArrayNonUniformIndexingEXT|InputAttachmentArrayNonUniformIndexing|InputAttachmentArrayNonUniformIndexingEXT|UniformTexelBufferArrayNonUniformIndexing|UniformTexelBufferArrayNonUniformIndexingEXT|StorageTexelBufferArrayNonUniformIndexing|StorageTexelBufferArrayNonUniformIndexingEXT|RayTracingNV|VulkanMemoryModel|VulkanMemoryModelKHR|VulkanMemoryModelDeviceScope|VulkanMemoryModelDeviceScopeKHR|PhysicalStorageBufferAddresses|PhysicalStorageBufferAddressesEXT|ComputeDerivativeGroupLinearNV|CooperativeMatrixNV|FragmentShaderSampleInterlockEXT|FragmentShaderShadingRateInterlockEXT|ShaderSMBuiltinsNV|FragmentShaderPixelInterlockEXT|DemoteToHelperInvocationEXT|SubgroupShuffleINTEL|SubgroupBufferBlockIOINTEL|SubgroupImageBlockIOINTEL|SubgroupImageMediaBlockIOINTEL|IntegerFunctions2INTEL|SubgroupAvcMotionEstimationINTEL|SubgroupAvcMotionEstimationIntraINTEL|SubgroupAvcMotionEstimationChromaINTEL)\\b", + "match": "\\b(Matrix|Shader|Geometry|Tessellation|Addresses|Linkage|Kernel|Vector16|Float16Buffer|Float16|Float64|Int64|Int64Atomics|ImageBasic|ImageReadWrite|ImageMipmap|Pipes|Groups|DeviceEnqueue|LiteralSampler|AtomicStorage|Int16|TessellationPointSize|GeometryPointSize|ImageGatherExtended|StorageImageMultisample|UniformBufferArrayDynamicIndexing|SampledImageArrayDynamicIndexing|StorageBufferArrayDynamicIndexing|StorageImageArrayDynamicIndexing|ClipDistance|CullDistance|ImageCubeArray|SampleRateShading|ImageRect|SampledRect|GenericPointer|Int8|InputAttachment|SparseResidency|MinLod|Sampled1D|Image1D|SampledCubeArray|SampledBuffer|ImageBuffer|ImageMSArray|StorageImageExtendedFormats|ImageQuery|DerivativeControl|InterpolationFunction|TransformFeedback|GeometryStreams|StorageImageReadWithoutFormat|StorageImageWriteWithoutFormat|MultiViewport|SubgroupDispatch|NamedBarrier|PipeStorage|GroupNonUniform|GroupNonUniformVote|GroupNonUniformArithmetic|GroupNonUniformBallot|GroupNonUniformShuffle|GroupNonUniformShuffleRelative|GroupNonUniformClustered|GroupNonUniformQuad|ShaderLayer|ShaderViewportIndex|SubgroupBallotKHR|DrawParameters|SubgroupVoteKHR|StorageBuffer16BitAccess|StorageUniformBufferBlock16|UniformAndStorageBuffer16BitAccess|StorageUniform16|StoragePushConstant16|StorageInputOutput16|DeviceGroup|MultiView|VariablePointersStorageBuffer|VariablePointers|AtomicStorageOps|SampleMaskPostDepthCoverage|StorageBuffer8BitAccess|UniformAndStorageBuffer8BitAccess|StoragePushConstant8|DenormPreserve|DenormFlushToZero|SignedZeroInfNanPreserve|RoundingModeRTE|RoundingModeRTZ|RayQueryProvisionalKHR|RayTraversalPrimitiveCullingProvisionalKHR|Float16ImageAMD|ImageGatherBiasLodAMD|FragmentMaskAMD|StencilExportEXT|ImageReadWriteLodAMD|ShaderClockKHR|SampleMaskOverrideCoverageNV|GeometryShaderPassthroughNV|ShaderViewportIndexLayerEXT|ShaderViewportIndexLayerNV|ShaderViewportMaskNV|ShaderStereoViewNV|PerViewAttributesNV|FragmentFullyCoveredEXT|MeshShadingNV|ImageFootprintNV|FragmentBarycentricNV|ComputeDerivativeGroupQuadsNV|FragmentDensityEXT|ShadingRateNV|GroupNonUniformPartitionedNV|ShaderNonUniform|ShaderNonUniformEXT|RuntimeDescriptorArray|RuntimeDescriptorArrayEXT|InputAttachmentArrayDynamicIndexing|InputAttachmentArrayDynamicIndexingEXT|UniformTexelBufferArrayDynamicIndexing|UniformTexelBufferArrayDynamicIndexingEXT|StorageTexelBufferArrayDynamicIndexing|StorageTexelBufferArrayDynamicIndexingEXT|UniformBufferArrayNonUniformIndexing|UniformBufferArrayNonUniformIndexingEXT|SampledImageArrayNonUniformIndexing|SampledImageArrayNonUniformIndexingEXT|StorageBufferArrayNonUniformIndexing|StorageBufferArrayNonUniformIndexingEXT|StorageImageArrayNonUniformIndexing|StorageImageArrayNonUniformIndexingEXT|InputAttachmentArrayNonUniformIndexing|InputAttachmentArrayNonUniformIndexingEXT|UniformTexelBufferArrayNonUniformIndexing|UniformTexelBufferArrayNonUniformIndexingEXT|StorageTexelBufferArrayNonUniformIndexing|StorageTexelBufferArrayNonUniformIndexingEXT|RayTracingNV|VulkanMemoryModel|VulkanMemoryModelKHR|VulkanMemoryModelDeviceScope|VulkanMemoryModelDeviceScopeKHR|PhysicalStorageBufferAddresses|PhysicalStorageBufferAddressesEXT|ComputeDerivativeGroupLinearNV|RayTracingProvisionalKHR|CooperativeMatrixNV|FragmentShaderSampleInterlockEXT|FragmentShaderShadingRateInterlockEXT|ShaderSMBuiltinsNV|FragmentShaderPixelInterlockEXT|DemoteToHelperInvocationEXT|SubgroupShuffleINTEL|SubgroupBufferBlockIOINTEL|SubgroupImageBlockIOINTEL|SubgroupImageMediaBlockIOINTEL|IntegerFunctions2INTEL|SubgroupAvcMotionEstimationINTEL|SubgroupAvcMotionEstimationIntraINTEL|SubgroupAvcMotionEstimationChromaINTEL)\\b", + "name": "keyword.spirv" + }, + "ValueEnum_RayQueryIntersection": { + "match": "\\b(RayQueryCandidateIntersectionKHR|RayQueryCommittedIntersectionKHR)\\b", + "name": "keyword.spirv" + }, + "ValueEnum_RayQueryCommittedIntersectionType": { + "match": "\\b(RayQueryCommittedIntersectionNoneKHR|RayQueryCommittedIntersectionTriangleKHR|RayQueryCommittedIntersectionGeneratedKHR)\\b", + "name": "keyword.spirv" + }, + "ValueEnum_RayQueryCandidateIntersectionType": { + "match": "\\b(RayQueryCandidateIntersectionTriangleKHR|RayQueryCandidateIntersectionAABBKHR)\\b", "name": "keyword.spirv" }, "BitEnum_DebugInfoFlags": { diff --git a/third_party/spirv-tools/utils/vscode/src/langsvr.go b/third_party/spirv-tools/utils/vscode/src/langsvr.go index d1b80dcab5..b76e35f78d 100644 --- a/third_party/spirv-tools/utils/vscode/src/langsvr.go +++ b/third_party/spirv-tools/utils/vscode/src/langsvr.go @@ -28,11 +28,15 @@ import ( "sync" "unicode/utf8" - "./parser" - "./schema" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/parser" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/schema" - "./lsp/jsonrpc2" - lsp "./lsp/protocol" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/jsonrpc2" + lsp "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/protocol" +) + +const ( + enableDebugLogging = false ) // rSpy is a reader 'spy' that wraps an io.Reader, and logs all data that passes @@ -63,12 +67,13 @@ func (s wSpy) Write(p []byte) (n int, err error) { // main entry point. func main() { - // create a log file in the executable's directory. - if logfile, err := os.Create(path.Join(path.Dir(os.Args[0]), "log.txt")); err == nil { - defer logfile.Close() - log.SetOutput(logfile) - } else { - log.SetOutput(ioutil.Discard) + log.SetOutput(ioutil.Discard) + if enableDebugLogging { + // create a log file in the executable's directory. + if logfile, err := os.Create(path.Join(path.Dir(os.Args[0]), "log.txt")); err == nil { + defer logfile.Close() + log.SetOutput(logfile) + } } log.Println("language server started") @@ -407,13 +412,15 @@ func (s *server) Formatting(ctx context.Context, p *lsp.DocumentFormattingParams } } - // Every good file ends with a new line. - sb.WriteString("\n") + formatted := sb.String() + + // Every good file ends with a single new line. + formatted = strings.TrimRight(formatted, "\n") + "\n" return []lsp.TextEdit{ - lsp.TextEdit{ + { Range: rangeToLSP(f.fullRange), - NewText: sb.String(), + NewText: formatted, }, }, nil } diff --git a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/log.go b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/log.go index f245881e18..2fd7bbbdd7 100644 --- a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/log.go +++ b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/log.go @@ -23,7 +23,7 @@ import ( "sync" "time" - "../jsonrpc2" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/jsonrpc2" ) type loggingStream struct { diff --git a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/protocol.go b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/protocol.go index e396c8325e..886b0aaad8 100644 --- a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/protocol.go +++ b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/protocol.go @@ -19,7 +19,7 @@ import ( "encoding/json" "log" - "../jsonrpc2" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/jsonrpc2" ) const ( diff --git a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/span.go b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/span.go index 33cc2a651b..799c228824 100644 --- a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/span.go +++ b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/span.go @@ -19,7 +19,8 @@ package protocol import ( "fmt" - "../span" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/span" + errors "golang.org/x/xerrors" ) diff --git a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsclient.go b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsclient.go index 2f9beef46a..f68d63d0c0 100644 --- a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsclient.go +++ b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsclient.go @@ -19,7 +19,7 @@ import ( "encoding/json" "log" - "../jsonrpc2" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/jsonrpc2" ) type Client interface { diff --git a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsserver.go b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsserver.go index d76050121f..37e8c6a75e 100644 --- a/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsserver.go +++ b/third_party/spirv-tools/utils/vscode/src/lsp/protocol/tsserver.go @@ -19,7 +19,7 @@ import ( "encoding/json" "log" - "../jsonrpc2" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/lsp/jsonrpc2" ) type Server interface { diff --git a/third_party/spirv-tools/utils/vscode/src/parser/parser.go b/third_party/spirv-tools/utils/vscode/src/parser/parser.go index 260a616ca2..cc6f33324b 100644 --- a/third_party/spirv-tools/utils/vscode/src/parser/parser.go +++ b/third_party/spirv-tools/utils/vscode/src/parser/parser.go @@ -23,7 +23,7 @@ import ( "unicode" "unicode/utf8" - "../schema" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/schema" ) // Type is an enumerator of token types. diff --git a/third_party/spirv-tools/utils/vscode/src/schema/schema.go b/third_party/spirv-tools/utils/vscode/src/schema/schema.go index 0d57cb121d..ed02de4e3a 100755 --- a/third_party/spirv-tools/utils/vscode/src/schema/schema.go +++ b/third_party/spirv-tools/utils/vscode/src/schema/schema.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Generated by gen-grammar.go --template=../schema/schema.go.tmpl --out=../schema/schema.go +// Generated by gen-grammar.go --template=./src/schema/schema.go.tmpl --out=./src/schema/schema.go // Do not modify this file directly. package schema diff --git a/third_party/spirv-tools/utils/vscode/src/tools/gen-grammar.go b/third_party/spirv-tools/utils/vscode/src/tools/gen-grammar.go index 200f695949..a1289ef9c9 100644 --- a/third_party/spirv-tools/utils/vscode/src/tools/gen-grammar.go +++ b/third_party/spirv-tools/utils/vscode/src/tools/gen-grammar.go @@ -31,7 +31,7 @@ import ( "github.com/pkg/errors" - "../grammar" + "github.com/KhronosGroup/SPIRV-Tools/utils/vscode/src/grammar" ) type grammarDefinition struct { @@ -54,7 +54,7 @@ var ( url: "https://raw.githubusercontent.com/KhronosGroup/SPIRV-Headers/master/include/spirv/unified1/extinst.opencl.std.100.grammar.json", }, { name: "OpenCL.DebugInfo.100", - url: "https://raw.githubusercontent.com/KhronosGroup/SPIRV-Tools/master/source/extinst.opencl.debuginfo.100.grammar.json", + url: "https://raw.githubusercontent.com/KhronosGroup/SPIRV-Headers/master/include/spirv/unified1/extinst.opencl.debuginfo.100.grammar.json", }, } @@ -106,7 +106,7 @@ func run() error { for _, ext := range extensionGrammars { root, err := parseGrammar(ext) if err != nil { - return errors.Wrap(err, "Failed to parse extension grammar file") + return errors.Wrap(err, "Failed to parse extension grammar file: "+ext.name) } args.Extensions = append(args.Extensions, extension{Root: root, Name: ext.name}) args.All.Instructions = append(args.All.Instructions, root.Instructions...)