validate_memory.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  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 "source/val/validate.h"
  15. #include <algorithm>
  16. #include <string>
  17. #include <vector>
  18. #include "source/opcode.h"
  19. #include "source/spirv_target_env.h"
  20. #include "source/val/instruction.h"
  21. #include "source/val/validate_scopes.h"
  22. #include "source/val/validation_state.h"
  23. namespace spvtools {
  24. namespace val {
  25. namespace {
  26. bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
  27. const Instruction*);
  28. bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
  29. const Instruction*);
  30. bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
  31. const Instruction*);
  32. bool HasConflictingMemberOffsets(const std::vector<Decoration>&,
  33. const std::vector<Decoration>&);
  34. bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction* type,
  35. std::initializer_list<uint32_t> allowed) {
  36. if (std::find(allowed.begin(), allowed.end(), type->opcode()) !=
  37. allowed.end()) {
  38. return true;
  39. }
  40. if (type->opcode() == SpvOpTypeArray ||
  41. type->opcode() == SpvOpTypeRuntimeArray) {
  42. auto elem_type = _.FindDef(type->word(2));
  43. return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
  44. allowed.end();
  45. }
  46. return false;
  47. }
  48. // Returns true if the two instructions represent structs that, as far as the
  49. // validator can tell, have the exact same data layout.
  50. bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
  51. const Instruction* type2) {
  52. if (type1->opcode() != SpvOpTypeStruct) {
  53. return false;
  54. }
  55. if (type2->opcode() != SpvOpTypeStruct) {
  56. return false;
  57. }
  58. if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
  59. return HaveSameLayoutDecorations(_, type1, type2);
  60. }
  61. // Returns true if the operands to the OpTypeStruct instruction defining the
  62. // types are the same or are layout compatible types. |type1| and |type2| must
  63. // be OpTypeStruct instructions.
  64. bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
  65. const Instruction* type2) {
  66. assert(type1->opcode() == SpvOpTypeStruct &&
  67. "type1 must be an OpTypeStruct instruction.");
  68. assert(type2->opcode() == SpvOpTypeStruct &&
  69. "type2 must be an OpTypeStruct instruction.");
  70. const auto& type1_operands = type1->operands();
  71. const auto& type2_operands = type2->operands();
  72. if (type1_operands.size() != type2_operands.size()) {
  73. return false;
  74. }
  75. for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
  76. if (type1->word(operand) != type2->word(operand)) {
  77. auto def1 = _.FindDef(type1->word(operand));
  78. auto def2 = _.FindDef(type2->word(operand));
  79. if (!AreLayoutCompatibleStructs(_, def1, def2)) {
  80. return false;
  81. }
  82. }
  83. }
  84. return true;
  85. }
  86. // Returns true if all decorations that affect the data layout of the struct
  87. // (like Offset), are the same for the two types. |type1| and |type2| must be
  88. // OpTypeStruct instructions.
  89. bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
  90. const Instruction* type2) {
  91. assert(type1->opcode() == SpvOpTypeStruct &&
  92. "type1 must be an OpTypeStruct instruction.");
  93. assert(type2->opcode() == SpvOpTypeStruct &&
  94. "type2 must be an OpTypeStruct instruction.");
  95. const std::vector<Decoration>& type1_decorations =
  96. _.id_decorations(type1->id());
  97. const std::vector<Decoration>& type2_decorations =
  98. _.id_decorations(type2->id());
  99. // TODO: Will have to add other check for arrays an matricies if we want to
  100. // handle them.
  101. if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
  102. return false;
  103. }
  104. return true;
  105. }
  106. bool HasConflictingMemberOffsets(
  107. const std::vector<Decoration>& type1_decorations,
  108. const std::vector<Decoration>& type2_decorations) {
  109. {
  110. // We are interested in conflicting decoration. If a decoration is in one
  111. // list but not the other, then we will assume the code is correct. We are
  112. // looking for things we know to be wrong.
  113. //
  114. // We do not have to traverse type2_decoration because, after traversing
  115. // type1_decorations, anything new will not be found in
  116. // type1_decoration. Therefore, it cannot lead to a conflict.
  117. for (const Decoration& decoration : type1_decorations) {
  118. switch (decoration.dec_type()) {
  119. case SpvDecorationOffset: {
  120. // Since these affect the layout of the struct, they must be present
  121. // in both structs.
  122. auto compare = [&decoration](const Decoration& rhs) {
  123. if (rhs.dec_type() != SpvDecorationOffset) return false;
  124. return decoration.struct_member_index() ==
  125. rhs.struct_member_index();
  126. };
  127. auto i = std::find_if(type2_decorations.begin(),
  128. type2_decorations.end(), compare);
  129. if (i != type2_decorations.end() &&
  130. decoration.params().front() != i->params().front()) {
  131. return true;
  132. }
  133. } break;
  134. default:
  135. // This decoration does not affect the layout of the structure, so
  136. // just moving on.
  137. break;
  138. }
  139. }
  140. }
  141. return false;
  142. }
  143. // If |skip_builtin| is true, returns true if |storage| contains bool within
  144. // it and no storage that contains the bool is builtin.
  145. // If |skip_builtin| is false, returns true if |storage| contains bool within
  146. // it.
  147. bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
  148. bool skip_builtin) {
  149. if (skip_builtin) {
  150. for (const Decoration& decoration : _.id_decorations(storage->id())) {
  151. if (decoration.dec_type() == SpvDecorationBuiltIn) return false;
  152. }
  153. }
  154. const size_t elem_type_index = 1;
  155. uint32_t elem_type_id;
  156. Instruction* elem_type;
  157. switch (storage->opcode()) {
  158. case SpvOpTypeBool:
  159. return true;
  160. case SpvOpTypeVector:
  161. case SpvOpTypeMatrix:
  162. case SpvOpTypeArray:
  163. case SpvOpTypeRuntimeArray:
  164. elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
  165. elem_type = _.FindDef(elem_type_id);
  166. return ContainsInvalidBool(_, elem_type, skip_builtin);
  167. case SpvOpTypeStruct:
  168. for (size_t member_type_index = 1;
  169. member_type_index < storage->operands().size();
  170. ++member_type_index) {
  171. auto member_type_id =
  172. storage->GetOperandAs<uint32_t>(member_type_index);
  173. auto member_type = _.FindDef(member_type_id);
  174. if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
  175. }
  176. default:
  177. break;
  178. }
  179. return false;
  180. }
  181. std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
  182. ValidationState_t& _, const Instruction* inst) {
  183. SpvStorageClass dst_sc = SpvStorageClassMax;
  184. SpvStorageClass src_sc = SpvStorageClassMax;
  185. switch (inst->opcode()) {
  186. case SpvOpLoad: {
  187. auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
  188. auto load_pointer_type = _.FindDef(load_pointer->type_id());
  189. dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
  190. break;
  191. }
  192. case SpvOpStore: {
  193. auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  194. auto store_pointer_type = _.FindDef(store_pointer->type_id());
  195. dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
  196. break;
  197. }
  198. case SpvOpCopyMemory:
  199. case SpvOpCopyMemorySized: {
  200. auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  201. auto dst_type = _.FindDef(dst->type_id());
  202. dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
  203. auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
  204. auto src_type = _.FindDef(src->type_id());
  205. src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
  206. break;
  207. }
  208. default:
  209. break;
  210. }
  211. return std::make_pair(dst_sc, src_sc);
  212. }
  213. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  214. // OpCopyMemorySized.
  215. uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask) {
  216. uint32_t offset = 1;
  217. if (mask & SpvMemoryAccessAlignedMask) ++offset;
  218. uint32_t scope_id = 0;
  219. switch (inst->opcode()) {
  220. case SpvOpLoad:
  221. case SpvOpCopyMemorySized:
  222. return inst->GetOperandAs<uint32_t>(3 + offset);
  223. case SpvOpStore:
  224. case SpvOpCopyMemory:
  225. return inst->GetOperandAs<uint32_t>(2 + offset);
  226. default:
  227. assert(false && "unexpected opcode");
  228. break;
  229. }
  230. return scope_id;
  231. }
  232. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  233. // OpCopyMemorySized.
  234. uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask) {
  235. uint32_t offset = 1;
  236. if (mask & SpvMemoryAccessAlignedMask) ++offset;
  237. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++offset;
  238. uint32_t scope_id = 0;
  239. switch (inst->opcode()) {
  240. case SpvOpLoad:
  241. case SpvOpCopyMemorySized:
  242. return inst->GetOperandAs<uint32_t>(3 + offset);
  243. case SpvOpStore:
  244. case SpvOpCopyMemory:
  245. return inst->GetOperandAs<uint32_t>(2 + offset);
  246. default:
  247. assert(false && "unexpected opcode");
  248. break;
  249. }
  250. return scope_id;
  251. }
  252. bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
  253. for (size_t member_index = 1; member_index < inst->operands().size();
  254. ++member_index) {
  255. const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
  256. const auto member_type = _.FindDef(member_id);
  257. if (member_type->opcode() == SpvOpTypeRuntimeArray) return true;
  258. }
  259. return false;
  260. }
  261. spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
  262. uint32_t index) {
  263. SpvStorageClass dst_sc, src_sc;
  264. std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
  265. if (inst->operands().size() <= index) {
  266. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  267. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  268. return _.diag(SPV_ERROR_INVALID_ID, inst)
  269. << "Memory accesses with PhysicalStorageBufferEXT must use "
  270. "Aligned.";
  271. }
  272. return SPV_SUCCESS;
  273. }
  274. uint32_t mask = inst->GetOperandAs<uint32_t>(index);
  275. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
  276. if (inst->opcode() == SpvOpLoad) {
  277. return _.diag(SPV_ERROR_INVALID_ID, inst)
  278. << "MakePointerAvailableKHR cannot be used with OpLoad.";
  279. }
  280. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  281. return _.diag(SPV_ERROR_INVALID_ID, inst)
  282. << "NonPrivatePointerKHR must be specified if "
  283. "MakePointerAvailableKHR is specified.";
  284. }
  285. // Check the associated scope for MakeAvailableKHR.
  286. const auto available_scope = GetMakeAvailableScope(inst, mask);
  287. if (auto error = ValidateMemoryScope(_, inst, available_scope))
  288. return error;
  289. }
  290. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
  291. if (inst->opcode() == SpvOpStore) {
  292. return _.diag(SPV_ERROR_INVALID_ID, inst)
  293. << "MakePointerVisibleKHR cannot be used with OpStore.";
  294. }
  295. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  296. return _.diag(SPV_ERROR_INVALID_ID, inst)
  297. << "NonPrivatePointerKHR must be specified if "
  298. << "MakePointerVisibleKHR is specified.";
  299. }
  300. // Check the associated scope for MakeVisibleKHR.
  301. const auto visible_scope = GetMakeVisibleScope(inst, mask);
  302. if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
  303. }
  304. if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
  305. if (dst_sc != SpvStorageClassUniform &&
  306. dst_sc != SpvStorageClassWorkgroup &&
  307. dst_sc != SpvStorageClassCrossWorkgroup &&
  308. dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
  309. dst_sc != SpvStorageClassStorageBuffer &&
  310. dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  311. return _.diag(SPV_ERROR_INVALID_ID, inst)
  312. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  313. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  314. << "storage classes.";
  315. }
  316. if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
  317. src_sc != SpvStorageClassWorkgroup &&
  318. src_sc != SpvStorageClassCrossWorkgroup &&
  319. src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
  320. src_sc != SpvStorageClassStorageBuffer &&
  321. src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  322. return _.diag(SPV_ERROR_INVALID_ID, inst)
  323. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  324. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  325. << "storage classes.";
  326. }
  327. }
  328. if (!(mask & SpvMemoryAccessAlignedMask)) {
  329. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  330. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  331. return _.diag(SPV_ERROR_INVALID_ID, inst)
  332. << "Memory accesses with PhysicalStorageBufferEXT must use "
  333. "Aligned.";
  334. }
  335. }
  336. return SPV_SUCCESS;
  337. }
  338. spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
  339. auto result_type = _.FindDef(inst->type_id());
  340. if (!result_type || result_type->opcode() != SpvOpTypePointer) {
  341. return _.diag(SPV_ERROR_INVALID_ID, inst)
  342. << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
  343. << "' is not a pointer type.";
  344. }
  345. const auto initializer_index = 3;
  346. const auto storage_class_index = 2;
  347. if (initializer_index < inst->operands().size()) {
  348. const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
  349. const auto initializer = _.FindDef(initializer_id);
  350. const auto is_module_scope_var =
  351. initializer && (initializer->opcode() == SpvOpVariable) &&
  352. (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
  353. SpvStorageClassFunction);
  354. const auto is_constant =
  355. initializer && spvOpcodeIsConstant(initializer->opcode());
  356. if (!initializer || !(is_constant || is_module_scope_var)) {
  357. return _.diag(SPV_ERROR_INVALID_ID, inst)
  358. << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
  359. << "' is not a constant or module-scope variable.";
  360. }
  361. }
  362. const auto storage_class =
  363. inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  364. if (storage_class != SpvStorageClassWorkgroup &&
  365. storage_class != SpvStorageClassCrossWorkgroup &&
  366. storage_class != SpvStorageClassPrivate &&
  367. storage_class != SpvStorageClassFunction &&
  368. storage_class != SpvStorageClassRayPayloadNV &&
  369. storage_class != SpvStorageClassIncomingRayPayloadNV &&
  370. storage_class != SpvStorageClassHitAttributeNV &&
  371. storage_class != SpvStorageClassCallableDataNV &&
  372. storage_class != SpvStorageClassIncomingCallableDataNV) {
  373. const auto storage_index = 2;
  374. const auto storage_id = result_type->GetOperandAs<uint32_t>(storage_index);
  375. const auto storage = _.FindDef(storage_id);
  376. bool storage_input_or_output = storage_class == SpvStorageClassInput ||
  377. storage_class == SpvStorageClassOutput;
  378. bool builtin = false;
  379. if (storage_input_or_output) {
  380. for (const Decoration& decoration : _.id_decorations(inst->id())) {
  381. if (decoration.dec_type() == SpvDecorationBuiltIn) {
  382. builtin = true;
  383. break;
  384. }
  385. }
  386. }
  387. if (!(storage_input_or_output && builtin) &&
  388. ContainsInvalidBool(_, storage, storage_input_or_output)) {
  389. return _.diag(SPV_ERROR_INVALID_ID, inst)
  390. << "If OpTypeBool is stored in conjunction with OpVariable, it "
  391. << "can only be used with non-externally visible shader Storage "
  392. << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
  393. }
  394. }
  395. // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  396. // storage class.
  397. const auto result_storage_class_index = 1;
  398. const auto result_storage_class =
  399. result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  400. if (storage_class != result_storage_class) {
  401. return _.diag(SPV_ERROR_INVALID_ID, inst)
  402. << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
  403. << "Its Storage Class operand must be the same as the Storage Class "
  404. << "operand of the result type.";
  405. }
  406. // Variable pointer related restrictions.
  407. const auto pointee = _.FindDef(result_type->word(3));
  408. if (_.addressing_model() == SpvAddressingModelLogical &&
  409. !_.options()->relax_logical_pointer) {
  410. // VariablePointersStorageBuffer is implied by VariablePointers.
  411. if (pointee->opcode() == SpvOpTypePointer) {
  412. if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
  413. return _.diag(SPV_ERROR_INVALID_ID, inst)
  414. << "In Logical addressing, variables may not allocate a pointer "
  415. << "type";
  416. } else if (storage_class != SpvStorageClassFunction &&
  417. storage_class != SpvStorageClassPrivate) {
  418. return _.diag(SPV_ERROR_INVALID_ID, inst)
  419. << "In Logical addressing with variable pointers, variables "
  420. << "that allocate pointers must be in Function or Private "
  421. << "storage classes";
  422. }
  423. }
  424. }
  425. // Vulkan 14.5.1: Check type of PushConstant variables.
  426. // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  427. if (spvIsVulkanEnv(_.context()->target_env)) {
  428. if (storage_class == SpvStorageClassPushConstant) {
  429. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  430. return _.diag(SPV_ERROR_INVALID_ID, inst)
  431. << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
  432. << "' has illegal type.\n"
  433. << "From Vulkan spec, section 14.5.1:\n"
  434. << "Such variables must be typed as OpTypeStruct, "
  435. << "or an array of this type";
  436. }
  437. }
  438. if (storage_class == SpvStorageClassUniformConstant) {
  439. if (!IsAllowedTypeOrArrayOfSame(
  440. _, pointee,
  441. {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
  442. SpvOpTypeAccelerationStructureNV})) {
  443. return _.diag(SPV_ERROR_INVALID_ID, inst)
  444. << "UniformConstant OpVariable <id> '" << _.getIdName(inst->id())
  445. << "' has illegal type.\n"
  446. << "From Vulkan spec, section 14.5.2:\n"
  447. << "Variables identified with the UniformConstant storage class "
  448. << "are used only as handles to refer to opaque resources. Such "
  449. << "variables must be typed as OpTypeImage, OpTypeSampler, "
  450. << "OpTypeSampledImage, OpTypeAccelerationStructureNV, "
  451. << "or an array of one of these types.";
  452. }
  453. }
  454. if (storage_class == SpvStorageClassUniform) {
  455. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  456. return _.diag(SPV_ERROR_INVALID_ID, inst)
  457. << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
  458. << "' has illegal type.\n"
  459. << "From Vulkan spec, section 14.5.2:\n"
  460. << "Variables identified with the Uniform storage class are "
  461. << "used to access transparent buffer backed resources. Such "
  462. << "variables must be typed as OpTypeStruct, or an array of "
  463. << "this type";
  464. }
  465. }
  466. }
  467. // WebGPU & Vulkan Appendix A: Check that if contains initializer, then
  468. // storage class is Output, Private, or Function.
  469. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
  470. storage_class != SpvStorageClassPrivate &&
  471. storage_class != SpvStorageClassFunction) {
  472. if (spvIsVulkanEnv(_.context()->target_env)) {
  473. return _.diag(SPV_ERROR_INVALID_ID, inst)
  474. << "OpVariable, <id> '" << _.getIdName(inst->id())
  475. << "', has a disallowed initializer & storage class "
  476. << "combination.\n"
  477. << "From Vulkan spec, Appendix A:\n"
  478. << "Variable declarations that include initializers must have "
  479. << "one of the following storage classes: Output, Private, or "
  480. << "Function";
  481. }
  482. if (spvIsWebGPUEnv(_.context()->target_env)) {
  483. return _.diag(SPV_ERROR_INVALID_ID, inst)
  484. << "OpVariable, <id> '" << _.getIdName(inst->id())
  485. << "', has a disallowed initializer & storage class "
  486. << "combination.\n"
  487. << "From WebGPU execution environment spec:\n"
  488. << "Variable declarations that include initializers must have "
  489. << "one of the following storage classes: Output, Private, or "
  490. << "Function";
  491. }
  492. }
  493. // WebGPU: All variables with storage class Output, Private, or Function MUST
  494. // have an initializer.
  495. if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 &&
  496. (storage_class == SpvStorageClassOutput ||
  497. storage_class == SpvStorageClassPrivate ||
  498. storage_class == SpvStorageClassFunction)) {
  499. return _.diag(SPV_ERROR_INVALID_ID, inst)
  500. << "OpVariable, <id> '" << _.getIdName(inst->id())
  501. << "', must have an initializer.\n"
  502. << "From WebGPU execution environment spec:\n"
  503. << "All variables in the following storage classes must have an "
  504. << "initializer: Output, Private, or Function";
  505. }
  506. if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
  507. return _.diag(SPV_ERROR_INVALID_ID, inst)
  508. << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  509. }
  510. auto pointee_base = pointee;
  511. while (pointee_base->opcode() == SpvOpTypeArray) {
  512. pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  513. }
  514. if (pointee_base->opcode() == SpvOpTypePointer) {
  515. if (pointee_base->GetOperandAs<uint32_t>(1u) ==
  516. SpvStorageClassPhysicalStorageBufferEXT) {
  517. // check for AliasedPointerEXT/RestrictPointerEXT
  518. bool foundAliased =
  519. _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
  520. bool foundRestrict =
  521. _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
  522. if (!foundAliased && !foundRestrict) {
  523. return _.diag(SPV_ERROR_INVALID_ID, inst)
  524. << "OpVariable " << inst->id()
  525. << ": expected AliasedPointerEXT or RestrictPointerEXT for "
  526. << "PhysicalStorageBufferEXT pointer.";
  527. }
  528. if (foundAliased && foundRestrict) {
  529. return _.diag(SPV_ERROR_INVALID_ID, inst)
  530. << "OpVariable " << inst->id()
  531. << ": can't specify both AliasedPointerEXT and "
  532. << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
  533. }
  534. }
  535. }
  536. // Vulkan specific validation rules for OpTypeRuntimeArray
  537. if (spvIsVulkanEnv(_.context()->target_env)) {
  538. const auto type_index = 2;
  539. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  540. auto value_type = _.FindDef(value_id);
  541. // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
  542. // so should never appear as a bare variable.
  543. // Unless the module has the RuntimeDescriptorArrayEXT capability.
  544. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  545. if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
  546. return _.diag(SPV_ERROR_INVALID_ID, inst)
  547. << "OpVariable, <id> '" << _.getIdName(inst->id())
  548. << "', is attempting to create memory for an illegal type, "
  549. << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
  550. << "appear as the final member of an OpTypeStruct, thus cannot "
  551. << "be instantiated via OpVariable";
  552. } else {
  553. // A bare variable OpTypeRuntimeArray is allowed in this context, but
  554. // still need to check the storage class.
  555. if (storage_class != SpvStorageClassStorageBuffer &&
  556. storage_class != SpvStorageClassUniform &&
  557. storage_class != SpvStorageClassUniformConstant) {
  558. return _.diag(SPV_ERROR_INVALID_ID, inst)
  559. << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
  560. << "containing OpTypeRuntimeArray must have storage class of "
  561. << "StorageBuffer, Uniform, or UniformConstant.";
  562. }
  563. }
  564. }
  565. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  566. // must either have the storage class StorageBuffer and be decorated
  567. // with Block, or it must be in the Uniform storage class and be decorated
  568. // as BufferBlock.
  569. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  570. if (DoesStructContainRTA(_, value_type)) {
  571. if (storage_class == SpvStorageClassStorageBuffer) {
  572. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  573. return _.diag(SPV_ERROR_INVALID_ID, inst)
  574. << "For Vulkan, an OpTypeStruct variable containing an "
  575. << "OpTypeRuntimeArray must be decorated with Block if it "
  576. << "has storage class StorageBuffer.";
  577. }
  578. } else if (storage_class == SpvStorageClassUniform) {
  579. if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
  580. return _.diag(SPV_ERROR_INVALID_ID, inst)
  581. << "For Vulkan, an OpTypeStruct variable containing an "
  582. << "OpTypeRuntimeArray must be decorated with BufferBlock "
  583. << "if it has storage class Uniform.";
  584. }
  585. } else {
  586. return _.diag(SPV_ERROR_INVALID_ID, inst)
  587. << "For Vulkan, OpTypeStruct variables containing "
  588. << "OpTypeRuntimeArray must have storage class of "
  589. << "StorageBuffer or Uniform.";
  590. }
  591. }
  592. }
  593. }
  594. // WebGPU specific validation rules for OpTypeRuntimeArray
  595. if (spvIsWebGPUEnv(_.context()->target_env)) {
  596. const auto type_index = 2;
  597. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  598. auto value_type = _.FindDef(value_id);
  599. // OpTypeRuntimeArray should only ever be in an OpTypeStruct,
  600. // so should never appear as a bare variable.
  601. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  602. return _.diag(SPV_ERROR_INVALID_ID, inst)
  603. << "OpVariable, <id> '" << _.getIdName(inst->id())
  604. << "', is attempting to create memory for an illegal type, "
  605. << "OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray can only "
  606. << "appear as the final member of an OpTypeStruct, thus cannot "
  607. << "be instantiated via OpVariable";
  608. }
  609. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  610. // must have the storage class StorageBuffer and be decorated
  611. // with Block.
  612. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  613. if (DoesStructContainRTA(_, value_type)) {
  614. if (storage_class == SpvStorageClassStorageBuffer) {
  615. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  616. return _.diag(SPV_ERROR_INVALID_ID, inst)
  617. << "For WebGPU, an OpTypeStruct variable containing an "
  618. << "OpTypeRuntimeArray must be decorated with Block if it "
  619. << "has storage class StorageBuffer.";
  620. }
  621. } else {
  622. return _.diag(SPV_ERROR_INVALID_ID, inst)
  623. << "For WebGPU, OpTypeStruct variables containing "
  624. << "OpTypeRuntimeArray must have storage class of "
  625. << "StorageBuffer";
  626. }
  627. }
  628. }
  629. }
  630. return SPV_SUCCESS;
  631. }
  632. spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  633. const auto result_type = _.FindDef(inst->type_id());
  634. if (!result_type) {
  635. return _.diag(SPV_ERROR_INVALID_ID, inst)
  636. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  637. << "' is not defined.";
  638. }
  639. const bool uses_variable_pointers =
  640. _.features().variable_pointers ||
  641. _.features().variable_pointers_storage_buffer;
  642. const auto pointer_index = 2;
  643. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  644. const auto pointer = _.FindDef(pointer_id);
  645. if (!pointer ||
  646. ((_.addressing_model() == SpvAddressingModelLogical) &&
  647. ((!uses_variable_pointers &&
  648. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  649. (uses_variable_pointers &&
  650. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  651. return _.diag(SPV_ERROR_INVALID_ID, inst)
  652. << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
  653. << "' is not a logical pointer.";
  654. }
  655. const auto pointer_type = _.FindDef(pointer->type_id());
  656. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  657. return _.diag(SPV_ERROR_INVALID_ID, inst)
  658. << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
  659. << "' is not a pointer type.";
  660. }
  661. const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  662. if (!pointee_type || result_type->id() != pointee_type->id()) {
  663. return _.diag(SPV_ERROR_INVALID_ID, inst)
  664. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  665. << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
  666. << "'s type.";
  667. }
  668. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  669. return SPV_SUCCESS;
  670. }
  671. spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
  672. const bool uses_variable_pointer =
  673. _.features().variable_pointers ||
  674. _.features().variable_pointers_storage_buffer;
  675. const auto pointer_index = 0;
  676. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  677. const auto pointer = _.FindDef(pointer_id);
  678. if (!pointer ||
  679. (_.addressing_model() == SpvAddressingModelLogical &&
  680. ((!uses_variable_pointer &&
  681. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  682. (uses_variable_pointer &&
  683. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  684. return _.diag(SPV_ERROR_INVALID_ID, inst)
  685. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  686. << "' is not a logical pointer.";
  687. }
  688. const auto pointer_type = _.FindDef(pointer->type_id());
  689. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  690. return _.diag(SPV_ERROR_INVALID_ID, inst)
  691. << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
  692. << "' is not a pointer type.";
  693. }
  694. const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
  695. const auto type = _.FindDef(type_id);
  696. if (!type || SpvOpTypeVoid == type->opcode()) {
  697. return _.diag(SPV_ERROR_INVALID_ID, inst)
  698. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  699. << "'s type is void.";
  700. }
  701. // validate storage class
  702. {
  703. uint32_t data_type;
  704. uint32_t storage_class;
  705. if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
  706. return _.diag(SPV_ERROR_INVALID_ID, inst)
  707. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  708. << "' is not pointer type";
  709. }
  710. if (storage_class == SpvStorageClassUniformConstant ||
  711. storage_class == SpvStorageClassInput ||
  712. storage_class == SpvStorageClassPushConstant) {
  713. return _.diag(SPV_ERROR_INVALID_ID, inst)
  714. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  715. << "' storage class is read-only";
  716. }
  717. }
  718. const auto object_index = 1;
  719. const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
  720. const auto object = _.FindDef(object_id);
  721. if (!object || !object->type_id()) {
  722. return _.diag(SPV_ERROR_INVALID_ID, inst)
  723. << "OpStore Object <id> '" << _.getIdName(object_id)
  724. << "' is not an object.";
  725. }
  726. const auto object_type = _.FindDef(object->type_id());
  727. if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
  728. return _.diag(SPV_ERROR_INVALID_ID, inst)
  729. << "OpStore Object <id> '" << _.getIdName(object_id)
  730. << "'s type is void.";
  731. }
  732. if (type->id() != object_type->id()) {
  733. if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
  734. object_type->opcode() != SpvOpTypeStruct) {
  735. return _.diag(SPV_ERROR_INVALID_ID, inst)
  736. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  737. << "'s type does not match Object <id> '"
  738. << _.getIdName(object->id()) << "'s type.";
  739. }
  740. // TODO: Check for layout compatible matricies and arrays as well.
  741. if (!AreLayoutCompatibleStructs(_, type, object_type)) {
  742. return _.diag(SPV_ERROR_INVALID_ID, inst)
  743. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  744. << "'s layout does not match Object <id> '"
  745. << _.getIdName(object->id()) << "'s layout.";
  746. }
  747. }
  748. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  749. return SPV_SUCCESS;
  750. }
  751. spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
  752. const auto target_index = 0;
  753. const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
  754. const auto target = _.FindDef(target_id);
  755. if (!target) {
  756. return _.diag(SPV_ERROR_INVALID_ID, inst)
  757. << "Target operand <id> '" << _.getIdName(target_id)
  758. << "' is not defined.";
  759. }
  760. const auto source_index = 1;
  761. const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
  762. const auto source = _.FindDef(source_id);
  763. if (!source) {
  764. return _.diag(SPV_ERROR_INVALID_ID, inst)
  765. << "Source operand <id> '" << _.getIdName(source_id)
  766. << "' is not defined.";
  767. }
  768. const auto target_pointer_type = _.FindDef(target->type_id());
  769. if (!target_pointer_type ||
  770. target_pointer_type->opcode() != SpvOpTypePointer) {
  771. return _.diag(SPV_ERROR_INVALID_ID, inst)
  772. << "Target operand <id> '" << _.getIdName(target_id)
  773. << "' is not a pointer.";
  774. }
  775. const auto source_pointer_type = _.FindDef(source->type_id());
  776. if (!source_pointer_type ||
  777. source_pointer_type->opcode() != SpvOpTypePointer) {
  778. return _.diag(SPV_ERROR_INVALID_ID, inst)
  779. << "Source operand <id> '" << _.getIdName(source_id)
  780. << "' is not a pointer.";
  781. }
  782. if (inst->opcode() == SpvOpCopyMemory) {
  783. const auto target_type =
  784. _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  785. if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
  786. return _.diag(SPV_ERROR_INVALID_ID, inst)
  787. << "Target operand <id> '" << _.getIdName(target_id)
  788. << "' cannot be a void pointer.";
  789. }
  790. const auto source_type =
  791. _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
  792. if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
  793. return _.diag(SPV_ERROR_INVALID_ID, inst)
  794. << "Source operand <id> '" << _.getIdName(source_id)
  795. << "' cannot be a void pointer.";
  796. }
  797. if (target_type->id() != source_type->id()) {
  798. return _.diag(SPV_ERROR_INVALID_ID, inst)
  799. << "Target <id> '" << _.getIdName(source_id)
  800. << "'s type does not match Source <id> '"
  801. << _.getIdName(source_type->id()) << "'s type.";
  802. }
  803. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  804. } else {
  805. const auto size_id = inst->GetOperandAs<uint32_t>(2);
  806. const auto size = _.FindDef(size_id);
  807. if (!size) {
  808. return _.diag(SPV_ERROR_INVALID_ID, inst)
  809. << "Size operand <id> '" << _.getIdName(size_id)
  810. << "' is not defined.";
  811. }
  812. const auto size_type = _.FindDef(size->type_id());
  813. if (!_.IsIntScalarType(size_type->id())) {
  814. return _.diag(SPV_ERROR_INVALID_ID, inst)
  815. << "Size operand <id> '" << _.getIdName(size_id)
  816. << "' must be a scalar integer type.";
  817. }
  818. bool is_zero = true;
  819. switch (size->opcode()) {
  820. case SpvOpConstantNull:
  821. return _.diag(SPV_ERROR_INVALID_ID, inst)
  822. << "Size operand <id> '" << _.getIdName(size_id)
  823. << "' cannot be a constant zero.";
  824. case SpvOpConstant:
  825. if (size_type->word(3) == 1 &&
  826. size->word(size->words().size() - 1) & 0x80000000) {
  827. return _.diag(SPV_ERROR_INVALID_ID, inst)
  828. << "Size operand <id> '" << _.getIdName(size_id)
  829. << "' cannot have the sign bit set to 1.";
  830. }
  831. for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
  832. is_zero &= (size->word(i) == 0);
  833. }
  834. if (is_zero) {
  835. return _.diag(SPV_ERROR_INVALID_ID, inst)
  836. << "Size operand <id> '" << _.getIdName(size_id)
  837. << "' cannot be a constant zero.";
  838. }
  839. break;
  840. default:
  841. // Cannot infer any other opcodes.
  842. break;
  843. }
  844. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  845. }
  846. return SPV_SUCCESS;
  847. }
  848. spv_result_t ValidateAccessChain(ValidationState_t& _,
  849. const Instruction* inst) {
  850. std::string instr_name =
  851. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  852. // The result type must be OpTypePointer.
  853. auto result_type = _.FindDef(inst->type_id());
  854. if (SpvOpTypePointer != result_type->opcode()) {
  855. return _.diag(SPV_ERROR_INVALID_ID, inst)
  856. << "The Result Type of " << instr_name << " <id> '"
  857. << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
  858. << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
  859. }
  860. // Result type is a pointer. Find out what it's pointing to.
  861. // This will be used to make sure the indexing results in the same type.
  862. // OpTypePointer word 3 is the type being pointed to.
  863. const auto result_type_pointee = _.FindDef(result_type->word(3));
  864. // Base must be a pointer, pointing to the base of a composite object.
  865. const auto base_index = 2;
  866. const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
  867. const auto base = _.FindDef(base_id);
  868. const auto base_type = _.FindDef(base->type_id());
  869. if (!base_type || SpvOpTypePointer != base_type->opcode()) {
  870. return _.diag(SPV_ERROR_INVALID_ID, inst)
  871. << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
  872. << " instruction must be a pointer.";
  873. }
  874. // The result pointer storage class and base pointer storage class must match.
  875. // Word 2 of OpTypePointer is the Storage Class.
  876. auto result_type_storage_class = result_type->word(2);
  877. auto base_type_storage_class = base_type->word(2);
  878. if (result_type_storage_class != base_type_storage_class) {
  879. return _.diag(SPV_ERROR_INVALID_ID, inst)
  880. << "The result pointer storage class and base "
  881. "pointer storage class in "
  882. << instr_name << " do not match.";
  883. }
  884. // The type pointed to by OpTypePointer (word 3) must be a composite type.
  885. auto type_pointee = _.FindDef(base_type->word(3));
  886. // Check Universal Limit (SPIR-V Spec. Section 2.17).
  887. // The number of indexes passed to OpAccessChain may not exceed 255
  888. // The instruction includes 4 words + N words (for N indexes)
  889. size_t num_indexes = inst->words().size() - 4;
  890. if (inst->opcode() == SpvOpPtrAccessChain ||
  891. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  892. // In pointer access chains, the element operand is required, but not
  893. // counted as an index.
  894. --num_indexes;
  895. }
  896. const size_t num_indexes_limit =
  897. _.options()->universal_limits_.max_access_chain_indexes;
  898. if (num_indexes > num_indexes_limit) {
  899. return _.diag(SPV_ERROR_INVALID_ID, inst)
  900. << "The number of indexes in " << instr_name << " may not exceed "
  901. << num_indexes_limit << ". Found " << num_indexes << " indexes.";
  902. }
  903. // Indexes walk the type hierarchy to the desired depth, potentially down to
  904. // scalar granularity. The first index in Indexes will select the top-level
  905. // member/element/component/element of the base composite. All composite
  906. // constituents use zero-based numbering, as described by their OpType...
  907. // instruction. The second index will apply similarly to that result, and so
  908. // on. Once any non-composite type is reached, there must be no remaining
  909. // (unused) indexes.
  910. auto starting_index = 4;
  911. if (inst->opcode() == SpvOpPtrAccessChain ||
  912. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  913. ++starting_index;
  914. }
  915. for (size_t i = starting_index; i < inst->words().size(); ++i) {
  916. const uint32_t cur_word = inst->words()[i];
  917. // Earlier ID checks ensure that cur_word definition exists.
  918. auto cur_word_instr = _.FindDef(cur_word);
  919. // The index must be a scalar integer type (See OpAccessChain in the Spec.)
  920. auto index_type = _.FindDef(cur_word_instr->type_id());
  921. if (!index_type || SpvOpTypeInt != index_type->opcode()) {
  922. return _.diag(SPV_ERROR_INVALID_ID, inst)
  923. << "Indexes passed to " << instr_name
  924. << " must be of type integer.";
  925. }
  926. switch (type_pointee->opcode()) {
  927. case SpvOpTypeMatrix:
  928. case SpvOpTypeVector:
  929. case SpvOpTypeArray:
  930. case SpvOpTypeRuntimeArray: {
  931. // In OpTypeMatrix, OpTypeVector, OpTypeArray, and OpTypeRuntimeArray,
  932. // word 2 is the Element Type.
  933. type_pointee = _.FindDef(type_pointee->word(2));
  934. break;
  935. }
  936. case SpvOpTypeStruct: {
  937. // In case of structures, there is an additional constraint on the
  938. // index: the index must be an OpConstant.
  939. if (SpvOpConstant != cur_word_instr->opcode()) {
  940. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  941. << "The <id> passed to " << instr_name
  942. << " to index into a "
  943. "structure must be an OpConstant.";
  944. }
  945. // Get the index value from the OpConstant (word 3 of OpConstant).
  946. // OpConstant could be a signed integer. But it's okay to treat it as
  947. // unsigned because a negative constant int would never be seen as
  948. // correct as a struct offset, since structs can't have more than 2
  949. // billion members.
  950. const uint32_t cur_index = cur_word_instr->word(3);
  951. // The index points to the struct member we want, therefore, the index
  952. // should be less than the number of struct members.
  953. const uint32_t num_struct_members =
  954. static_cast<uint32_t>(type_pointee->words().size() - 2);
  955. if (cur_index >= num_struct_members) {
  956. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  957. << "Index is out of bounds: " << instr_name
  958. << " can not find index " << cur_index
  959. << " into the structure <id> '"
  960. << _.getIdName(type_pointee->id()) << "'. This structure has "
  961. << num_struct_members << " members. Largest valid index is "
  962. << num_struct_members - 1 << ".";
  963. }
  964. // Struct members IDs start at word 2 of OpTypeStruct.
  965. auto structMemberId = type_pointee->word(cur_index + 2);
  966. type_pointee = _.FindDef(structMemberId);
  967. break;
  968. }
  969. default: {
  970. // Give an error. reached non-composite type while indexes still remain.
  971. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  972. << instr_name
  973. << " reached non-composite type while indexes "
  974. "still remain to be traversed.";
  975. }
  976. }
  977. }
  978. // At this point, we have fully walked down from the base using the indeces.
  979. // The type being pointed to should be the same as the result type.
  980. if (type_pointee->id() != result_type_pointee->id()) {
  981. return _.diag(SPV_ERROR_INVALID_ID, inst)
  982. << instr_name << " result type (Op"
  983. << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
  984. << ") does not match the type that results from indexing into the "
  985. "base "
  986. "<id> (Op"
  987. << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
  988. << ").";
  989. }
  990. return SPV_SUCCESS;
  991. }
  992. spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
  993. const Instruction* inst) {
  994. if (_.addressing_model() == SpvAddressingModelLogical) {
  995. if (!_.features().variable_pointers &&
  996. !_.features().variable_pointers_storage_buffer) {
  997. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  998. << "Generating variable pointers requires capability "
  999. << "VariablePointers or VariablePointersStorageBuffer";
  1000. }
  1001. }
  1002. return ValidateAccessChain(_, inst);
  1003. }
  1004. spv_result_t ValidateArrayLength(ValidationState_t& state,
  1005. const Instruction* inst) {
  1006. std::string instr_name =
  1007. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1008. // Result type must be a 32-bit unsigned int.
  1009. auto result_type = state.FindDef(inst->type_id());
  1010. if (result_type->opcode() != SpvOpTypeInt ||
  1011. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1012. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1013. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1014. << "The Result Type of " << instr_name << " <id> '"
  1015. << state.getIdName(inst->id())
  1016. << "' must be OpTypeInt with width 32 and signedness 0.";
  1017. }
  1018. // The structure that is passed in must be an pointer to a structure, whose
  1019. // last element is a runtime array.
  1020. auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
  1021. auto pointer_type = state.FindDef(pointer->type_id());
  1022. if (pointer_type->opcode() != SpvOpTypePointer) {
  1023. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1024. << "The Struture's type in " << instr_name << " <id> '"
  1025. << state.getIdName(inst->id())
  1026. << "' must be a pointer to an OpTypeStruct.";
  1027. }
  1028. auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  1029. if (structure_type->opcode() != SpvOpTypeStruct) {
  1030. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1031. << "The Struture's type in " << instr_name << " <id> '"
  1032. << state.getIdName(inst->id())
  1033. << "' must be a pointer to an OpTypeStruct.";
  1034. }
  1035. auto num_of_members = structure_type->operands().size() - 1;
  1036. auto last_member =
  1037. state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
  1038. if (last_member->opcode() != SpvOpTypeRuntimeArray) {
  1039. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1040. << "The Struture's last member in " << instr_name << " <id> '"
  1041. << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
  1042. }
  1043. // The array member must the the index of the last element (the run time
  1044. // array).
  1045. if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
  1046. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1047. << "The array member in " << instr_name << " <id> '"
  1048. << state.getIdName(inst->id())
  1049. << "' must be an the last member of the struct.";
  1050. }
  1051. return SPV_SUCCESS;
  1052. }
  1053. } // namespace
  1054. spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
  1055. switch (inst->opcode()) {
  1056. case SpvOpVariable:
  1057. if (auto error = ValidateVariable(_, inst)) return error;
  1058. break;
  1059. case SpvOpLoad:
  1060. if (auto error = ValidateLoad(_, inst)) return error;
  1061. break;
  1062. case SpvOpStore:
  1063. if (auto error = ValidateStore(_, inst)) return error;
  1064. break;
  1065. case SpvOpCopyMemory:
  1066. case SpvOpCopyMemorySized:
  1067. if (auto error = ValidateCopyMemory(_, inst)) return error;
  1068. break;
  1069. case SpvOpPtrAccessChain:
  1070. if (auto error = ValidatePtrAccessChain(_, inst)) return error;
  1071. break;
  1072. case SpvOpAccessChain:
  1073. case SpvOpInBoundsAccessChain:
  1074. case SpvOpInBoundsPtrAccessChain:
  1075. if (auto error = ValidateAccessChain(_, inst)) return error;
  1076. break;
  1077. case SpvOpArrayLength:
  1078. if (auto error = ValidateArrayLength(_, inst)) return error;
  1079. break;
  1080. case SpvOpImageTexelPointer:
  1081. case SpvOpGenericPtrMemSemantics:
  1082. default:
  1083. break;
  1084. }
  1085. return SPV_SUCCESS;
  1086. }
  1087. } // namespace val
  1088. } // namespace spvtools