validate_instruction.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. // Returns capabilities that enable an opcode. An empty result is interpreted
  53. // as no prohibition of use of the opcode. If the result is non-empty, then
  54. // the opcode may only be used if at least one of the capabilities is specified
  55. // by the module.
  56. CapabilitySet EnablingCapabilitiesForOp(const ValidationState_t& state,
  57. SpvOp opcode) {
  58. // Exceptions for SPV_AMD_shader_ballot
  59. switch (opcode) {
  60. // Normally these would require Group capability
  61. case SpvOpGroupIAddNonUniformAMD:
  62. case SpvOpGroupFAddNonUniformAMD:
  63. case SpvOpGroupFMinNonUniformAMD:
  64. case SpvOpGroupUMinNonUniformAMD:
  65. case SpvOpGroupSMinNonUniformAMD:
  66. case SpvOpGroupFMaxNonUniformAMD:
  67. case SpvOpGroupUMaxNonUniformAMD:
  68. case SpvOpGroupSMaxNonUniformAMD:
  69. if (state.HasExtension(kSPV_AMD_shader_ballot)) return CapabilitySet();
  70. break;
  71. default:
  72. break;
  73. }
  74. // Look it up in the grammar
  75. spv_opcode_desc opcode_desc = {};
  76. if (SPV_SUCCESS == state.grammar().lookupOpcode(opcode, &opcode_desc)) {
  77. return state.grammar().filterCapsAgainstTargetEnv(
  78. opcode_desc->capabilities, opcode_desc->numCapabilities);
  79. }
  80. return CapabilitySet();
  81. }
  82. // Returns SPV_SUCCESS if, for the given operand, the target environment
  83. // satsifies minimum version requirements, or if the module declares an
  84. // enabling extension for the operand. Otherwise emit a diagnostic and
  85. // return an error code.
  86. spv_result_t OperandVersionExtensionCheck(
  87. ValidationState_t& _, const Instruction* inst, size_t which_operand,
  88. const spv_operand_desc_t& operand_desc, uint32_t word) {
  89. const uint32_t module_version = _.version();
  90. const uint32_t operand_min_version = operand_desc.minVersion;
  91. const uint32_t operand_last_version = operand_desc.lastVersion;
  92. const bool reserved = operand_min_version == 0xffffffffu;
  93. const bool version_satisfied = !reserved &&
  94. (operand_min_version <= module_version) &&
  95. (module_version <= operand_last_version);
  96. if (version_satisfied) {
  97. return SPV_SUCCESS;
  98. }
  99. if (operand_last_version < module_version) {
  100. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  101. << spvtools::utils::CardinalToOrdinal(which_operand)
  102. << " operand of " << spvOpcodeString(inst->opcode()) << ": operand "
  103. << operand_desc.name << "(" << word << ") requires SPIR-V version "
  104. << SPV_SPIRV_VERSION_MAJOR_PART(operand_last_version) << "."
  105. << SPV_SPIRV_VERSION_MINOR_PART(operand_last_version)
  106. << " or earlier";
  107. }
  108. if (!reserved && operand_desc.numExtensions == 0) {
  109. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  110. << spvtools::utils::CardinalToOrdinal(which_operand)
  111. << " operand of " << spvOpcodeString(inst->opcode()) << ": operand "
  112. << operand_desc.name << "(" << word << ") requires SPIR-V version "
  113. << SPV_SPIRV_VERSION_MAJOR_PART(operand_min_version) << "."
  114. << SPV_SPIRV_VERSION_MINOR_PART(operand_min_version) << " or later";
  115. } else {
  116. ExtensionSet required_extensions(operand_desc.numExtensions,
  117. operand_desc.extensions);
  118. if (!_.HasAnyOfExtensions(required_extensions)) {
  119. return _.diag(SPV_ERROR_MISSING_EXTENSION, inst)
  120. << spvtools::utils::CardinalToOrdinal(which_operand)
  121. << " operand of " << spvOpcodeString(inst->opcode())
  122. << ": operand " << operand_desc.name << "(" << word
  123. << ") requires one of these extensions: "
  124. << ExtensionSetToString(required_extensions);
  125. }
  126. }
  127. return SPV_SUCCESS;
  128. }
  129. // Returns SPV_SUCCESS if the given operand is enabled by capabilities declared
  130. // in the module. Otherwise issues an error message and returns
  131. // SPV_ERROR_INVALID_CAPABILITY.
  132. spv_result_t CheckRequiredCapabilities(ValidationState_t& state,
  133. const Instruction* inst,
  134. size_t which_operand,
  135. const spv_parsed_operand_t& operand,
  136. uint32_t word) {
  137. // Mere mention of PointSize, ClipDistance, or CullDistance in a Builtin
  138. // decoration does not require the associated capability. The use of such
  139. // a variable value should trigger the capability requirement, but that's
  140. // not implemented yet. This rule is independent of target environment.
  141. // See https://github.com/KhronosGroup/SPIRV-Tools/issues/365
  142. if (operand.type == SPV_OPERAND_TYPE_BUILT_IN) {
  143. switch (word) {
  144. case SpvBuiltInPointSize:
  145. case SpvBuiltInClipDistance:
  146. case SpvBuiltInCullDistance:
  147. return SPV_SUCCESS;
  148. default:
  149. break;
  150. }
  151. } else if (operand.type == SPV_OPERAND_TYPE_FP_ROUNDING_MODE) {
  152. // Allow all FP rounding modes if requested
  153. if (state.features().free_fp_rounding_mode) {
  154. return SPV_SUCCESS;
  155. }
  156. } else if (operand.type == SPV_OPERAND_TYPE_GROUP_OPERATION &&
  157. state.features().group_ops_reduce_and_scans &&
  158. (word <= uint32_t(SpvGroupOperationExclusiveScan))) {
  159. // Allow certain group operations if requested.
  160. return SPV_SUCCESS;
  161. }
  162. CapabilitySet enabling_capabilities;
  163. spv_operand_desc operand_desc = nullptr;
  164. const auto lookup_result =
  165. state.grammar().lookupOperand(operand.type, word, &operand_desc);
  166. if (lookup_result == SPV_SUCCESS) {
  167. // Allow FPRoundingMode decoration if requested.
  168. if (operand.type == SPV_OPERAND_TYPE_DECORATION &&
  169. operand_desc->value == SpvDecorationFPRoundingMode) {
  170. if (state.features().free_fp_rounding_mode) return SPV_SUCCESS;
  171. // Vulkan API requires more capabilities on rounding mode.
  172. if (spvIsVulkanEnv(state.context()->target_env)) {
  173. enabling_capabilities.Add(SpvCapabilityStorageUniformBufferBlock16);
  174. enabling_capabilities.Add(SpvCapabilityStorageUniform16);
  175. enabling_capabilities.Add(SpvCapabilityStoragePushConstant16);
  176. enabling_capabilities.Add(SpvCapabilityStorageInputOutput16);
  177. }
  178. } else {
  179. enabling_capabilities = state.grammar().filterCapsAgainstTargetEnv(
  180. operand_desc->capabilities, operand_desc->numCapabilities);
  181. }
  182. // When encountering an OpCapability instruction, the instruction pass
  183. // registers a capability with the module *before* checking capabilities.
  184. // So in the case of an OpCapability instruction, don't bother checking
  185. // enablement by another capability.
  186. if (inst->opcode() != SpvOpCapability) {
  187. const bool enabled_by_cap =
  188. state.HasAnyOfCapabilities(enabling_capabilities);
  189. if (!enabling_capabilities.IsEmpty() && !enabled_by_cap) {
  190. return state.diag(SPV_ERROR_INVALID_CAPABILITY, inst)
  191. << "Operand " << which_operand << " of "
  192. << spvOpcodeString(inst->opcode())
  193. << " requires one of these capabilities: "
  194. << ToString(enabling_capabilities, state.grammar());
  195. }
  196. }
  197. return OperandVersionExtensionCheck(state, inst, which_operand,
  198. *operand_desc, word);
  199. }
  200. return SPV_SUCCESS;
  201. }
  202. // Returns SPV_ERROR_INVALID_BINARY and emits a diagnostic if the instruction
  203. // is explicitly reserved in the SPIR-V core spec. Otherwise return
  204. // SPV_SUCCESS.
  205. spv_result_t ReservedCheck(ValidationState_t& _, const Instruction* inst) {
  206. const SpvOp opcode = inst->opcode();
  207. switch (opcode) {
  208. // These instructions are enabled by a capability, but should never
  209. // be used anyway.
  210. case SpvOpImageSparseSampleProjImplicitLod:
  211. case SpvOpImageSparseSampleProjExplicitLod:
  212. case SpvOpImageSparseSampleProjDrefImplicitLod:
  213. case SpvOpImageSparseSampleProjDrefExplicitLod: {
  214. spv_opcode_desc inst_desc;
  215. _.grammar().lookupOpcode(opcode, &inst_desc);
  216. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  217. << "Invalid Opcode name 'Op" << inst_desc->name << "'";
  218. }
  219. default:
  220. break;
  221. }
  222. return SPV_SUCCESS;
  223. }
  224. // Returns SPV_ERROR_INVALID_CAPABILITY and emits a diagnostic if the
  225. // instruction is invalid because the required capability isn't declared
  226. // in the module.
  227. spv_result_t CapabilityCheck(ValidationState_t& _, const Instruction* inst) {
  228. const SpvOp opcode = inst->opcode();
  229. CapabilitySet opcode_caps = EnablingCapabilitiesForOp(_, opcode);
  230. if (!_.HasAnyOfCapabilities(opcode_caps)) {
  231. return _.diag(SPV_ERROR_INVALID_CAPABILITY, inst)
  232. << "Opcode " << spvOpcodeString(opcode)
  233. << " requires one of these capabilities: "
  234. << ToString(opcode_caps, _.grammar());
  235. }
  236. for (size_t i = 0; i < inst->operands().size(); ++i) {
  237. const auto& operand = inst->operand(i);
  238. const auto word = inst->word(operand.offset);
  239. if (spvOperandIsConcreteMask(operand.type)) {
  240. // Check for required capabilities for each bit position of the mask.
  241. for (uint32_t mask_bit = 0x80000000; mask_bit; mask_bit >>= 1) {
  242. if (word & mask_bit) {
  243. spv_result_t status =
  244. CheckRequiredCapabilities(_, inst, i + 1, operand, mask_bit);
  245. if (status != SPV_SUCCESS) return status;
  246. }
  247. }
  248. } else if (spvIsIdType(operand.type)) {
  249. // TODO(dneto): Check the value referenced by this Id, if we can compute
  250. // it. For now, just punt, to fix issue 248:
  251. // https://github.com/KhronosGroup/SPIRV-Tools/issues/248
  252. } else {
  253. // Check the operand word as a whole.
  254. spv_result_t status =
  255. CheckRequiredCapabilities(_, inst, i + 1, operand, word);
  256. if (status != SPV_SUCCESS) return status;
  257. }
  258. }
  259. return SPV_SUCCESS;
  260. }
  261. // Checks that the instruction can be used in this target environment's base
  262. // version. Assumes that CapabilityCheck has checked direct capability
  263. // dependencies for the opcode.
  264. spv_result_t VersionCheck(ValidationState_t& _, const Instruction* inst) {
  265. const auto opcode = inst->opcode();
  266. spv_opcode_desc inst_desc;
  267. const spv_result_t r = _.grammar().lookupOpcode(opcode, &inst_desc);
  268. assert(r == SPV_SUCCESS);
  269. (void)r;
  270. const auto min_version = inst_desc->minVersion;
  271. const auto last_version = inst_desc->lastVersion;
  272. const auto module_version = _.version();
  273. if (last_version < module_version) {
  274. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  275. << spvOpcodeString(opcode) << " requires SPIR-V version "
  276. << SPV_SPIRV_VERSION_MAJOR_PART(last_version) << "."
  277. << SPV_SPIRV_VERSION_MINOR_PART(last_version) << " or earlier";
  278. }
  279. if (inst_desc->numCapabilities > 0u) {
  280. // We already checked that the direct capability dependency has been
  281. // satisfied. We don't need to check any further.
  282. return SPV_SUCCESS;
  283. }
  284. ExtensionSet exts(inst_desc->numExtensions, inst_desc->extensions);
  285. if (exts.IsEmpty()) {
  286. // If no extensions can enable this instruction, then emit error
  287. // messages only concerning core SPIR-V versions if errors happen.
  288. if (min_version == ~0u) {
  289. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  290. << spvOpcodeString(opcode) << " is reserved for future use.";
  291. }
  292. if (module_version < min_version) {
  293. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  294. << spvOpcodeString(opcode) << " requires "
  295. << spvTargetEnvDescription(
  296. static_cast<spv_target_env>(min_version))
  297. << " at minimum.";
  298. }
  299. } else if (!_.HasAnyOfExtensions(exts)) {
  300. // Otherwise, we only error out when no enabling extensions are
  301. // registered.
  302. if (min_version == ~0u) {
  303. return _.diag(SPV_ERROR_MISSING_EXTENSION, inst)
  304. << spvOpcodeString(opcode)
  305. << " requires one of the following extensions: "
  306. << ExtensionSetToString(exts);
  307. }
  308. if (module_version < min_version) {
  309. return _.diag(SPV_ERROR_WRONG_VERSION, inst)
  310. << spvOpcodeString(opcode) << " requires SPIR-V version "
  311. << SPV_SPIRV_VERSION_MAJOR_PART(min_version) << "."
  312. << SPV_SPIRV_VERSION_MINOR_PART(min_version)
  313. << " at minimum or one of the following extensions: "
  314. << ExtensionSetToString(exts);
  315. }
  316. }
  317. return SPV_SUCCESS;
  318. }
  319. // Checks that the Resuld <id> is within the valid bound.
  320. spv_result_t LimitCheckIdBound(ValidationState_t& _, const Instruction* inst) {
  321. if (inst->id() >= _.getIdBound()) {
  322. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  323. << "Result <id> '" << inst->id()
  324. << "' must be less than the ID bound '" << _.getIdBound() << "'.";
  325. }
  326. return SPV_SUCCESS;
  327. }
  328. // Checks that the number of OpTypeStruct members is within the limit.
  329. spv_result_t LimitCheckStruct(ValidationState_t& _, const Instruction* inst) {
  330. if (SpvOpTypeStruct != inst->opcode()) {
  331. return SPV_SUCCESS;
  332. }
  333. // Number of members is the number of operands of the instruction minus 1.
  334. // One operand is the result ID.
  335. const uint16_t limit =
  336. static_cast<uint16_t>(_.options()->universal_limits_.max_struct_members);
  337. if (inst->operands().size() - 1 > limit) {
  338. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  339. << "Number of OpTypeStruct members (" << inst->operands().size() - 1
  340. << ") has exceeded the limit (" << limit << ").";
  341. }
  342. // Section 2.17 of SPIRV Spec specifies that the "Structure Nesting Depth"
  343. // must be less than or equal to 255.
  344. // This is interpreted as structures including other structures as
  345. // members. The code does not follow pointers or look into arrays to see
  346. // if we reach a structure downstream. The nesting depth of a struct is
  347. // 1+(largest depth of any member). Scalars are at depth 0.
  348. uint32_t max_member_depth = 0;
  349. // Struct members start at word 2 of OpTypeStruct instruction.
  350. for (size_t word_i = 2; word_i < inst->words().size(); ++word_i) {
  351. auto member = inst->word(word_i);
  352. auto memberTypeInstr = _.FindDef(member);
  353. if (memberTypeInstr && SpvOpTypeStruct == memberTypeInstr->opcode()) {
  354. max_member_depth = std::max(
  355. max_member_depth, _.struct_nesting_depth(memberTypeInstr->id()));
  356. }
  357. }
  358. const uint32_t depth_limit = _.options()->universal_limits_.max_struct_depth;
  359. const uint32_t cur_depth = 1 + max_member_depth;
  360. _.set_struct_nesting_depth(inst->id(), cur_depth);
  361. if (cur_depth > depth_limit) {
  362. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  363. << "Structure Nesting Depth may not be larger than " << depth_limit
  364. << ". Found " << cur_depth << ".";
  365. }
  366. return SPV_SUCCESS;
  367. }
  368. // Checks that the number of (literal, label) pairs in OpSwitch is within
  369. // the limit.
  370. spv_result_t LimitCheckSwitch(ValidationState_t& _, const Instruction* inst) {
  371. if (SpvOpSwitch == inst->opcode()) {
  372. // The instruction syntax is as follows:
  373. // OpSwitch <selector ID> <Default ID> literal label literal label ...
  374. // literal,label pairs come after the first 2 operands.
  375. // It is guaranteed at this point that num_operands is an even numner.
  376. size_t num_pairs = (inst->operands().size() - 2) / 2;
  377. const unsigned int num_pairs_limit =
  378. _.options()->universal_limits_.max_switch_branches;
  379. if (num_pairs > num_pairs_limit) {
  380. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  381. << "Number of (literal, label) pairs in OpSwitch (" << num_pairs
  382. << ") exceeds the limit (" << num_pairs_limit << ").";
  383. }
  384. }
  385. return SPV_SUCCESS;
  386. }
  387. // Ensure the number of variables of the given class does not exceed the
  388. // limit.
  389. spv_result_t LimitCheckNumVars(ValidationState_t& _, const uint32_t var_id,
  390. const SpvStorageClass storage_class) {
  391. if (SpvStorageClassFunction == storage_class) {
  392. _.registerLocalVariable(var_id);
  393. const uint32_t num_local_vars_limit =
  394. _.options()->universal_limits_.max_local_variables;
  395. if (_.num_local_vars() > num_local_vars_limit) {
  396. return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
  397. << "Number of local variables ('Function' Storage Class) "
  398. "exceeded the valid limit ("
  399. << num_local_vars_limit << ").";
  400. }
  401. } else {
  402. _.registerGlobalVariable(var_id);
  403. const uint32_t num_global_vars_limit =
  404. _.options()->universal_limits_.max_global_variables;
  405. if (_.num_global_vars() > num_global_vars_limit) {
  406. return _.diag(SPV_ERROR_INVALID_BINARY, nullptr)
  407. << "Number of Global Variables (Storage Class other than "
  408. "'Function') exceeded the valid limit ("
  409. << num_global_vars_limit << ").";
  410. }
  411. }
  412. return SPV_SUCCESS;
  413. }
  414. // Parses OpExtension instruction and logs warnings if unsuccessful.
  415. spv_result_t CheckIfKnownExtension(ValidationState_t& _,
  416. const Instruction* inst) {
  417. const std::string extension_str = GetExtensionString(&(inst->c_inst()));
  418. Extension extension;
  419. if (!GetExtensionFromString(extension_str.c_str(), &extension)) {
  420. return _.diag(SPV_WARNING, inst)
  421. << "Found unrecognized extension " << extension_str;
  422. }
  423. return SPV_SUCCESS;
  424. }
  425. } // namespace
  426. spv_result_t InstructionPass(ValidationState_t& _, const Instruction* inst) {
  427. const SpvOp opcode = inst->opcode();
  428. if (opcode == SpvOpExtension) {
  429. CheckIfKnownExtension(_, inst);
  430. } else if (opcode == SpvOpCapability) {
  431. _.RegisterCapability(inst->GetOperandAs<SpvCapability>(0));
  432. } else if (opcode == SpvOpMemoryModel) {
  433. if (_.has_memory_model_specified()) {
  434. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  435. << "OpMemoryModel should only be provided once.";
  436. }
  437. _.set_addressing_model(inst->GetOperandAs<SpvAddressingModel>(0));
  438. _.set_memory_model(inst->GetOperandAs<SpvMemoryModel>(1));
  439. } else if (opcode == SpvOpExecutionMode) {
  440. const uint32_t entry_point = inst->word(1);
  441. _.RegisterExecutionModeForEntryPoint(entry_point,
  442. SpvExecutionMode(inst->word(2)));
  443. } else if (opcode == SpvOpVariable) {
  444. const auto storage_class = inst->GetOperandAs<SpvStorageClass>(2);
  445. if (auto error = LimitCheckNumVars(_, inst->id(), storage_class)) {
  446. return error;
  447. }
  448. }
  449. if (auto error = ReservedCheck(_, inst)) return error;
  450. if (auto error = CapabilityCheck(_, inst)) return error;
  451. if (auto error = LimitCheckIdBound(_, inst)) return error;
  452. if (auto error = LimitCheckStruct(_, inst)) return error;
  453. if (auto error = LimitCheckSwitch(_, inst)) return error;
  454. if (auto error = VersionCheck(_, inst)) return error;
  455. // All instruction checks have passed.
  456. return SPV_SUCCESS;
  457. }
  458. } // namespace val
  459. } // namespace spvtools