validate_interfaces.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. // Copyright (c) 2018 Google LLC.
  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. #include <algorithm>
  15. #include <vector>
  16. #include "source/diagnostic.h"
  17. #include "source/spirv_constant.h"
  18. #include "source/spirv_target_env.h"
  19. #include "source/val/function.h"
  20. #include "source/val/instruction.h"
  21. #include "source/val/validate.h"
  22. #include "source/val/validation_state.h"
  23. namespace spvtools {
  24. namespace val {
  25. namespace {
  26. // Returns true if \c inst is an input or output variable.
  27. bool is_interface_variable(const Instruction* inst, bool is_spv_1_4) {
  28. if (is_spv_1_4) {
  29. // Starting in SPIR-V 1.4, all global variables are interface variables.
  30. return inst->opcode() == SpvOpVariable &&
  31. inst->word(3u) != SpvStorageClassFunction;
  32. } else {
  33. return inst->opcode() == SpvOpVariable &&
  34. (inst->word(3u) == SpvStorageClassInput ||
  35. inst->word(3u) == SpvStorageClassOutput);
  36. }
  37. }
  38. // Checks that \c var is listed as an interface in all the entry points that use
  39. // it.
  40. spv_result_t check_interface_variable(ValidationState_t& _,
  41. const Instruction* var) {
  42. std::vector<const Function*> functions;
  43. std::vector<const Instruction*> uses;
  44. for (auto use : var->uses()) {
  45. uses.push_back(use.first);
  46. }
  47. for (uint32_t i = 0; i < uses.size(); ++i) {
  48. const auto user = uses[i];
  49. if (const Function* func = user->function()) {
  50. functions.push_back(func);
  51. } else {
  52. // In the rare case that the variable is used by another instruction in
  53. // the global scope, continue searching for an instruction used in a
  54. // function.
  55. for (auto use : user->uses()) {
  56. uses.push_back(use.first);
  57. }
  58. }
  59. }
  60. std::sort(functions.begin(), functions.end(),
  61. [](const Function* lhs, const Function* rhs) {
  62. return lhs->id() < rhs->id();
  63. });
  64. functions.erase(std::unique(functions.begin(), functions.end()),
  65. functions.end());
  66. std::vector<uint32_t> entry_points;
  67. for (const auto func : functions) {
  68. for (auto id : _.FunctionEntryPoints(func->id())) {
  69. entry_points.push_back(id);
  70. }
  71. }
  72. std::sort(entry_points.begin(), entry_points.end());
  73. entry_points.erase(std::unique(entry_points.begin(), entry_points.end()),
  74. entry_points.end());
  75. for (auto id : entry_points) {
  76. for (const auto& desc : _.entry_point_descriptions(id)) {
  77. bool found = false;
  78. for (auto interface : desc.interfaces) {
  79. if (var->id() == interface) {
  80. found = true;
  81. break;
  82. }
  83. }
  84. if (!found) {
  85. return _.diag(SPV_ERROR_INVALID_ID, var)
  86. << "Interface variable id <" << var->id()
  87. << "> is used by entry point '" << desc.name << "' id <" << id
  88. << ">, but is not listed as an interface";
  89. }
  90. }
  91. }
  92. return SPV_SUCCESS;
  93. }
  94. // This function assumes a base location has been determined already. As such
  95. // any further location decorations are invalid.
  96. // TODO: if this code turns out to be slow, there is an opportunity to cache
  97. // the result for a given type id.
  98. spv_result_t NumConsumedLocations(ValidationState_t& _, const Instruction* type,
  99. uint32_t* num_locations) {
  100. *num_locations = 0;
  101. switch (type->opcode()) {
  102. case SpvOpTypeInt:
  103. case SpvOpTypeFloat:
  104. // Scalars always consume a single location.
  105. *num_locations = 1;
  106. break;
  107. case SpvOpTypeVector:
  108. // 3- and 4-component 64-bit vectors consume two locations.
  109. if ((_.ContainsSizedIntOrFloatType(type->id(), SpvOpTypeInt, 64) ||
  110. _.ContainsSizedIntOrFloatType(type->id(), SpvOpTypeFloat, 64)) &&
  111. (type->GetOperandAs<uint32_t>(2) > 2)) {
  112. *num_locations = 2;
  113. } else {
  114. *num_locations = 1;
  115. }
  116. break;
  117. case SpvOpTypeMatrix:
  118. // Matrices consume locations equal to the underlying vector type for
  119. // each column.
  120. NumConsumedLocations(_, _.FindDef(type->GetOperandAs<uint32_t>(1)),
  121. num_locations);
  122. *num_locations *= type->GetOperandAs<uint32_t>(2);
  123. break;
  124. case SpvOpTypeArray: {
  125. // Arrays consume locations equal to the underlying type times the number
  126. // of elements in the vector.
  127. NumConsumedLocations(_, _.FindDef(type->GetOperandAs<uint32_t>(1)),
  128. num_locations);
  129. bool is_int = false;
  130. bool is_const = false;
  131. uint32_t value = 0;
  132. // Attempt to evaluate the number of array elements.
  133. std::tie(is_int, is_const, value) =
  134. _.EvalInt32IfConst(type->GetOperandAs<uint32_t>(2));
  135. if (is_int && is_const) *num_locations *= value;
  136. break;
  137. }
  138. case SpvOpTypeStruct: {
  139. // Members cannot have location decorations at this point.
  140. if (_.HasDecoration(type->id(), SpvDecorationLocation)) {
  141. return _.diag(SPV_ERROR_INVALID_DATA, type)
  142. << "Members cannot be assigned a location";
  143. }
  144. // Structs consume locations equal to the sum of the locations consumed
  145. // by the members.
  146. for (uint32_t i = 1; i < type->operands().size(); ++i) {
  147. uint32_t member_locations = 0;
  148. if (auto error = NumConsumedLocations(
  149. _, _.FindDef(type->GetOperandAs<uint32_t>(i)),
  150. &member_locations)) {
  151. return error;
  152. }
  153. *num_locations += member_locations;
  154. }
  155. break;
  156. }
  157. default:
  158. break;
  159. }
  160. return SPV_SUCCESS;
  161. }
  162. // Returns the number of components consumed by types that support a component
  163. // decoration.
  164. uint32_t NumConsumedComponents(ValidationState_t& _, const Instruction* type) {
  165. uint32_t num_components = 0;
  166. switch (type->opcode()) {
  167. case SpvOpTypeInt:
  168. case SpvOpTypeFloat:
  169. // 64-bit types consume two components.
  170. if (type->GetOperandAs<uint32_t>(1) == 64) {
  171. num_components = 2;
  172. } else {
  173. num_components = 1;
  174. }
  175. break;
  176. case SpvOpTypeVector:
  177. // Vectors consume components equal to the underlying type's consumption
  178. // times the number of elements in the vector. Note that 3- and 4-element
  179. // vectors cannot have a component decoration (i.e. assumed to be zero).
  180. num_components =
  181. NumConsumedComponents(_, _.FindDef(type->GetOperandAs<uint32_t>(1)));
  182. num_components *= type->GetOperandAs<uint32_t>(2);
  183. break;
  184. default:
  185. // This is an error that is validated elsewhere.
  186. break;
  187. }
  188. return num_components;
  189. }
  190. // Populates |locations| (and/or |output_index1_locations|) with the use
  191. // location and component coordinates for |variable|. Indices are calculated as
  192. // 4 * location + component.
  193. spv_result_t GetLocationsForVariable(
  194. ValidationState_t& _, const Instruction* entry_point,
  195. const Instruction* variable, std::vector<bool>* locations,
  196. std::vector<bool>* output_index1_locations) {
  197. const bool is_fragment = entry_point->GetOperandAs<SpvExecutionModel>(0) ==
  198. SpvExecutionModelFragment;
  199. const bool is_output =
  200. variable->GetOperandAs<SpvStorageClass>(2) == SpvStorageClassOutput;
  201. auto ptr_type_id = variable->GetOperandAs<uint32_t>(0);
  202. auto ptr_type = _.FindDef(ptr_type_id);
  203. auto type_id = ptr_type->GetOperandAs<uint32_t>(2);
  204. auto type = _.FindDef(type_id);
  205. // Check for Location, Component and Index decorations on the variable. The
  206. // validator allows duplicate decorations if the location/component/index are
  207. // equal. Also track Patch and PerTaskNV decorations.
  208. bool has_location = false;
  209. uint32_t location = 0;
  210. bool has_component = false;
  211. uint32_t component = 0;
  212. bool has_index = false;
  213. uint32_t index = 0;
  214. bool has_patch = false;
  215. bool has_per_task_nv = false;
  216. bool has_per_vertex_nv = false;
  217. for (auto& dec : _.id_decorations(variable->id())) {
  218. if (dec.dec_type() == SpvDecorationLocation) {
  219. if (has_location && dec.params()[0] != location) {
  220. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  221. << "Variable has conflicting location decorations";
  222. }
  223. has_location = true;
  224. location = dec.params()[0];
  225. } else if (dec.dec_type() == SpvDecorationComponent) {
  226. if (has_component && dec.params()[0] != component) {
  227. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  228. << "Variable has conflicting component decorations";
  229. }
  230. has_component = true;
  231. component = dec.params()[0];
  232. } else if (dec.dec_type() == SpvDecorationIndex) {
  233. if (!is_output || !is_fragment) {
  234. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  235. << "Index can only be applied to Fragment output variables";
  236. }
  237. if (has_index && dec.params()[0] != index) {
  238. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  239. << "Variable has conflicting index decorations";
  240. }
  241. has_index = true;
  242. index = dec.params()[0];
  243. } else if (dec.dec_type() == SpvDecorationBuiltIn) {
  244. // Don't check built-ins.
  245. return SPV_SUCCESS;
  246. } else if (dec.dec_type() == SpvDecorationPatch) {
  247. has_patch = true;
  248. } else if (dec.dec_type() == SpvDecorationPerTaskNV) {
  249. has_per_task_nv = true;
  250. } else if (dec.dec_type() == SpvDecorationPerVertexNV) {
  251. has_per_vertex_nv = true;
  252. }
  253. }
  254. // Vulkan 14.1.3: Tessellation control and mesh per-vertex outputs and
  255. // tessellation control, evaluation and geometry per-vertex inputs have a
  256. // layer of arraying that is not included in interface matching.
  257. bool is_arrayed = false;
  258. switch (entry_point->GetOperandAs<SpvExecutionModel>(0)) {
  259. case SpvExecutionModelTessellationControl:
  260. if (!has_patch) {
  261. is_arrayed = true;
  262. }
  263. break;
  264. case SpvExecutionModelTessellationEvaluation:
  265. if (!is_output && !has_patch) {
  266. is_arrayed = true;
  267. }
  268. break;
  269. case SpvExecutionModelGeometry:
  270. if (!is_output) {
  271. is_arrayed = true;
  272. }
  273. break;
  274. case SpvExecutionModelFragment:
  275. if (!is_output && has_per_vertex_nv) {
  276. is_arrayed = true;
  277. }
  278. break;
  279. case SpvExecutionModelMeshNV:
  280. if (is_output && !has_per_task_nv) {
  281. is_arrayed = true;
  282. }
  283. break;
  284. default:
  285. break;
  286. }
  287. // Unpack arrayness.
  288. if (is_arrayed && (type->opcode() == SpvOpTypeArray ||
  289. type->opcode() == SpvOpTypeRuntimeArray)) {
  290. type_id = type->GetOperandAs<uint32_t>(1);
  291. type = _.FindDef(type_id);
  292. }
  293. if (type->opcode() == SpvOpTypeStruct) {
  294. // Don't check built-ins.
  295. if (_.HasDecoration(type_id, SpvDecorationBuiltIn)) return SPV_SUCCESS;
  296. }
  297. // Only block-decorated structs don't need a location on the variable.
  298. const bool is_block = _.HasDecoration(type_id, SpvDecorationBlock);
  299. if (!has_location && !is_block) {
  300. return _.diag(SPV_ERROR_INVALID_DATA, variable)
  301. << "Variable must be decorated with a location";
  302. }
  303. const std::string storage_class = is_output ? "output" : "input";
  304. if (has_location) {
  305. auto sub_type = type;
  306. bool is_int = false;
  307. bool is_const = false;
  308. uint32_t array_size = 1;
  309. // If the variable is still arrayed, mark the locations/components per
  310. // index.
  311. if (type->opcode() == SpvOpTypeArray) {
  312. // Determine the array size if possible and get the element type.
  313. std::tie(is_int, is_const, array_size) =
  314. _.EvalInt32IfConst(type->GetOperandAs<uint32_t>(2));
  315. if (!is_int || !is_const) array_size = 1;
  316. auto sub_type_id = type->GetOperandAs<uint32_t>(1);
  317. sub_type = _.FindDef(sub_type_id);
  318. }
  319. for (uint32_t array_idx = 0; array_idx < array_size; ++array_idx) {
  320. uint32_t num_locations = 0;
  321. if (auto error = NumConsumedLocations(_, sub_type, &num_locations))
  322. return error;
  323. uint32_t num_components = NumConsumedComponents(_, sub_type);
  324. uint32_t array_location = location + (num_locations * array_idx);
  325. uint32_t start = array_location * 4;
  326. uint32_t end = (array_location + num_locations) * 4;
  327. if (num_components != 0) {
  328. start += component;
  329. end = array_location * 4 + component + num_components;
  330. }
  331. auto locs = locations;
  332. if (has_index && index == 1) locs = output_index1_locations;
  333. if (end > locs->size()) {
  334. locs->resize(end, false);
  335. }
  336. for (uint32_t i = start; i < end; ++i) {
  337. if (locs->at(i)) {
  338. return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
  339. << "Entry-point has conflicting " << storage_class
  340. << " location assignment at location " << i / 4
  341. << ", component " << i % 4;
  342. }
  343. (*locs)[i] = true;
  344. }
  345. }
  346. } else {
  347. // For Block-decorated structs with no location assigned to the variable,
  348. // each member of the block must be assigned a location. Also record any
  349. // member component assignments. The validator allows duplicate decorations
  350. // if they agree on the location/component.
  351. std::unordered_map<uint32_t, uint32_t> member_locations;
  352. std::unordered_map<uint32_t, uint32_t> member_components;
  353. for (auto& dec : _.id_decorations(type_id)) {
  354. if (dec.dec_type() == SpvDecorationLocation) {
  355. auto where = member_locations.find(dec.struct_member_index());
  356. if (where == member_locations.end()) {
  357. member_locations[dec.struct_member_index()] = dec.params()[0];
  358. } else if (where->second != dec.params()[0]) {
  359. return _.diag(SPV_ERROR_INVALID_DATA, type)
  360. << "Member index " << dec.struct_member_index()
  361. << " has conflicting location assignments";
  362. }
  363. } else if (dec.dec_type() == SpvDecorationComponent) {
  364. auto where = member_components.find(dec.struct_member_index());
  365. if (where == member_components.end()) {
  366. member_components[dec.struct_member_index()] = dec.params()[0];
  367. } else if (where->second != dec.params()[0]) {
  368. return _.diag(SPV_ERROR_INVALID_DATA, type)
  369. << "Member index " << dec.struct_member_index()
  370. << " has conflicting component assignments";
  371. }
  372. }
  373. }
  374. for (uint32_t i = 1; i < type->operands().size(); ++i) {
  375. auto where = member_locations.find(i - 1);
  376. if (where == member_locations.end()) {
  377. return _.diag(SPV_ERROR_INVALID_DATA, type)
  378. << "Member index " << i - 1
  379. << " is missing a location assignment";
  380. }
  381. location = where->second;
  382. auto member = _.FindDef(type->GetOperandAs<uint32_t>(i));
  383. uint32_t num_locations = 0;
  384. if (auto error = NumConsumedLocations(_, member, &num_locations))
  385. return error;
  386. // If the component is not specified, it is assumed to be zero.
  387. uint32_t num_components = NumConsumedComponents(_, member);
  388. component = 0;
  389. if (member_components.count(i - 1)) {
  390. component = member_components[i - 1];
  391. }
  392. uint32_t start = location * 4;
  393. uint32_t end = (location + num_locations) * 4;
  394. if (num_components != 0) {
  395. start += component;
  396. end = location * 4 + component + num_components;
  397. }
  398. if (end > locations->size()) {
  399. locations->resize(end, false);
  400. }
  401. for (uint32_t l = start; l < end; ++l) {
  402. if (locations->at(l)) {
  403. return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
  404. << "Entry-point has conflicting " << storage_class
  405. << " location assignment at location " << l / 4
  406. << ", component " << l % 4;
  407. }
  408. (*locations)[l] = true;
  409. }
  410. }
  411. }
  412. return SPV_SUCCESS;
  413. }
  414. spv_result_t ValidateLocations(ValidationState_t& _,
  415. const Instruction* entry_point) {
  416. // Reserve space for 16 locations with 4 components each.
  417. std::vector<bool> input_locations(16 * 4, false);
  418. std::vector<bool> output_locations_index0(16 * 4, false);
  419. std::vector<bool> output_locations_index1(16 * 4, false);
  420. for (uint32_t i = 3; i < entry_point->operands().size(); ++i) {
  421. auto interface_id = entry_point->GetOperandAs<uint32_t>(i);
  422. auto interface_var = _.FindDef(interface_id);
  423. auto storage_class = interface_var->GetOperandAs<SpvStorageClass>(2);
  424. if (storage_class != SpvStorageClassInput &&
  425. storage_class != SpvStorageClassOutput) {
  426. continue;
  427. }
  428. auto locations = (storage_class == SpvStorageClassInput)
  429. ? &input_locations
  430. : &output_locations_index0;
  431. if (auto error = GetLocationsForVariable(
  432. _, entry_point, interface_var, locations, &output_locations_index1))
  433. return error;
  434. }
  435. return SPV_SUCCESS;
  436. }
  437. } // namespace
  438. spv_result_t ValidateInterfaces(ValidationState_t& _) {
  439. bool is_spv_1_4 = _.version() >= SPV_SPIRV_VERSION_WORD(1, 4);
  440. for (auto& inst : _.ordered_instructions()) {
  441. if (is_interface_variable(&inst, is_spv_1_4)) {
  442. if (auto error = check_interface_variable(_, &inst)) {
  443. return error;
  444. }
  445. }
  446. }
  447. if (spvIsVulkanEnv(_.context()->target_env)) {
  448. for (auto& inst : _.ordered_instructions()) {
  449. if (inst.opcode() == SpvOpEntryPoint) {
  450. if (auto error = ValidateLocations(_, &inst)) {
  451. return error;
  452. }
  453. }
  454. if (inst.opcode() == SpvOpTypeVoid) break;
  455. }
  456. }
  457. return SPV_SUCCESS;
  458. }
  459. } // namespace val
  460. } // namespace spvtools