validate_memory.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. // Copyright (c) 2018 Google LLC.
  2. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
  3. // reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. #include <algorithm>
  17. #include <string>
  18. #include <vector>
  19. #include "source/opcode.h"
  20. #include "source/spirv_target_env.h"
  21. #include "source/val/instruction.h"
  22. #include "source/val/validate.h"
  23. #include "source/val/validate_scopes.h"
  24. #include "source/val/validation_state.h"
  25. namespace spvtools {
  26. namespace val {
  27. namespace {
  28. bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
  29. const Instruction*);
  30. bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
  31. const Instruction*);
  32. bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
  33. const Instruction*);
  34. bool HasConflictingMemberOffsets(const std::vector<Decoration>&,
  35. const std::vector<Decoration>&);
  36. bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction* type,
  37. std::initializer_list<uint32_t> allowed) {
  38. if (std::find(allowed.begin(), allowed.end(), type->opcode()) !=
  39. allowed.end()) {
  40. return true;
  41. }
  42. if (type->opcode() == SpvOpTypeArray ||
  43. type->opcode() == SpvOpTypeRuntimeArray) {
  44. auto elem_type = _.FindDef(type->word(2));
  45. return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
  46. allowed.end();
  47. }
  48. return false;
  49. }
  50. // Returns true if the two instructions represent structs that, as far as the
  51. // validator can tell, have the exact same data layout.
  52. bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
  53. const Instruction* type2) {
  54. if (type1->opcode() != SpvOpTypeStruct) {
  55. return false;
  56. }
  57. if (type2->opcode() != SpvOpTypeStruct) {
  58. return false;
  59. }
  60. if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
  61. return HaveSameLayoutDecorations(_, type1, type2);
  62. }
  63. // Returns true if the operands to the OpTypeStruct instruction defining the
  64. // types are the same or are layout compatible types. |type1| and |type2| must
  65. // be OpTypeStruct instructions.
  66. bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
  67. const Instruction* type2) {
  68. assert(type1->opcode() == SpvOpTypeStruct &&
  69. "type1 must be an OpTypeStruct instruction.");
  70. assert(type2->opcode() == SpvOpTypeStruct &&
  71. "type2 must be an OpTypeStruct instruction.");
  72. const auto& type1_operands = type1->operands();
  73. const auto& type2_operands = type2->operands();
  74. if (type1_operands.size() != type2_operands.size()) {
  75. return false;
  76. }
  77. for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
  78. if (type1->word(operand) != type2->word(operand)) {
  79. auto def1 = _.FindDef(type1->word(operand));
  80. auto def2 = _.FindDef(type2->word(operand));
  81. if (!AreLayoutCompatibleStructs(_, def1, def2)) {
  82. return false;
  83. }
  84. }
  85. }
  86. return true;
  87. }
  88. // Returns true if all decorations that affect the data layout of the struct
  89. // (like Offset), are the same for the two types. |type1| and |type2| must be
  90. // OpTypeStruct instructions.
  91. bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
  92. const Instruction* type2) {
  93. assert(type1->opcode() == SpvOpTypeStruct &&
  94. "type1 must be an OpTypeStruct instruction.");
  95. assert(type2->opcode() == SpvOpTypeStruct &&
  96. "type2 must be an OpTypeStruct instruction.");
  97. const std::vector<Decoration>& type1_decorations =
  98. _.id_decorations(type1->id());
  99. const std::vector<Decoration>& type2_decorations =
  100. _.id_decorations(type2->id());
  101. // TODO: Will have to add other check for arrays an matricies if we want to
  102. // handle them.
  103. if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
  104. return false;
  105. }
  106. return true;
  107. }
  108. bool HasConflictingMemberOffsets(
  109. const std::vector<Decoration>& type1_decorations,
  110. const std::vector<Decoration>& type2_decorations) {
  111. {
  112. // We are interested in conflicting decoration. If a decoration is in one
  113. // list but not the other, then we will assume the code is correct. We are
  114. // looking for things we know to be wrong.
  115. //
  116. // We do not have to traverse type2_decoration because, after traversing
  117. // type1_decorations, anything new will not be found in
  118. // type1_decoration. Therefore, it cannot lead to a conflict.
  119. for (const Decoration& decoration : type1_decorations) {
  120. switch (decoration.dec_type()) {
  121. case SpvDecorationOffset: {
  122. // Since these affect the layout of the struct, they must be present
  123. // in both structs.
  124. auto compare = [&decoration](const Decoration& rhs) {
  125. if (rhs.dec_type() != SpvDecorationOffset) return false;
  126. return decoration.struct_member_index() ==
  127. rhs.struct_member_index();
  128. };
  129. auto i = std::find_if(type2_decorations.begin(),
  130. type2_decorations.end(), compare);
  131. if (i != type2_decorations.end() &&
  132. decoration.params().front() != i->params().front()) {
  133. return true;
  134. }
  135. } break;
  136. default:
  137. // This decoration does not affect the layout of the structure, so
  138. // just moving on.
  139. break;
  140. }
  141. }
  142. }
  143. return false;
  144. }
  145. // If |skip_builtin| is true, returns true if |storage| contains bool within
  146. // it and no storage that contains the bool is builtin.
  147. // If |skip_builtin| is false, returns true if |storage| contains bool within
  148. // it.
  149. bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
  150. bool skip_builtin) {
  151. if (skip_builtin) {
  152. for (const Decoration& decoration : _.id_decorations(storage->id())) {
  153. if (decoration.dec_type() == SpvDecorationBuiltIn) return false;
  154. }
  155. }
  156. const size_t elem_type_index = 1;
  157. uint32_t elem_type_id;
  158. Instruction* elem_type;
  159. switch (storage->opcode()) {
  160. case SpvOpTypeBool:
  161. return true;
  162. case SpvOpTypeVector:
  163. case SpvOpTypeMatrix:
  164. case SpvOpTypeArray:
  165. case SpvOpTypeRuntimeArray:
  166. elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
  167. elem_type = _.FindDef(elem_type_id);
  168. return ContainsInvalidBool(_, elem_type, skip_builtin);
  169. case SpvOpTypeStruct:
  170. for (size_t member_type_index = 1;
  171. member_type_index < storage->operands().size();
  172. ++member_type_index) {
  173. auto member_type_id =
  174. storage->GetOperandAs<uint32_t>(member_type_index);
  175. auto member_type = _.FindDef(member_type_id);
  176. if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
  177. }
  178. default:
  179. break;
  180. }
  181. return false;
  182. }
  183. bool ContainsCooperativeMatrix(ValidationState_t& _,
  184. const Instruction* storage) {
  185. const size_t elem_type_index = 1;
  186. uint32_t elem_type_id;
  187. Instruction* elem_type;
  188. switch (storage->opcode()) {
  189. case SpvOpTypeCooperativeMatrixNV:
  190. return true;
  191. case SpvOpTypeArray:
  192. case SpvOpTypeRuntimeArray:
  193. elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
  194. elem_type = _.FindDef(elem_type_id);
  195. return ContainsCooperativeMatrix(_, elem_type);
  196. case SpvOpTypeStruct:
  197. for (size_t member_type_index = 1;
  198. member_type_index < storage->operands().size();
  199. ++member_type_index) {
  200. auto member_type_id =
  201. storage->GetOperandAs<uint32_t>(member_type_index);
  202. auto member_type = _.FindDef(member_type_id);
  203. if (ContainsCooperativeMatrix(_, member_type)) return true;
  204. }
  205. break;
  206. default:
  207. break;
  208. }
  209. return false;
  210. }
  211. std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
  212. ValidationState_t& _, const Instruction* inst) {
  213. SpvStorageClass dst_sc = SpvStorageClassMax;
  214. SpvStorageClass src_sc = SpvStorageClassMax;
  215. switch (inst->opcode()) {
  216. case SpvOpCooperativeMatrixLoadNV:
  217. case SpvOpLoad: {
  218. auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
  219. auto load_pointer_type = _.FindDef(load_pointer->type_id());
  220. dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
  221. break;
  222. }
  223. case SpvOpCooperativeMatrixStoreNV:
  224. case SpvOpStore: {
  225. auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  226. auto store_pointer_type = _.FindDef(store_pointer->type_id());
  227. dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
  228. break;
  229. }
  230. case SpvOpCopyMemory:
  231. case SpvOpCopyMemorySized: {
  232. auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  233. auto dst_type = _.FindDef(dst->type_id());
  234. dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
  235. auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
  236. auto src_type = _.FindDef(src->type_id());
  237. src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
  238. break;
  239. }
  240. default:
  241. break;
  242. }
  243. return std::make_pair(dst_sc, src_sc);
  244. }
  245. // Returns the number of instruction words taken up by a memory access
  246. // argument and its implied operands.
  247. int MemoryAccessNumWords(uint32_t mask) {
  248. int result = 1; // Count the mask
  249. if (mask & SpvMemoryAccessAlignedMask) ++result;
  250. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++result;
  251. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) ++result;
  252. return result;
  253. }
  254. // Returns the scope ID operand for MakeAvailable memory access with mask
  255. // at the given operand index.
  256. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  257. // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
  258. // OpCooperativeMatrixStoreNV.
  259. uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
  260. uint32_t mask_index) {
  261. assert(mask & SpvMemoryAccessMakePointerAvailableKHRMask);
  262. uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerAvailableKHRMask);
  263. uint32_t index =
  264. mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  265. return inst->GetOperandAs<uint32_t>(index);
  266. }
  267. // This function is only called for OpLoad, OpStore, OpCopyMemory,
  268. // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
  269. // OpCooperativeMatrixStoreNV.
  270. uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
  271. uint32_t mask_index) {
  272. assert(mask & SpvMemoryAccessMakePointerVisibleKHRMask);
  273. uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerVisibleKHRMask);
  274. uint32_t index =
  275. mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  276. return inst->GetOperandAs<uint32_t>(index);
  277. }
  278. bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
  279. for (size_t member_index = 1; member_index < inst->operands().size();
  280. ++member_index) {
  281. const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
  282. const auto member_type = _.FindDef(member_id);
  283. if (member_type->opcode() == SpvOpTypeRuntimeArray) return true;
  284. }
  285. return false;
  286. }
  287. spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
  288. uint32_t index) {
  289. SpvStorageClass dst_sc, src_sc;
  290. std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
  291. if (inst->operands().size() <= index) {
  292. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  293. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  294. return _.diag(SPV_ERROR_INVALID_ID, inst)
  295. << "Memory accesses with PhysicalStorageBufferEXT must use "
  296. "Aligned.";
  297. }
  298. return SPV_SUCCESS;
  299. }
  300. const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
  301. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
  302. if (inst->opcode() == SpvOpLoad ||
  303. inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  304. return _.diag(SPV_ERROR_INVALID_ID, inst)
  305. << "MakePointerAvailableKHR cannot be used with OpLoad.";
  306. }
  307. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  308. return _.diag(SPV_ERROR_INVALID_ID, inst)
  309. << "NonPrivatePointerKHR must be specified if "
  310. "MakePointerAvailableKHR is specified.";
  311. }
  312. // Check the associated scope for MakeAvailableKHR.
  313. const auto available_scope = GetMakeAvailableScope(inst, mask, index);
  314. if (auto error = ValidateMemoryScope(_, inst, available_scope))
  315. return error;
  316. }
  317. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
  318. if (inst->opcode() == SpvOpStore ||
  319. inst->opcode() == SpvOpCooperativeMatrixStoreNV) {
  320. return _.diag(SPV_ERROR_INVALID_ID, inst)
  321. << "MakePointerVisibleKHR cannot be used with OpStore.";
  322. }
  323. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  324. return _.diag(SPV_ERROR_INVALID_ID, inst)
  325. << "NonPrivatePointerKHR must be specified if "
  326. << "MakePointerVisibleKHR is specified.";
  327. }
  328. // Check the associated scope for MakeVisibleKHR.
  329. const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
  330. if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
  331. }
  332. if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
  333. if (dst_sc != SpvStorageClassUniform &&
  334. dst_sc != SpvStorageClassWorkgroup &&
  335. dst_sc != SpvStorageClassCrossWorkgroup &&
  336. dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
  337. dst_sc != SpvStorageClassStorageBuffer &&
  338. dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  339. return _.diag(SPV_ERROR_INVALID_ID, inst)
  340. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  341. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  342. << "storage classes.";
  343. }
  344. if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
  345. src_sc != SpvStorageClassWorkgroup &&
  346. src_sc != SpvStorageClassCrossWorkgroup &&
  347. src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
  348. src_sc != SpvStorageClassStorageBuffer &&
  349. src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  350. return _.diag(SPV_ERROR_INVALID_ID, inst)
  351. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  352. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  353. << "storage classes.";
  354. }
  355. }
  356. if (!(mask & SpvMemoryAccessAlignedMask)) {
  357. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  358. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  359. return _.diag(SPV_ERROR_INVALID_ID, inst)
  360. << "Memory accesses with PhysicalStorageBufferEXT must use "
  361. "Aligned.";
  362. }
  363. }
  364. return SPV_SUCCESS;
  365. }
  366. spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
  367. auto result_type = _.FindDef(inst->type_id());
  368. if (!result_type || result_type->opcode() != SpvOpTypePointer) {
  369. return _.diag(SPV_ERROR_INVALID_ID, inst)
  370. << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
  371. << "' is not a pointer type.";
  372. }
  373. const auto type_index = 2;
  374. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  375. auto value_type = _.FindDef(value_id);
  376. const auto initializer_index = 3;
  377. const auto storage_class_index = 2;
  378. if (initializer_index < inst->operands().size()) {
  379. const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
  380. const auto initializer = _.FindDef(initializer_id);
  381. const auto is_module_scope_var =
  382. initializer && (initializer->opcode() == SpvOpVariable) &&
  383. (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
  384. SpvStorageClassFunction);
  385. const auto is_constant =
  386. initializer && spvOpcodeIsConstant(initializer->opcode());
  387. if (!initializer || !(is_constant || is_module_scope_var)) {
  388. return _.diag(SPV_ERROR_INVALID_ID, inst)
  389. << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
  390. << "' is not a constant or module-scope variable.";
  391. }
  392. if (initializer->type_id() != value_id) {
  393. return _.diag(SPV_ERROR_INVALID_ID, inst)
  394. << "Initializer type must match the type pointed to by the Result "
  395. "Type";
  396. }
  397. }
  398. auto storage_class = inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  399. if (storage_class != SpvStorageClassWorkgroup &&
  400. storage_class != SpvStorageClassCrossWorkgroup &&
  401. storage_class != SpvStorageClassPrivate &&
  402. storage_class != SpvStorageClassFunction &&
  403. storage_class != SpvStorageClassRayPayloadNV &&
  404. storage_class != SpvStorageClassIncomingRayPayloadNV &&
  405. storage_class != SpvStorageClassHitAttributeNV &&
  406. storage_class != SpvStorageClassCallableDataNV &&
  407. storage_class != SpvStorageClassIncomingCallableDataNV) {
  408. bool storage_input_or_output = storage_class == SpvStorageClassInput ||
  409. storage_class == SpvStorageClassOutput;
  410. bool builtin = false;
  411. if (storage_input_or_output) {
  412. for (const Decoration& decoration : _.id_decorations(inst->id())) {
  413. if (decoration.dec_type() == SpvDecorationBuiltIn) {
  414. builtin = true;
  415. break;
  416. }
  417. }
  418. }
  419. if (!(storage_input_or_output && builtin) &&
  420. ContainsInvalidBool(_, value_type, storage_input_or_output)) {
  421. return _.diag(SPV_ERROR_INVALID_ID, inst)
  422. << "If OpTypeBool is stored in conjunction with OpVariable, it "
  423. << "can only be used with non-externally visible shader Storage "
  424. << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
  425. }
  426. }
  427. if (!_.IsValidStorageClass(storage_class)) {
  428. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  429. << _.VkErrorID(4643)
  430. << "Invalid storage class for target environment";
  431. }
  432. if (storage_class == SpvStorageClassGeneric) {
  433. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  434. << "OpVariable storage class cannot be Generic";
  435. }
  436. if (inst->function() && storage_class != SpvStorageClassFunction) {
  437. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  438. << "Variables must have a function[7] storage class inside"
  439. " of a function";
  440. }
  441. if (!inst->function() && storage_class == SpvStorageClassFunction) {
  442. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  443. << "Variables can not have a function[7] storage class "
  444. "outside of a function";
  445. }
  446. // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  447. // storage class.
  448. const auto result_storage_class_index = 1;
  449. const auto result_storage_class =
  450. result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  451. if (storage_class != result_storage_class) {
  452. return _.diag(SPV_ERROR_INVALID_ID, inst)
  453. << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
  454. << "Its Storage Class operand must be the same as the Storage Class "
  455. << "operand of the result type.";
  456. }
  457. // Variable pointer related restrictions.
  458. const auto pointee = _.FindDef(result_type->word(3));
  459. if (_.addressing_model() == SpvAddressingModelLogical &&
  460. !_.options()->relax_logical_pointer) {
  461. // VariablePointersStorageBuffer is implied by VariablePointers.
  462. if (pointee->opcode() == SpvOpTypePointer) {
  463. if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
  464. return _.diag(SPV_ERROR_INVALID_ID, inst)
  465. << "In Logical addressing, variables may not allocate a pointer "
  466. << "type";
  467. } else if (storage_class != SpvStorageClassFunction &&
  468. storage_class != SpvStorageClassPrivate) {
  469. return _.diag(SPV_ERROR_INVALID_ID, inst)
  470. << "In Logical addressing with variable pointers, variables "
  471. << "that allocate pointers must be in Function or Private "
  472. << "storage classes";
  473. }
  474. }
  475. }
  476. // Vulkan 14.5.1: Check type of PushConstant variables.
  477. // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  478. if (spvIsVulkanEnv(_.context()->target_env)) {
  479. if (storage_class == SpvStorageClassPushConstant) {
  480. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  481. return _.diag(SPV_ERROR_INVALID_ID, inst)
  482. << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
  483. << "' has illegal type.\n"
  484. << "From Vulkan spec, section 14.5.1:\n"
  485. << "Such variables must be typed as OpTypeStruct, "
  486. << "or an array of this type";
  487. }
  488. }
  489. if (storage_class == SpvStorageClassUniformConstant) {
  490. if (!IsAllowedTypeOrArrayOfSame(
  491. _, pointee,
  492. {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
  493. SpvOpTypeAccelerationStructureKHR})) {
  494. return _.diag(SPV_ERROR_INVALID_ID, inst)
  495. << _.VkErrorID(4655) << "UniformConstant OpVariable <id> '"
  496. << _.getIdName(inst->id()) << "' has illegal type.\n"
  497. << "Variables identified with the UniformConstant storage class "
  498. << "are used only as handles to refer to opaque resources. Such "
  499. << "variables must be typed as OpTypeImage, OpTypeSampler, "
  500. << "OpTypeSampledImage, OpTypeAccelerationStructureKHR, "
  501. << "or an array of one of these types.";
  502. }
  503. }
  504. if (storage_class == SpvStorageClassUniform) {
  505. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  506. return _.diag(SPV_ERROR_INVALID_ID, inst)
  507. << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
  508. << "' has illegal type.\n"
  509. << "From Vulkan spec, section 14.5.2:\n"
  510. << "Variables identified with the Uniform storage class are "
  511. << "used to access transparent buffer backed resources. Such "
  512. << "variables must be typed as OpTypeStruct, or an array of "
  513. << "this type";
  514. }
  515. }
  516. if (storage_class == SpvStorageClassStorageBuffer) {
  517. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  518. return _.diag(SPV_ERROR_INVALID_ID, inst)
  519. << "StorageBuffer OpVariable <id> '" << _.getIdName(inst->id())
  520. << "' has illegal type.\n"
  521. << "From Vulkan spec, section 14.5.2:\n"
  522. << "Variables identified with the StorageBuffer storage class "
  523. "are used to access transparent buffer backed resources. "
  524. "Such variables must be typed as OpTypeStruct, or an array "
  525. "of this type";
  526. }
  527. }
  528. // Check for invalid use of Invariant
  529. if (storage_class != SpvStorageClassInput &&
  530. storage_class != SpvStorageClassOutput) {
  531. if (_.HasDecoration(inst->id(), SpvDecorationInvariant)) {
  532. return _.diag(SPV_ERROR_INVALID_ID, inst)
  533. << _.VkErrorID(4677)
  534. << "Variable decorated with Invariant must only be identified "
  535. "with the Input or Output storage class in Vulkan "
  536. "environment.";
  537. }
  538. // Need to check if only the members in a struct are decorated
  539. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  540. if (_.HasDecoration(value_id, SpvDecorationInvariant)) {
  541. return _.diag(SPV_ERROR_INVALID_ID, inst)
  542. << _.VkErrorID(4677)
  543. << "Variable struct member decorated with Invariant must only "
  544. "be identified with the Input or Output storage class in "
  545. "Vulkan environment.";
  546. }
  547. }
  548. }
  549. }
  550. // Vulkan Appendix A: Check that if contains initializer, then
  551. // storage class is Output, Private, or Function.
  552. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
  553. storage_class != SpvStorageClassPrivate &&
  554. storage_class != SpvStorageClassFunction) {
  555. if (spvIsVulkanEnv(_.context()->target_env)) {
  556. if (storage_class == SpvStorageClassWorkgroup) {
  557. auto init_id = inst->GetOperandAs<uint32_t>(3);
  558. auto init = _.FindDef(init_id);
  559. if (init->opcode() != SpvOpConstantNull) {
  560. return _.diag(SPV_ERROR_INVALID_ID, inst)
  561. << "Variable initializers in Workgroup storage class are "
  562. "limited to OpConstantNull";
  563. }
  564. } else {
  565. return _.diag(SPV_ERROR_INVALID_ID, inst)
  566. << _.VkErrorID(4651) << "OpVariable, <id> '"
  567. << _.getIdName(inst->id())
  568. << "', has a disallowed initializer & storage class "
  569. << "combination.\n"
  570. << "From " << spvLogStringForEnv(_.context()->target_env)
  571. << " spec:\n"
  572. << "Variable declarations that include initializers must have "
  573. << "one of the following storage classes: Output, Private, "
  574. << "Function or Workgroup";
  575. }
  576. }
  577. }
  578. if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
  579. return _.diag(SPV_ERROR_INVALID_ID, inst)
  580. << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  581. }
  582. auto pointee_base = pointee;
  583. while (pointee_base->opcode() == SpvOpTypeArray) {
  584. pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  585. }
  586. if (pointee_base->opcode() == SpvOpTypePointer) {
  587. if (pointee_base->GetOperandAs<uint32_t>(1u) ==
  588. SpvStorageClassPhysicalStorageBufferEXT) {
  589. // check for AliasedPointerEXT/RestrictPointerEXT
  590. bool foundAliased =
  591. _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
  592. bool foundRestrict =
  593. _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
  594. if (!foundAliased && !foundRestrict) {
  595. return _.diag(SPV_ERROR_INVALID_ID, inst)
  596. << "OpVariable " << inst->id()
  597. << ": expected AliasedPointerEXT or RestrictPointerEXT for "
  598. << "PhysicalStorageBufferEXT pointer.";
  599. }
  600. if (foundAliased && foundRestrict) {
  601. return _.diag(SPV_ERROR_INVALID_ID, inst)
  602. << "OpVariable " << inst->id()
  603. << ": can't specify both AliasedPointerEXT and "
  604. << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
  605. }
  606. }
  607. }
  608. // Vulkan specific validation rules for OpTypeRuntimeArray
  609. if (spvIsVulkanEnv(_.context()->target_env)) {
  610. // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
  611. // so should never appear as a bare variable.
  612. // Unless the module has the RuntimeDescriptorArrayEXT capability.
  613. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  614. if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
  615. return _.diag(SPV_ERROR_INVALID_ID, inst)
  616. << "OpVariable, <id> '" << _.getIdName(inst->id())
  617. << "', is attempting to create memory for an illegal type, "
  618. << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
  619. << "appear as the final member of an OpTypeStruct, thus cannot "
  620. << "be instantiated via OpVariable";
  621. } else {
  622. // A bare variable OpTypeRuntimeArray is allowed in this context, but
  623. // still need to check the storage class.
  624. if (storage_class != SpvStorageClassStorageBuffer &&
  625. storage_class != SpvStorageClassUniform &&
  626. storage_class != SpvStorageClassUniformConstant) {
  627. return _.diag(SPV_ERROR_INVALID_ID, inst)
  628. << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
  629. << "containing OpTypeRuntimeArray must have storage class of "
  630. << "StorageBuffer, Uniform, or UniformConstant.";
  631. }
  632. }
  633. }
  634. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  635. // must either have the storage class StorageBuffer and be decorated
  636. // with Block, or it must be in the Uniform storage class and be decorated
  637. // as BufferBlock.
  638. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  639. if (DoesStructContainRTA(_, value_type)) {
  640. if (storage_class == SpvStorageClassStorageBuffer) {
  641. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  642. return _.diag(SPV_ERROR_INVALID_ID, inst)
  643. << "For Vulkan, an OpTypeStruct variable containing an "
  644. << "OpTypeRuntimeArray must be decorated with Block if it "
  645. << "has storage class StorageBuffer.";
  646. }
  647. } else if (storage_class == SpvStorageClassUniform) {
  648. if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
  649. return _.diag(SPV_ERROR_INVALID_ID, inst)
  650. << "For Vulkan, an OpTypeStruct variable containing an "
  651. << "OpTypeRuntimeArray must be decorated with BufferBlock "
  652. << "if it has storage class Uniform.";
  653. }
  654. } else {
  655. return _.diag(SPV_ERROR_INVALID_ID, inst)
  656. << "For Vulkan, OpTypeStruct variables containing "
  657. << "OpTypeRuntimeArray must have storage class of "
  658. << "StorageBuffer or Uniform.";
  659. }
  660. }
  661. }
  662. }
  663. // Cooperative matrix types can only be allocated in Function or Private
  664. if ((storage_class != SpvStorageClassFunction &&
  665. storage_class != SpvStorageClassPrivate) &&
  666. ContainsCooperativeMatrix(_, pointee)) {
  667. return _.diag(SPV_ERROR_INVALID_ID, inst)
  668. << "Cooperative matrix types (or types containing them) can only be "
  669. "allocated "
  670. << "in Function or Private storage classes or as function "
  671. "parameters";
  672. }
  673. if (_.HasCapability(SpvCapabilityShader)) {
  674. // Don't allow variables containing 16-bit elements without the appropriate
  675. // capabilities.
  676. if ((!_.HasCapability(SpvCapabilityInt16) &&
  677. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 16)) ||
  678. (!_.HasCapability(SpvCapabilityFloat16) &&
  679. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeFloat, 16))) {
  680. auto underlying_type = value_type;
  681. while (underlying_type->opcode() == SpvOpTypePointer) {
  682. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  683. underlying_type =
  684. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  685. }
  686. bool storage_class_ok = true;
  687. std::string sc_name = _.grammar().lookupOperandName(
  688. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  689. switch (storage_class) {
  690. case SpvStorageClassStorageBuffer:
  691. case SpvStorageClassPhysicalStorageBufferEXT:
  692. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess)) {
  693. storage_class_ok = false;
  694. }
  695. break;
  696. case SpvStorageClassUniform:
  697. if (!_.HasCapability(
  698. SpvCapabilityUniformAndStorageBuffer16BitAccess)) {
  699. if (underlying_type->opcode() == SpvOpTypeArray ||
  700. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  701. underlying_type =
  702. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  703. }
  704. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess) ||
  705. !_.HasDecoration(underlying_type->id(),
  706. SpvDecorationBufferBlock)) {
  707. storage_class_ok = false;
  708. }
  709. }
  710. break;
  711. case SpvStorageClassPushConstant:
  712. if (!_.HasCapability(SpvCapabilityStoragePushConstant16)) {
  713. storage_class_ok = false;
  714. }
  715. break;
  716. case SpvStorageClassInput:
  717. case SpvStorageClassOutput:
  718. if (!_.HasCapability(SpvCapabilityStorageInputOutput16)) {
  719. storage_class_ok = false;
  720. }
  721. break;
  722. case SpvStorageClassWorkgroup:
  723. if (!_.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR)) {
  724. storage_class_ok = false;
  725. }
  726. break;
  727. default:
  728. return _.diag(SPV_ERROR_INVALID_ID, inst)
  729. << "Cannot allocate a variable containing a 16-bit type in "
  730. << sc_name << " storage class";
  731. }
  732. if (!storage_class_ok) {
  733. return _.diag(SPV_ERROR_INVALID_ID, inst)
  734. << "Allocating a variable containing a 16-bit element in "
  735. << sc_name << " storage class requires an additional capability";
  736. }
  737. }
  738. // Don't allow variables containing 8-bit elements without the appropriate
  739. // capabilities.
  740. if (!_.HasCapability(SpvCapabilityInt8) &&
  741. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 8)) {
  742. auto underlying_type = value_type;
  743. while (underlying_type->opcode() == SpvOpTypePointer) {
  744. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  745. underlying_type =
  746. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  747. }
  748. bool storage_class_ok = true;
  749. std::string sc_name = _.grammar().lookupOperandName(
  750. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  751. switch (storage_class) {
  752. case SpvStorageClassStorageBuffer:
  753. case SpvStorageClassPhysicalStorageBufferEXT:
  754. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess)) {
  755. storage_class_ok = false;
  756. }
  757. break;
  758. case SpvStorageClassUniform:
  759. if (!_.HasCapability(
  760. SpvCapabilityUniformAndStorageBuffer8BitAccess)) {
  761. if (underlying_type->opcode() == SpvOpTypeArray ||
  762. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  763. underlying_type =
  764. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  765. }
  766. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess) ||
  767. !_.HasDecoration(underlying_type->id(),
  768. SpvDecorationBufferBlock)) {
  769. storage_class_ok = false;
  770. }
  771. }
  772. break;
  773. case SpvStorageClassPushConstant:
  774. if (!_.HasCapability(SpvCapabilityStoragePushConstant8)) {
  775. storage_class_ok = false;
  776. }
  777. break;
  778. case SpvStorageClassWorkgroup:
  779. if (!_.HasCapability(SpvCapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR)) {
  780. storage_class_ok = false;
  781. }
  782. break;
  783. default:
  784. return _.diag(SPV_ERROR_INVALID_ID, inst)
  785. << "Cannot allocate a variable containing a 8-bit type in "
  786. << sc_name << " storage class";
  787. }
  788. if (!storage_class_ok) {
  789. return _.diag(SPV_ERROR_INVALID_ID, inst)
  790. << "Allocating a variable containing a 8-bit element in "
  791. << sc_name << " storage class requires an additional capability";
  792. }
  793. }
  794. }
  795. return SPV_SUCCESS;
  796. }
  797. spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  798. const auto result_type = _.FindDef(inst->type_id());
  799. if (!result_type) {
  800. return _.diag(SPV_ERROR_INVALID_ID, inst)
  801. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  802. << "' is not defined.";
  803. }
  804. const bool uses_variable_pointers =
  805. _.features().variable_pointers ||
  806. _.features().variable_pointers_storage_buffer;
  807. const auto pointer_index = 2;
  808. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  809. const auto pointer = _.FindDef(pointer_id);
  810. if (!pointer ||
  811. ((_.addressing_model() == SpvAddressingModelLogical) &&
  812. ((!uses_variable_pointers &&
  813. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  814. (uses_variable_pointers &&
  815. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  816. return _.diag(SPV_ERROR_INVALID_ID, inst)
  817. << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
  818. << "' is not a logical pointer.";
  819. }
  820. const auto pointer_type = _.FindDef(pointer->type_id());
  821. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  822. return _.diag(SPV_ERROR_INVALID_ID, inst)
  823. << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
  824. << "' is not a pointer type.";
  825. }
  826. const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  827. if (!pointee_type || result_type->id() != pointee_type->id()) {
  828. return _.diag(SPV_ERROR_INVALID_ID, inst)
  829. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  830. << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
  831. << "'s type.";
  832. }
  833. if (!_.options()->before_hlsl_legalization &&
  834. _.ContainsRuntimeArray(inst->type_id())) {
  835. return _.diag(SPV_ERROR_INVALID_ID, inst)
  836. << "Cannot load a runtime-sized array";
  837. }
  838. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  839. if (_.HasCapability(SpvCapabilityShader) &&
  840. _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
  841. result_type->opcode() != SpvOpTypePointer) {
  842. if (result_type->opcode() != SpvOpTypeInt &&
  843. result_type->opcode() != SpvOpTypeFloat &&
  844. result_type->opcode() != SpvOpTypeVector &&
  845. result_type->opcode() != SpvOpTypeMatrix) {
  846. return _.diag(SPV_ERROR_INVALID_ID, inst)
  847. << "8- or 16-bit loads must be a scalar, vector or matrix type";
  848. }
  849. }
  850. return SPV_SUCCESS;
  851. }
  852. spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
  853. const bool uses_variable_pointer =
  854. _.features().variable_pointers ||
  855. _.features().variable_pointers_storage_buffer;
  856. const auto pointer_index = 0;
  857. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  858. const auto pointer = _.FindDef(pointer_id);
  859. if (!pointer ||
  860. (_.addressing_model() == SpvAddressingModelLogical &&
  861. ((!uses_variable_pointer &&
  862. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  863. (uses_variable_pointer &&
  864. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  865. return _.diag(SPV_ERROR_INVALID_ID, inst)
  866. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  867. << "' is not a logical pointer.";
  868. }
  869. const auto pointer_type = _.FindDef(pointer->type_id());
  870. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  871. return _.diag(SPV_ERROR_INVALID_ID, inst)
  872. << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
  873. << "' is not a pointer type.";
  874. }
  875. const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
  876. const auto type = _.FindDef(type_id);
  877. if (!type || SpvOpTypeVoid == type->opcode()) {
  878. return _.diag(SPV_ERROR_INVALID_ID, inst)
  879. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  880. << "'s type is void.";
  881. }
  882. // validate storage class
  883. {
  884. uint32_t data_type;
  885. uint32_t storage_class;
  886. if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
  887. return _.diag(SPV_ERROR_INVALID_ID, inst)
  888. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  889. << "' is not pointer type";
  890. }
  891. if (storage_class == SpvStorageClassUniformConstant ||
  892. storage_class == SpvStorageClassInput ||
  893. storage_class == SpvStorageClassPushConstant) {
  894. return _.diag(SPV_ERROR_INVALID_ID, inst)
  895. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  896. << "' storage class is read-only";
  897. }
  898. if (spvIsVulkanEnv(_.context()->target_env) &&
  899. storage_class == SpvStorageClassUniform) {
  900. auto base_ptr = _.TracePointer(pointer);
  901. if (base_ptr->opcode() == SpvOpVariable) {
  902. // If it's not a variable a different check should catch the problem.
  903. auto base_type = _.FindDef(base_ptr->GetOperandAs<uint32_t>(0));
  904. // Get the pointed-to type.
  905. base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(2u));
  906. if (base_type->opcode() == SpvOpTypeArray ||
  907. base_type->opcode() == SpvOpTypeRuntimeArray) {
  908. base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(1u));
  909. }
  910. if (_.HasDecoration(base_type->id(), SpvDecorationBlock)) {
  911. return _.diag(SPV_ERROR_INVALID_ID, inst)
  912. << "In the Vulkan environment, cannot store to Uniform Blocks";
  913. }
  914. }
  915. }
  916. }
  917. const auto object_index = 1;
  918. const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
  919. const auto object = _.FindDef(object_id);
  920. if (!object || !object->type_id()) {
  921. return _.diag(SPV_ERROR_INVALID_ID, inst)
  922. << "OpStore Object <id> '" << _.getIdName(object_id)
  923. << "' is not an object.";
  924. }
  925. const auto object_type = _.FindDef(object->type_id());
  926. if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
  927. return _.diag(SPV_ERROR_INVALID_ID, inst)
  928. << "OpStore Object <id> '" << _.getIdName(object_id)
  929. << "'s type is void.";
  930. }
  931. if (type->id() != object_type->id()) {
  932. if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
  933. object_type->opcode() != SpvOpTypeStruct) {
  934. return _.diag(SPV_ERROR_INVALID_ID, inst)
  935. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  936. << "'s type does not match Object <id> '"
  937. << _.getIdName(object->id()) << "'s type.";
  938. }
  939. // TODO: Check for layout compatible matricies and arrays as well.
  940. if (!AreLayoutCompatibleStructs(_, type, object_type)) {
  941. return _.diag(SPV_ERROR_INVALID_ID, inst)
  942. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  943. << "'s layout does not match Object <id> '"
  944. << _.getIdName(object->id()) << "'s layout.";
  945. }
  946. }
  947. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  948. if (_.HasCapability(SpvCapabilityShader) &&
  949. _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
  950. object_type->opcode() != SpvOpTypePointer) {
  951. if (object_type->opcode() != SpvOpTypeInt &&
  952. object_type->opcode() != SpvOpTypeFloat &&
  953. object_type->opcode() != SpvOpTypeVector &&
  954. object_type->opcode() != SpvOpTypeMatrix) {
  955. return _.diag(SPV_ERROR_INVALID_ID, inst)
  956. << "8- or 16-bit stores must be a scalar, vector or matrix type";
  957. }
  958. }
  959. return SPV_SUCCESS;
  960. }
  961. spv_result_t ValidateCopyMemoryMemoryAccess(ValidationState_t& _,
  962. const Instruction* inst) {
  963. assert(inst->opcode() == SpvOpCopyMemory ||
  964. inst->opcode() == SpvOpCopyMemorySized);
  965. const uint32_t first_access_index = inst->opcode() == SpvOpCopyMemory ? 2 : 3;
  966. if (inst->operands().size() > first_access_index) {
  967. if (auto error = CheckMemoryAccess(_, inst, first_access_index))
  968. return error;
  969. const auto first_access = inst->GetOperandAs<uint32_t>(first_access_index);
  970. const uint32_t second_access_index =
  971. first_access_index + MemoryAccessNumWords(first_access);
  972. if (inst->operands().size() > second_access_index) {
  973. if (_.features().copy_memory_permits_two_memory_accesses) {
  974. if (auto error = CheckMemoryAccess(_, inst, second_access_index))
  975. return error;
  976. // In the two-access form in SPIR-V 1.4 and later:
  977. // - the first is the target (write) access and it can't have
  978. // make-visible.
  979. // - the second is the source (read) access and it can't have
  980. // make-available.
  981. if (first_access & SpvMemoryAccessMakePointerVisibleKHRMask) {
  982. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  983. << "Target memory access must not include "
  984. "MakePointerVisibleKHR";
  985. }
  986. const auto second_access =
  987. inst->GetOperandAs<uint32_t>(second_access_index);
  988. if (second_access & SpvMemoryAccessMakePointerAvailableKHRMask) {
  989. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  990. << "Source memory access must not include "
  991. "MakePointerAvailableKHR";
  992. }
  993. } else {
  994. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  995. << spvOpcodeString(static_cast<SpvOp>(inst->opcode()))
  996. << " with two memory access operands requires SPIR-V 1.4 or "
  997. "later";
  998. }
  999. }
  1000. }
  1001. return SPV_SUCCESS;
  1002. }
  1003. spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
  1004. const auto target_index = 0;
  1005. const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
  1006. const auto target = _.FindDef(target_id);
  1007. if (!target) {
  1008. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1009. << "Target operand <id> '" << _.getIdName(target_id)
  1010. << "' is not defined.";
  1011. }
  1012. const auto source_index = 1;
  1013. const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
  1014. const auto source = _.FindDef(source_id);
  1015. if (!source) {
  1016. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1017. << "Source operand <id> '" << _.getIdName(source_id)
  1018. << "' is not defined.";
  1019. }
  1020. const auto target_pointer_type = _.FindDef(target->type_id());
  1021. if (!target_pointer_type ||
  1022. target_pointer_type->opcode() != SpvOpTypePointer) {
  1023. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1024. << "Target operand <id> '" << _.getIdName(target_id)
  1025. << "' is not a pointer.";
  1026. }
  1027. const auto source_pointer_type = _.FindDef(source->type_id());
  1028. if (!source_pointer_type ||
  1029. source_pointer_type->opcode() != SpvOpTypePointer) {
  1030. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1031. << "Source operand <id> '" << _.getIdName(source_id)
  1032. << "' is not a pointer.";
  1033. }
  1034. if (inst->opcode() == SpvOpCopyMemory) {
  1035. const auto target_type =
  1036. _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  1037. if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
  1038. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1039. << "Target operand <id> '" << _.getIdName(target_id)
  1040. << "' cannot be a void pointer.";
  1041. }
  1042. const auto source_type =
  1043. _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
  1044. if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
  1045. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1046. << "Source operand <id> '" << _.getIdName(source_id)
  1047. << "' cannot be a void pointer.";
  1048. }
  1049. if (target_type->id() != source_type->id()) {
  1050. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1051. << "Target <id> '" << _.getIdName(source_id)
  1052. << "'s type does not match Source <id> '"
  1053. << _.getIdName(source_type->id()) << "'s type.";
  1054. }
  1055. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  1056. } else {
  1057. const auto size_id = inst->GetOperandAs<uint32_t>(2);
  1058. const auto size = _.FindDef(size_id);
  1059. if (!size) {
  1060. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1061. << "Size operand <id> '" << _.getIdName(size_id)
  1062. << "' is not defined.";
  1063. }
  1064. const auto size_type = _.FindDef(size->type_id());
  1065. if (!_.IsIntScalarType(size_type->id())) {
  1066. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1067. << "Size operand <id> '" << _.getIdName(size_id)
  1068. << "' must be a scalar integer type.";
  1069. }
  1070. bool is_zero = true;
  1071. switch (size->opcode()) {
  1072. case SpvOpConstantNull:
  1073. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1074. << "Size operand <id> '" << _.getIdName(size_id)
  1075. << "' cannot be a constant zero.";
  1076. case SpvOpConstant:
  1077. if (size_type->word(3) == 1 &&
  1078. size->word(size->words().size() - 1) & 0x80000000) {
  1079. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1080. << "Size operand <id> '" << _.getIdName(size_id)
  1081. << "' cannot have the sign bit set to 1.";
  1082. }
  1083. for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
  1084. is_zero &= (size->word(i) == 0);
  1085. }
  1086. if (is_zero) {
  1087. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1088. << "Size operand <id> '" << _.getIdName(size_id)
  1089. << "' cannot be a constant zero.";
  1090. }
  1091. break;
  1092. default:
  1093. // Cannot infer any other opcodes.
  1094. break;
  1095. }
  1096. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  1097. }
  1098. if (auto error = ValidateCopyMemoryMemoryAccess(_, inst)) return error;
  1099. // Get past the pointers to avoid checking a pointer copy.
  1100. auto sub_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  1101. while (sub_type->opcode() == SpvOpTypePointer) {
  1102. sub_type = _.FindDef(sub_type->GetOperandAs<uint32_t>(2));
  1103. }
  1104. if (_.HasCapability(SpvCapabilityShader) &&
  1105. _.ContainsLimitedUseIntOrFloatType(sub_type->id())) {
  1106. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1107. << "Cannot copy memory of objects containing 8- or 16-bit types";
  1108. }
  1109. return SPV_SUCCESS;
  1110. }
  1111. spv_result_t ValidateAccessChain(ValidationState_t& _,
  1112. const Instruction* inst) {
  1113. std::string instr_name =
  1114. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1115. // The result type must be OpTypePointer.
  1116. auto result_type = _.FindDef(inst->type_id());
  1117. if (SpvOpTypePointer != result_type->opcode()) {
  1118. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1119. << "The Result Type of " << instr_name << " <id> '"
  1120. << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
  1121. << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
  1122. }
  1123. // Result type is a pointer. Find out what it's pointing to.
  1124. // This will be used to make sure the indexing results in the same type.
  1125. // OpTypePointer word 3 is the type being pointed to.
  1126. const auto result_type_pointee = _.FindDef(result_type->word(3));
  1127. // Base must be a pointer, pointing to the base of a composite object.
  1128. const auto base_index = 2;
  1129. const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
  1130. const auto base = _.FindDef(base_id);
  1131. const auto base_type = _.FindDef(base->type_id());
  1132. if (!base_type || SpvOpTypePointer != base_type->opcode()) {
  1133. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1134. << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
  1135. << " instruction must be a pointer.";
  1136. }
  1137. // The result pointer storage class and base pointer storage class must match.
  1138. // Word 2 of OpTypePointer is the Storage Class.
  1139. auto result_type_storage_class = result_type->word(2);
  1140. auto base_type_storage_class = base_type->word(2);
  1141. if (result_type_storage_class != base_type_storage_class) {
  1142. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1143. << "The result pointer storage class and base "
  1144. "pointer storage class in "
  1145. << instr_name << " do not match.";
  1146. }
  1147. // The type pointed to by OpTypePointer (word 3) must be a composite type.
  1148. auto type_pointee = _.FindDef(base_type->word(3));
  1149. // Check Universal Limit (SPIR-V Spec. Section 2.17).
  1150. // The number of indexes passed to OpAccessChain may not exceed 255
  1151. // The instruction includes 4 words + N words (for N indexes)
  1152. size_t num_indexes = inst->words().size() - 4;
  1153. if (inst->opcode() == SpvOpPtrAccessChain ||
  1154. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  1155. // In pointer access chains, the element operand is required, but not
  1156. // counted as an index.
  1157. --num_indexes;
  1158. }
  1159. const size_t num_indexes_limit =
  1160. _.options()->universal_limits_.max_access_chain_indexes;
  1161. if (num_indexes > num_indexes_limit) {
  1162. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1163. << "The number of indexes in " << instr_name << " may not exceed "
  1164. << num_indexes_limit << ". Found " << num_indexes << " indexes.";
  1165. }
  1166. // Indexes walk the type hierarchy to the desired depth, potentially down to
  1167. // scalar granularity. The first index in Indexes will select the top-level
  1168. // member/element/component/element of the base composite. All composite
  1169. // constituents use zero-based numbering, as described by their OpType...
  1170. // instruction. The second index will apply similarly to that result, and so
  1171. // on. Once any non-composite type is reached, there must be no remaining
  1172. // (unused) indexes.
  1173. auto starting_index = 4;
  1174. if (inst->opcode() == SpvOpPtrAccessChain ||
  1175. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  1176. ++starting_index;
  1177. }
  1178. for (size_t i = starting_index; i < inst->words().size(); ++i) {
  1179. const uint32_t cur_word = inst->words()[i];
  1180. // Earlier ID checks ensure that cur_word definition exists.
  1181. auto cur_word_instr = _.FindDef(cur_word);
  1182. // The index must be a scalar integer type (See OpAccessChain in the Spec.)
  1183. auto index_type = _.FindDef(cur_word_instr->type_id());
  1184. if (!index_type || SpvOpTypeInt != index_type->opcode()) {
  1185. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1186. << "Indexes passed to " << instr_name
  1187. << " must be of type integer.";
  1188. }
  1189. switch (type_pointee->opcode()) {
  1190. case SpvOpTypeMatrix:
  1191. case SpvOpTypeVector:
  1192. case SpvOpTypeCooperativeMatrixNV:
  1193. case SpvOpTypeArray:
  1194. case SpvOpTypeRuntimeArray: {
  1195. // In OpTypeMatrix, OpTypeVector, SpvOpTypeCooperativeMatrixNV,
  1196. // OpTypeArray, and OpTypeRuntimeArray, word 2 is the Element Type.
  1197. type_pointee = _.FindDef(type_pointee->word(2));
  1198. break;
  1199. }
  1200. case SpvOpTypeStruct: {
  1201. // In case of structures, there is an additional constraint on the
  1202. // index: the index must be an OpConstant.
  1203. if (SpvOpConstant != cur_word_instr->opcode()) {
  1204. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1205. << "The <id> passed to " << instr_name
  1206. << " to index into a "
  1207. "structure must be an OpConstant.";
  1208. }
  1209. // Get the index value from the OpConstant (word 3 of OpConstant).
  1210. // OpConstant could be a signed integer. But it's okay to treat it as
  1211. // unsigned because a negative constant int would never be seen as
  1212. // correct as a struct offset, since structs can't have more than 2
  1213. // billion members.
  1214. const uint32_t cur_index = cur_word_instr->word(3);
  1215. // The index points to the struct member we want, therefore, the index
  1216. // should be less than the number of struct members.
  1217. const uint32_t num_struct_members =
  1218. static_cast<uint32_t>(type_pointee->words().size() - 2);
  1219. if (cur_index >= num_struct_members) {
  1220. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1221. << "Index is out of bounds: " << instr_name
  1222. << " can not find index " << cur_index
  1223. << " into the structure <id> '"
  1224. << _.getIdName(type_pointee->id()) << "'. This structure has "
  1225. << num_struct_members << " members. Largest valid index is "
  1226. << num_struct_members - 1 << ".";
  1227. }
  1228. // Struct members IDs start at word 2 of OpTypeStruct.
  1229. auto structMemberId = type_pointee->word(cur_index + 2);
  1230. type_pointee = _.FindDef(structMemberId);
  1231. break;
  1232. }
  1233. default: {
  1234. // Give an error. reached non-composite type while indexes still remain.
  1235. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1236. << instr_name
  1237. << " reached non-composite type while indexes "
  1238. "still remain to be traversed.";
  1239. }
  1240. }
  1241. }
  1242. // At this point, we have fully walked down from the base using the indeces.
  1243. // The type being pointed to should be the same as the result type.
  1244. if (type_pointee->id() != result_type_pointee->id()) {
  1245. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1246. << instr_name << " result type (Op"
  1247. << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
  1248. << ") does not match the type that results from indexing into the "
  1249. "base "
  1250. "<id> (Op"
  1251. << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
  1252. << ").";
  1253. }
  1254. return SPV_SUCCESS;
  1255. }
  1256. spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
  1257. const Instruction* inst) {
  1258. if (_.addressing_model() == SpvAddressingModelLogical) {
  1259. if (!_.features().variable_pointers &&
  1260. !_.features().variable_pointers_storage_buffer) {
  1261. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  1262. << "Generating variable pointers requires capability "
  1263. << "VariablePointers or VariablePointersStorageBuffer";
  1264. }
  1265. }
  1266. return ValidateAccessChain(_, inst);
  1267. }
  1268. spv_result_t ValidateArrayLength(ValidationState_t& state,
  1269. const Instruction* inst) {
  1270. std::string instr_name =
  1271. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1272. // Result type must be a 32-bit unsigned int.
  1273. auto result_type = state.FindDef(inst->type_id());
  1274. if (result_type->opcode() != SpvOpTypeInt ||
  1275. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1276. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1277. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1278. << "The Result Type of " << instr_name << " <id> '"
  1279. << state.getIdName(inst->id())
  1280. << "' must be OpTypeInt with width 32 and signedness 0.";
  1281. }
  1282. // The structure that is passed in must be an pointer to a structure, whose
  1283. // last element is a runtime array.
  1284. auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
  1285. auto pointer_type = state.FindDef(pointer->type_id());
  1286. if (pointer_type->opcode() != SpvOpTypePointer) {
  1287. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1288. << "The Struture's type in " << instr_name << " <id> '"
  1289. << state.getIdName(inst->id())
  1290. << "' must be a pointer to an OpTypeStruct.";
  1291. }
  1292. auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  1293. if (structure_type->opcode() != SpvOpTypeStruct) {
  1294. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1295. << "The Struture's type in " << instr_name << " <id> '"
  1296. << state.getIdName(inst->id())
  1297. << "' must be a pointer to an OpTypeStruct.";
  1298. }
  1299. auto num_of_members = structure_type->operands().size() - 1;
  1300. auto last_member =
  1301. state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
  1302. if (last_member->opcode() != SpvOpTypeRuntimeArray) {
  1303. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1304. << "The Struture's last member in " << instr_name << " <id> '"
  1305. << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
  1306. }
  1307. // The array member must the the index of the last element (the run time
  1308. // array).
  1309. if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
  1310. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1311. << "The array member in " << instr_name << " <id> '"
  1312. << state.getIdName(inst->id())
  1313. << "' must be an the last member of the struct.";
  1314. }
  1315. return SPV_SUCCESS;
  1316. }
  1317. spv_result_t ValidateCooperativeMatrixLengthNV(ValidationState_t& state,
  1318. const Instruction* inst) {
  1319. std::string instr_name =
  1320. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1321. // Result type must be a 32-bit unsigned int.
  1322. auto result_type = state.FindDef(inst->type_id());
  1323. if (result_type->opcode() != SpvOpTypeInt ||
  1324. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1325. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1326. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1327. << "The Result Type of " << instr_name << " <id> '"
  1328. << state.getIdName(inst->id())
  1329. << "' must be OpTypeInt with width 32 and signedness 0.";
  1330. }
  1331. auto type_id = inst->GetOperandAs<uint32_t>(2);
  1332. auto type = state.FindDef(type_id);
  1333. if (type->opcode() != SpvOpTypeCooperativeMatrixNV) {
  1334. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1335. << "The type in " << instr_name << " <id> '"
  1336. << state.getIdName(type_id)
  1337. << "' must be OpTypeCooperativeMatrixNV.";
  1338. }
  1339. return SPV_SUCCESS;
  1340. }
  1341. spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
  1342. const Instruction* inst) {
  1343. uint32_t type_id;
  1344. const char* opname;
  1345. if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  1346. type_id = inst->type_id();
  1347. opname = "SpvOpCooperativeMatrixLoadNV";
  1348. } else {
  1349. // get Object operand's type
  1350. type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
  1351. opname = "SpvOpCooperativeMatrixStoreNV";
  1352. }
  1353. auto matrix_type = _.FindDef(type_id);
  1354. if (matrix_type->opcode() != SpvOpTypeCooperativeMatrixNV) {
  1355. if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  1356. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1357. << "SpvOpCooperativeMatrixLoadNV Result Type <id> '"
  1358. << _.getIdName(type_id) << "' is not a cooperative matrix type.";
  1359. } else {
  1360. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1361. << "SpvOpCooperativeMatrixStoreNV Object type <id> '"
  1362. << _.getIdName(type_id) << "' is not a cooperative matrix type.";
  1363. }
  1364. }
  1365. const bool uses_variable_pointers =
  1366. _.features().variable_pointers ||
  1367. _.features().variable_pointers_storage_buffer;
  1368. const auto pointer_index =
  1369. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 2u : 0u;
  1370. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  1371. const auto pointer = _.FindDef(pointer_id);
  1372. if (!pointer ||
  1373. ((_.addressing_model() == SpvAddressingModelLogical) &&
  1374. ((!uses_variable_pointers &&
  1375. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  1376. (uses_variable_pointers &&
  1377. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  1378. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1379. << opname << " Pointer <id> '" << _.getIdName(pointer_id)
  1380. << "' is not a logical pointer.";
  1381. }
  1382. const auto pointer_type_id = pointer->type_id();
  1383. const auto pointer_type = _.FindDef(pointer_type_id);
  1384. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  1385. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1386. << opname << " type for pointer <id> '" << _.getIdName(pointer_id)
  1387. << "' is not a pointer type.";
  1388. }
  1389. const auto storage_class_index = 1u;
  1390. const auto storage_class =
  1391. pointer_type->GetOperandAs<uint32_t>(storage_class_index);
  1392. if (storage_class != SpvStorageClassWorkgroup &&
  1393. storage_class != SpvStorageClassStorageBuffer &&
  1394. storage_class != SpvStorageClassPhysicalStorageBufferEXT) {
  1395. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1396. << opname << " storage class for pointer type <id> '"
  1397. << _.getIdName(pointer_type_id)
  1398. << "' is not Workgroup or StorageBuffer.";
  1399. }
  1400. const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
  1401. const auto pointee_type = _.FindDef(pointee_id);
  1402. if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
  1403. _.IsFloatScalarOrVectorType(pointee_id))) {
  1404. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1405. << opname << " Pointer <id> '" << _.getIdName(pointer->id())
  1406. << "'s Type must be a scalar or vector type.";
  1407. }
  1408. const auto stride_index =
  1409. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 3u : 2u;
  1410. const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
  1411. const auto stride = _.FindDef(stride_id);
  1412. if (!stride || !_.IsIntScalarType(stride->type_id())) {
  1413. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1414. << "Stride operand <id> '" << _.getIdName(stride_id)
  1415. << "' must be a scalar integer type.";
  1416. }
  1417. const auto colmajor_index =
  1418. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 4u : 3u;
  1419. const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
  1420. const auto colmajor = _.FindDef(colmajor_id);
  1421. if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
  1422. !(spvOpcodeIsConstant(colmajor->opcode()) ||
  1423. spvOpcodeIsSpecConstant(colmajor->opcode()))) {
  1424. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1425. << "Column Major operand <id> '" << _.getIdName(colmajor_id)
  1426. << "' must be a boolean constant instruction.";
  1427. }
  1428. const auto memory_access_index =
  1429. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 5u : 4u;
  1430. if (inst->operands().size() > memory_access_index) {
  1431. if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
  1432. return error;
  1433. }
  1434. return SPV_SUCCESS;
  1435. }
  1436. spv_result_t ValidatePtrComparison(ValidationState_t& _,
  1437. const Instruction* inst) {
  1438. if (_.addressing_model() == SpvAddressingModelLogical &&
  1439. !_.features().variable_pointers_storage_buffer) {
  1440. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1441. << "Instruction cannot be used without a variable pointers "
  1442. "capability";
  1443. }
  1444. const auto result_type = _.FindDef(inst->type_id());
  1445. if (inst->opcode() == SpvOpPtrDiff) {
  1446. if (!result_type || result_type->opcode() != SpvOpTypeInt) {
  1447. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1448. << "Result Type must be an integer scalar";
  1449. }
  1450. } else {
  1451. if (!result_type || result_type->opcode() != SpvOpTypeBool) {
  1452. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1453. << "Result Type must be OpTypeBool";
  1454. }
  1455. }
  1456. const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
  1457. const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
  1458. if (!op1 || !op2 || op1->type_id() != op2->type_id()) {
  1459. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1460. << "The types of Operand 1 and Operand 2 must match";
  1461. }
  1462. const auto op1_type = _.FindDef(op1->type_id());
  1463. if (!op1_type || op1_type->opcode() != SpvOpTypePointer) {
  1464. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1465. << "Operand type must be a pointer";
  1466. }
  1467. SpvStorageClass sc = op1_type->GetOperandAs<SpvStorageClass>(1u);
  1468. if (_.addressing_model() == SpvAddressingModelLogical) {
  1469. if (sc != SpvStorageClassWorkgroup && sc != SpvStorageClassStorageBuffer) {
  1470. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1471. << "Invalid pointer storage class";
  1472. }
  1473. if (sc == SpvStorageClassWorkgroup && !_.features().variable_pointers) {
  1474. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1475. << "Workgroup storage class pointer requires VariablePointers "
  1476. "capability to be specified";
  1477. }
  1478. } else if (sc == SpvStorageClassPhysicalStorageBuffer) {
  1479. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1480. << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
  1481. }
  1482. return SPV_SUCCESS;
  1483. }
  1484. } // namespace
  1485. spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
  1486. switch (inst->opcode()) {
  1487. case SpvOpVariable:
  1488. if (auto error = ValidateVariable(_, inst)) return error;
  1489. break;
  1490. case SpvOpLoad:
  1491. if (auto error = ValidateLoad(_, inst)) return error;
  1492. break;
  1493. case SpvOpStore:
  1494. if (auto error = ValidateStore(_, inst)) return error;
  1495. break;
  1496. case SpvOpCopyMemory:
  1497. case SpvOpCopyMemorySized:
  1498. if (auto error = ValidateCopyMemory(_, inst)) return error;
  1499. break;
  1500. case SpvOpPtrAccessChain:
  1501. if (auto error = ValidatePtrAccessChain(_, inst)) return error;
  1502. break;
  1503. case SpvOpAccessChain:
  1504. case SpvOpInBoundsAccessChain:
  1505. case SpvOpInBoundsPtrAccessChain:
  1506. if (auto error = ValidateAccessChain(_, inst)) return error;
  1507. break;
  1508. case SpvOpArrayLength:
  1509. if (auto error = ValidateArrayLength(_, inst)) return error;
  1510. break;
  1511. case SpvOpCooperativeMatrixLoadNV:
  1512. case SpvOpCooperativeMatrixStoreNV:
  1513. if (auto error = ValidateCooperativeMatrixLoadStoreNV(_, inst))
  1514. return error;
  1515. break;
  1516. case SpvOpCooperativeMatrixLengthNV:
  1517. if (auto error = ValidateCooperativeMatrixLengthNV(_, inst)) return error;
  1518. break;
  1519. case SpvOpPtrEqual:
  1520. case SpvOpPtrNotEqual:
  1521. case SpvOpPtrDiff:
  1522. if (auto error = ValidatePtrComparison(_, inst)) return error;
  1523. break;
  1524. case SpvOpImageTexelPointer:
  1525. case SpvOpGenericPtrMemSemantics:
  1526. default:
  1527. break;
  1528. }
  1529. return SPV_SUCCESS;
  1530. }
  1531. } // namespace val
  1532. } // namespace spvtools