validate_instruction.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Performs validation on instructions that appear inside of a SPIR-V block.
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <iomanip>
  18. #include <sstream>
  19. #include <string>
  20. #include <vector>
  21. #include "source/binary.h"
  22. #include "source/diagnostic.h"
  23. #include "source/enum_set.h"
  24. #include "source/enum_string_mapping.h"
  25. #include "source/extensions.h"
  26. #include "source/opcode.h"
  27. #include "source/operand.h"
  28. #include "source/spirv_constant.h"
  29. #include "source/spirv_definition.h"
  30. #include "source/spirv_target_env.h"
  31. #include "source/spirv_validator_options.h"
  32. #include "source/util/string_utils.h"
  33. #include "source/val/function.h"
  34. #include "source/val/validate.h"
  35. #include "source/val/validation_state.h"
  36. namespace spvtools {
  37. namespace val {
  38. namespace {
  39. std::string ToString(const CapabilitySet& capabilities,
  40. const AssemblyGrammar& grammar) {
  41. std::stringstream ss;
  42. capabilities.ForEach([&grammar, &ss](SpvCapability cap) {
  43. spv_operand_desc desc;
  44. if (SPV_SUCCESS ==
  45. grammar.lookupOperand(SPV_OPERAND_TYPE_CAPABILITY, cap, &desc))
  46. ss << desc->name << " ";
  47. else
  48. ss << cap << " ";
  49. });
  50. return ss.str();
  51. }
  52. bool IsValidWebGPUStorageClass(SpvStorageClass storage_class) {
  53. return storage_class == SpvStorageClassUniformConstant ||
  54. storage_class == SpvStorageClassUniform ||
  55. storage_class == SpvStorageClassStorageBuffer ||
  56. storage_class == SpvStorageClassInput ||
  57. storage_class == SpvStorageClassOutput ||
  58. storage_class == SpvStorageClassImage ||
  59. storage_class == SpvStorageClassWorkgroup ||
  60. storage_class == SpvStorageClassPrivate ||
  61. storage_class == SpvStorageClassFunction;
  62. }
  63. // Returns capabilities that enable an opcode. An empty result is interpreted
  64. // as no prohibition of use of the opcode. If the result is non-empty, then
  65. // the opcode may only be used if at least one of the capabilities is specified
  66. // by the module.
  67. CapabilitySet EnablingCapabilitiesForOp(const ValidationState_t& state,
  68. SpvOp opcode) {
  69. // Exceptions for SPV_AMD_shader_ballot
  70. switch (opcode) {
  71. // Normally these would require Group capability
  72. case SpvOpGroupIAddNonUniformAMD:
  73. case SpvOpGroupFAddNonUniformAMD:
  74. case SpvOpGroupFMinNonUniformAMD:
  75. case SpvOpGroupUMinNonUniformAMD:
  76. case SpvOpGroupSMinNonUniformAMD:
  77. case SpvOpGroupFMaxNonUniformAMD:
  78. case SpvOpGroupUMaxNonUniformAMD:
  79. case SpvOpGroupSMaxNonUniformAMD:
  80. if (state.HasExtension(kSPV_AMD_shader_ballot)) return CapabilitySet();
  81. break;
  82. default:
  83. break;
  84. }
  85. // Look it up in the grammar
  86. spv_opcode_desc opcode_desc = {};
  87. if (SPV_SUCCESS == state.grammar().lookupOpcode(opcode, &opcode_desc)) {
  88. return state.grammar().filterCapsAgainstTargetEnv(
  89. opcode_desc->capabilities, opcode_desc->numCapabilities);
  90. }
  91. return CapabilitySet();
  92. }
  93. // Returns SPV_SUCCESS if, for the given operand, the target environment
  94. // satsifies minimum version requirements, or if the module declares an
  95. // enabling extension for the operand. Otherwise emit a diagnostic and
  96. // return an error code.
  97. spv_result_t OperandVersionExtensionCheck(
  98. ValidationState_t& _, const Instruction* inst, size_t which_operand,
  99. const spv_operand_desc_t& operand_desc, uint32_t word) {
  100. const uint32_t module_version = _.version();
  101. const uint32_t operand_min_version = operand_desc.minVersion;
  102. const uint32_t operand_last_version = operand_desc.lastVersion;
  103. const bool reserved = operand_min_version == 0xffffffffu;
  104. const bool version_satisfied = !reserved &&
  105. (operand_min_version <= module_version) &&
  106. (module_version <= operand_last_version);
  107. if (version_satisfied) {
  108. return SPV_SUCCESS;
  109. }
  110. if (operand_last_version < module_version) {
  111. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  112. << spvtools::utils::CardinalToOrdinal(which_operand)
  113. << " operand of " << spvOpcodeString(inst->opcode()) << ": operand "
  114. << operand_desc.name << "(" << word << ") requires SPIR-V version "
  115. << SPV_SPIRV_VERSION_MAJOR_PART(operand_last_version) << "."
  116. << SPV_SPIRV_VERSION_MINOR_PART(operand_last_version)
  117. << " or earlier";
  118. }
  119. if (!reserved && operand_desc.numExtensions == 0) {
  120. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  121. << spvtools::utils::CardinalToOrdinal(which_operand)
  122. << " operand of " << spvOpcodeString(inst->opcode()) << ": operand "
  123. << operand_desc.name << "(" << word << ") requires SPIR-V version "
  124. << SPV_SPIRV_VERSION_MAJOR_PART(operand_min_version) << "."
  125. << SPV_SPIRV_VERSION_MINOR_PART(operand_min_version) << " or later";
  126. } else {
  127. ExtensionSet required_extensions(operand_desc.numExtensions,
  128. operand_desc.extensions);
  129. if (!_.HasAnyOfExtensions(required_extensions)) {
  130. return _.diag(SPV_ERROR_MISSING_EXTENSION, inst)
  131. << spvtools::utils::CardinalToOrdinal(which_operand)
  132. << " operand of " << spvOpcodeString(inst->opcode())
  133. << ": operand " << operand_desc.name << "(" << word
  134. << ") requires one of these extensions: "
  135. << ExtensionSetToString(required_extensions);
  136. }
  137. }
  138. return SPV_SUCCESS;
  139. }
  140. // Returns SPV_SUCCESS if the given operand is enabled by capabilities declared
  141. // in the module. Otherwise issues an error message and returns
  142. // SPV_ERROR_INVALID_CAPABILITY.
  143. spv_result_t CheckRequiredCapabilities(ValidationState_t& state,
  144. const Instruction* inst,
  145. size_t which_operand,
  146. const spv_parsed_operand_t& operand,
  147. uint32_t word) {
  148. // Mere mention of PointSize, ClipDistance, or CullDistance in a Builtin
  149. // decoration does not require the associated capability. The use of such
  150. // a variable value should trigger the capability requirement, but that's
  151. // not implemented yet. This rule is independent of target environment.
  152. // See https://github.com/KhronosGroup/SPIRV-Tools/issues/365
  153. if (operand.type == SPV_OPERAND_TYPE_BUILT_IN) {
  154. switch (word) {
  155. case SpvBuiltInPointSize:
  156. case SpvBuiltInClipDistance:
  157. case SpvBuiltInCullDistance:
  158. return SPV_SUCCESS;
  159. default:
  160. break;
  161. }
  162. } else if (operand.type == SPV_OPERAND_TYPE_FP_ROUNDING_MODE) {
  163. // Allow all FP rounding modes if requested
  164. if (state.features().free_fp_rounding_mode) {
  165. return SPV_SUCCESS;
  166. }
  167. } else if (operand.type == SPV_OPERAND_TYPE_GROUP_OPERATION &&
  168. state.features().group_ops_reduce_and_scans &&
  169. (word <= uint32_t(SpvGroupOperationExclusiveScan))) {
  170. // Allow certain group operations if requested.
  171. return SPV_SUCCESS;
  172. }
  173. CapabilitySet enabling_capabilities;
  174. spv_operand_desc operand_desc = nullptr;
  175. const auto lookup_result =
  176. state.grammar().lookupOperand(operand.type, word, &operand_desc);
  177. if (lookup_result == SPV_SUCCESS) {
  178. // Allow FPRoundingMode decoration if requested.
  179. if (operand.type == SPV_OPERAND_TYPE_DECORATION &&
  180. operand_desc->value == SpvDecorationFPRoundingMode) {
  181. if (state.features().free_fp_rounding_mode) return SPV_SUCCESS;
  182. // Vulkan API requires more capabilities on rounding mode.
  183. if (spvIsVulkanEnv(state.context()->target_env)) {
  184. enabling_capabilities.Add(SpvCapabilityStorageUniformBufferBlock16);
  185. enabling_capabilities.Add(SpvCapabilityStorageUniform16);
  186. enabling_capabilities.Add(SpvCapabilityStoragePushConstant16);
  187. enabling_capabilities.Add(SpvCapabilityStorageInputOutput16);
  188. }
  189. } else {
  190. enabling_capabilities = state.grammar().filterCapsAgainstTargetEnv(
  191. operand_desc->capabilities, operand_desc->numCapabilities);
  192. }
  193. if (!state.HasAnyOfCapabilities(enabling_capabilities)) {
  194. return state.diag(SPV_ERROR_INVALID_CAPABILITY, inst)
  195. << "Operand " << which_operand << " of "
  196. << spvOpcodeString(inst->opcode())
  197. << " requires one of these capabilities: "
  198. << ToString(enabling_capabilities, state.grammar());
  199. }
  200. return OperandVersionExtensionCheck(state, inst, which_operand,
  201. *operand_desc, word);
  202. }
  203. return SPV_SUCCESS;
  204. }
  205. // Returns SPV_ERROR_INVALID_BINARY and emits a diagnostic if the instruction
  206. // is explicitly reserved in the SPIR-V core spec. Otherwise return
  207. // SPV_SUCCESS.
  208. spv_result_t ReservedCheck(ValidationState_t& _, const Instruction* inst) {
  209. const SpvOp opcode = inst->opcode();
  210. switch (opcode) {
  211. // These instructions are enabled by a capability, but should never
  212. // be used anyway.
  213. case SpvOpImageSparseSampleProjImplicitLod:
  214. case SpvOpImageSparseSampleProjExplicitLod:
  215. case SpvOpImageSparseSampleProjDrefImplicitLod:
  216. case SpvOpImageSparseSampleProjDrefExplicitLod: {
  217. spv_opcode_desc inst_desc;
  218. _.grammar().lookupOpcode(opcode, &inst_desc);
  219. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  220. << "Invalid Opcode name 'Op" << inst_desc->name << "'";
  221. }
  222. default:
  223. break;
  224. }
  225. return SPV_SUCCESS;
  226. }
  227. // Returns SPV_ERROR_INVALID_BINARY and emits a diagnostic if the instruction
  228. // is invalid because of an execution environment constraint.
  229. spv_result_t EnvironmentCheck(ValidationState_t& _, const Instruction* inst) {
  230. const SpvOp opcode = inst->opcode();
  231. switch (opcode) {
  232. case SpvOpUndef:
  233. if (_.features().bans_op_undef) {
  234. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  235. << "OpUndef is disallowed";
  236. }
  237. break;
  238. default:
  239. break;
  240. }
  241. return SPV_SUCCESS;
  242. }
  243. // Returns SPV_ERROR_INVALID_CAPABILITY and emits a diagnostic if the
  244. // instruction is invalid because the required capability isn't declared
  245. // in the module.
  246. spv_result_t CapabilityCheck(ValidationState_t& _, const Instruction* inst) {
  247. const SpvOp opcode = inst->opcode();
  248. CapabilitySet opcode_caps = EnablingCapabilitiesForOp(_, opcode);
  249. if (!_.HasAnyOfCapabilities(opcode_caps)) {
  250. return _.diag(SPV_ERROR_INVALID_CAPABILITY, inst)
  251. << "Opcode " << spvOpcodeString(opcode)
  252. << " requires one of these capabilities: "
  253. << ToString(opcode_caps, _.grammar());
  254. }
  255. for (size_t i = 0; i < inst->operands().size(); ++i) {
  256. const auto& operand = inst->operand(i);
  257. const auto word = inst->word(operand.offset);
  258. if (spvOperandIsConcreteMask(operand.type)) {
  259. // Check for required capabilities for each bit position of the mask.
  260. for (uint32_t mask_bit = 0x80000000; mask_bit; mask_bit >>= 1) {
  261. if (word & mask_bit) {
  262. spv_result_t status =
  263. CheckRequiredCapabilities(_, inst, i + 1, operand, mask_bit);
  264. if (status != SPV_SUCCESS) return status;
  265. }
  266. }
  267. } else if (spvIsIdType(operand.type)) {
  268. // TODO(dneto): Check the value referenced by this Id, if we can compute
  269. // it. For now, just punt, to fix issue 248:
  270. // https://github.com/KhronosGroup/SPIRV-Tools/issues/248
  271. } else {
  272. // Check the operand word as a whole.
  273. spv_result_t status =
  274. CheckRequiredCapabilities(_, inst, i + 1, operand, word);
  275. if (status != SPV_SUCCESS) return status;
  276. }
  277. }
  278. return SPV_SUCCESS;
  279. }
  280. // Checks that the instruction can be used in this target environment's base
  281. // version. Assumes that CapabilityCheck has checked direct capability
  282. // dependencies for the opcode.
  283. spv_result_t VersionCheck(ValidationState_t& _, const Instruction* inst) {
  284. const auto opcode = inst->opcode();
  285. spv_opcode_desc inst_desc;
  286. const spv_result_t r = _.grammar().lookupOpcode(opcode, &inst_desc);
  287. assert(r == SPV_SUCCESS);
  288. (void)r;
  289. const auto min_version = inst_desc->minVersion;
  290. const auto last_version = inst_desc->lastVersion;
  291. const auto module_version = _.version();
  292. if (last_version < module_version) {
  293. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  294. << spvOpcodeString(opcode) << " requires SPIR-V version "
  295. << SPV_SPIRV_VERSION_MAJOR_PART(last_version) << "."
  296. << SPV_SPIRV_VERSION_MINOR_PART(last_version) << " or earlier";
  297. }
  298. if (inst_desc->numCapabilities > 0u) {
  299. // We already checked that the direct capability dependency has been
  300. // satisfied. We don't need to check any further.
  301. return SPV_SUCCESS;
  302. }
  303. ExtensionSet exts(inst_desc->numExtensions, inst_desc->extensions);
  304. if (exts.IsEmpty()) {
  305. // If no extensions can enable this instruction, then emit error
  306. // messages only concerning core SPIR-V versions if errors happen.
  307. if (min_version == ~0u) {
  308. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  309. << spvOpcodeString(opcode) << " is reserved for future use.";
  310. }
  311. if (module_version < min_version) {
  312. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  313. << spvOpcodeString(opcode) << " requires "
  314. << spvTargetEnvDescription(
  315. static_cast<spv_target_env>(min_version))
  316. << " at minimum.";
  317. }
  318. } else if (!_.HasAnyOfExtensions(exts)) {
  319. // Otherwise, we only error out when no enabling extensions are
  320. // registered.
  321. if (min_version == ~0u) {
  322. return _.diag(SPV_ERROR_MISSING_EXTENSION, inst)
  323. << spvOpcodeString(opcode)
  324. << " requires one of the following extensions: "
  325. << ExtensionSetToString(exts);
  326. }
  327. if (module_version < min_version) {
  328. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  329. << spvOpcodeString(opcode) << " requires SPIR-V version "
  330. << SPV_SPIRV_VERSION_MAJOR_PART(min_version) << "."
  331. << SPV_SPIRV_VERSION_MINOR_PART(min_version)
  332. << " at minimum or one of the following extensions: "
  333. << ExtensionSetToString(exts);
  334. }
  335. }
  336. return SPV_SUCCESS;
  337. }
  338. // Checks that the Resuld <id> is within the valid bound.
  339. spv_result_t LimitCheckIdBound(ValidationState_t& _, const Instruction* inst) {
  340. if (inst->id() >= _.getIdBound()) {
  341. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  342. << "Result <id> '" << inst->id()
  343. << "' must be less than the ID bound '" << _.getIdBound() << "'.";
  344. }
  345. return SPV_SUCCESS;
  346. }
  347. // Checks that the number of OpTypeStruct members is within the limit.
  348. spv_result_t LimitCheckStruct(ValidationState_t& _, const Instruction* inst) {
  349. if (SpvOpTypeStruct != inst->opcode()) {
  350. return SPV_SUCCESS;
  351. }
  352. // Number of members is the number of operands of the instruction minus 1.
  353. // One operand is the result ID.
  354. const uint16_t limit =
  355. static_cast<uint16_t>(_.options()->universal_limits_.max_struct_members);
  356. if (inst->operands().size() - 1 > limit) {
  357. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  358. << "Number of OpTypeStruct members (" << inst->operands().size() - 1
  359. << ") has exceeded the limit (" << limit << ").";
  360. }
  361. // Section 2.17 of SPIRV Spec specifies that the "Structure Nesting Depth"
  362. // must be less than or equal to 255.
  363. // This is interpreted as structures including other structures as
  364. // members. The code does not follow pointers or look into arrays to see
  365. // if we reach a structure downstream. The nesting depth of a struct is
  366. // 1+(largest depth of any member). Scalars are at depth 0.
  367. uint32_t max_member_depth = 0;
  368. // Struct members start at word 2 of OpTypeStruct instruction.
  369. for (size_t word_i = 2; word_i < inst->words().size(); ++word_i) {
  370. auto member = inst->word(word_i);
  371. auto memberTypeInstr = _.FindDef(member);
  372. if (memberTypeInstr && SpvOpTypeStruct == memberTypeInstr->opcode()) {
  373. max_member_depth = std::max(
  374. max_member_depth, _.struct_nesting_depth(memberTypeInstr->id()));
  375. }
  376. }
  377. const uint32_t depth_limit = _.options()->universal_limits_.max_struct_depth;
  378. const uint32_t cur_depth = 1 + max_member_depth;
  379. _.set_struct_nesting_depth(inst->id(), cur_depth);
  380. if (cur_depth > depth_limit) {
  381. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  382. << "Structure Nesting Depth may not be larger than " << depth_limit
  383. << ". Found " << cur_depth << ".";
  384. }
  385. return SPV_SUCCESS;
  386. }
  387. // Checks that the number of (literal, label) pairs in OpSwitch is within
  388. // the limit.
  389. spv_result_t LimitCheckSwitch(ValidationState_t& _, const Instruction* inst) {
  390. if (SpvOpSwitch == inst->opcode()) {
  391. // The instruction syntax is as follows:
  392. // OpSwitch <selector ID> <Default ID> literal label literal label ...
  393. // literal,label pairs come after the first 2 operands.
  394. // It is guaranteed at this point that num_operands is an even numner.
  395. size_t num_pairs = (inst->operands().size() - 2) / 2;
  396. const unsigned int num_pairs_limit =
  397. _.options()->universal_limits_.max_switch_branches;
  398. if (num_pairs > num_pairs_limit) {
  399. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  400. << "Number of (literal, label) pairs in OpSwitch (" << num_pairs
  401. << ") exceeds the limit (" << num_pairs_limit << ").";
  402. }
  403. }
  404. return SPV_SUCCESS;
  405. }
  406. // Ensure the number of variables of the given class does not exceed the
  407. // limit.
  408. spv_result_t LimitCheckNumVars(ValidationState_t& _, const uint32_t var_id,
  409. const SpvStorageClass storage_class) {
  410. if (SpvStorageClassFunction == storage_class) {
  411. _.registerLocalVariable(var_id);
  412. const uint32_t num_local_vars_limit =
  413. _.options()->universal_limits_.max_local_variables;
  414. if (_.num_local_vars() > num_local_vars_limit) {
  415. return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
  416. << "Number of local variables ('Function' Storage Class) "
  417. "exceeded the valid limit ("
  418. << num_local_vars_limit << ").";
  419. }
  420. } else {
  421. _.registerGlobalVariable(var_id);
  422. const uint32_t num_global_vars_limit =
  423. _.options()->universal_limits_.max_global_variables;
  424. if (_.num_global_vars() > num_global_vars_limit) {
  425. return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
  426. << "Number of Global Variables (Storage Class other than "
  427. "'Function') exceeded the valid limit ("
  428. << num_global_vars_limit << ").";
  429. }
  430. }
  431. return SPV_SUCCESS;
  432. }
  433. // Parses OpExtension instruction and logs warnings if unsuccessful.
  434. spv_result_t CheckIfKnownExtension(ValidationState_t& _,
  435. const Instruction* inst) {
  436. const std::string extension_str = GetExtensionString(&(inst->c_inst()));
  437. Extension extension;
  438. if (!GetExtensionFromString(extension_str.c_str(), &extension)) {
  439. return _.diag(SPV_WARNING, inst)
  440. << "Found unrecognized extension " << extension_str;
  441. }
  442. return SPV_SUCCESS;
  443. }
  444. } // namespace
  445. spv_result_t InstructionPass(ValidationState_t& _, const Instruction* inst) {
  446. const SpvOp opcode = inst->opcode();
  447. if (opcode == SpvOpExtension) {
  448. CheckIfKnownExtension(_, inst);
  449. } else if (opcode == SpvOpCapability) {
  450. _.RegisterCapability(inst->GetOperandAs<SpvCapability>(0));
  451. } else if (opcode == SpvOpMemoryModel) {
  452. if (_.has_memory_model_specified()) {
  453. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  454. << "OpMemoryModel should only be provided once.";
  455. }
  456. _.set_addressing_model(inst->GetOperandAs<SpvAddressingModel>(0));
  457. _.set_memory_model(inst->GetOperandAs<SpvMemoryModel>(1));
  458. if (_.memory_model() != SpvMemoryModelVulkanKHR &&
  459. _.HasCapability(SpvCapabilityVulkanMemoryModelKHR)) {
  460. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  461. << "VulkanMemoryModelKHR capability must only be specified if "
  462. "the "
  463. "VulkanKHR memory model is used.";
  464. }
  465. if (spvIsWebGPUEnv(_.context()->target_env)) {
  466. if (_.addressing_model() != SpvAddressingModelLogical) {
  467. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  468. << "Addressing model must be Logical for WebGPU environment.";
  469. }
  470. if (_.memory_model() != SpvMemoryModelVulkanKHR) {
  471. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  472. << "Memory model must be VulkanKHR for WebGPU environment.";
  473. }
  474. }
  475. if (spvIsOpenCLEnv(_.context()->target_env)) {
  476. if ((_.addressing_model() != SpvAddressingModelPhysical32) &&
  477. (_.addressing_model() != SpvAddressingModelPhysical64)) {
  478. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  479. << "Addressing model must be Physical32 or Physical64 "
  480. << "in the OpenCL environment.";
  481. }
  482. if (_.memory_model() != SpvMemoryModelOpenCL) {
  483. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  484. << "Memory model must be OpenCL in the OpenCL environment.";
  485. }
  486. }
  487. } else if (opcode == SpvOpExecutionMode) {
  488. const uint32_t entry_point = inst->word(1);
  489. _.RegisterExecutionModeForEntryPoint(entry_point,
  490. SpvExecutionMode(inst->word(2)));
  491. } else if (opcode == SpvOpVariable) {
  492. const auto storage_class = inst->GetOperandAs<SpvStorageClass>(2);
  493. if (auto error = LimitCheckNumVars(_, inst->id(), storage_class)) {
  494. return error;
  495. }
  496. if (spvIsWebGPUEnv(_.context()->target_env) &&
  497. !IsValidWebGPUStorageClass(storage_class)) {
  498. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  499. << "For WebGPU, OpVariable storage class must be one of "
  500. "UniformConstant, Uniform, StorageBuffer, Input, Output, "
  501. "Image, Workgroup, Private, Function for WebGPU";
  502. }
  503. if (storage_class == SpvStorageClassGeneric)
  504. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  505. << "OpVariable storage class cannot be Generic";
  506. if (_.current_layout_section() == kLayoutFunctionDefinitions) {
  507. if (storage_class != SpvStorageClassFunction) {
  508. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  509. << "Variables must have a function[7] storage class inside"
  510. " of a function";
  511. }
  512. if (_.current_function().IsFirstBlock(
  513. _.current_function().current_block()->id()) == false) {
  514. return _.diag(SPV_ERROR_INVALID_CFG, inst)
  515. << "Variables can only be defined "
  516. "in the first block of a "
  517. "function";
  518. }
  519. } else {
  520. if (storage_class == SpvStorageClassFunction) {
  521. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  522. << "Variables can not have a function[7] storage class "
  523. "outside of a function";
  524. }
  525. }
  526. } else if (opcode == SpvOpTypePointer) {
  527. const auto storage_class = inst->GetOperandAs<SpvStorageClass>(1);
  528. if (spvIsWebGPUEnv(_.context()->target_env) &&
  529. !IsValidWebGPUStorageClass(storage_class)) {
  530. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  531. << "For WebGPU, OpTypePointer storage class must be one of "
  532. "UniformConstant, Uniform, StorageBuffer, Input, Output, "
  533. "Image, Workgroup, Private, Function";
  534. }
  535. }
  536. // SPIR-V Spec 2.16.3: Validation Rules for Kernel Capabilities: The
  537. // Signedness in OpTypeInt must always be 0.
  538. if (SpvOpTypeInt == inst->opcode() && _.HasCapability(SpvCapabilityKernel) &&
  539. inst->GetOperandAs<uint32_t>(2) != 0u) {
  540. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  541. << "The Signedness in OpTypeInt "
  542. "must always be 0 when Kernel "
  543. "capability is used.";
  544. }
  545. if (auto error = ReservedCheck(_, inst)) return error;
  546. if (auto error = EnvironmentCheck(_, inst)) return error;
  547. if (auto error = CapabilityCheck(_, inst)) return error;
  548. if (auto error = LimitCheckIdBound(_, inst)) return error;
  549. if (auto error = LimitCheckStruct(_, inst)) return error;
  550. if (auto error = LimitCheckSwitch(_, inst)) return error;
  551. if (auto error = VersionCheck(_, inst)) return error;
  552. // All instruction checks have passed.
  553. return SPV_SUCCESS;
  554. }
  555. } // namespace val
  556. } // namespace spvtools