validate_memory.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  1. // Copyright (c) 2018 Google LLC.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <algorithm>
  15. #include <string>
  16. #include <vector>
  17. #include "source/opcode.h"
  18. #include "source/spirv_target_env.h"
  19. #include "source/val/instruction.h"
  20. #include "source/val/validate.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. bool ContainsCooperativeMatrix(ValidationState_t& _,
  182. const Instruction* storage) {
  183. const size_t elem_type_index = 1;
  184. uint32_t elem_type_id;
  185. Instruction* elem_type;
  186. switch (storage->opcode()) {
  187. case SpvOpTypeCooperativeMatrixNV:
  188. return true;
  189. case SpvOpTypeArray:
  190. case SpvOpTypeRuntimeArray:
  191. elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
  192. elem_type = _.FindDef(elem_type_id);
  193. return ContainsCooperativeMatrix(_, elem_type);
  194. case SpvOpTypeStruct:
  195. for (size_t member_type_index = 1;
  196. member_type_index < storage->operands().size();
  197. ++member_type_index) {
  198. auto member_type_id =
  199. storage->GetOperandAs<uint32_t>(member_type_index);
  200. auto member_type = _.FindDef(member_type_id);
  201. if (ContainsCooperativeMatrix(_, member_type)) return true;
  202. }
  203. break;
  204. default:
  205. break;
  206. }
  207. return false;
  208. }
  209. std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
  210. ValidationState_t& _, const Instruction* inst) {
  211. SpvStorageClass dst_sc = SpvStorageClassMax;
  212. SpvStorageClass src_sc = SpvStorageClassMax;
  213. switch (inst->opcode()) {
  214. case SpvOpCooperativeMatrixLoadNV:
  215. case SpvOpLoad: {
  216. auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
  217. auto load_pointer_type = _.FindDef(load_pointer->type_id());
  218. dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
  219. break;
  220. }
  221. case SpvOpCooperativeMatrixStoreNV:
  222. case SpvOpStore: {
  223. auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  224. auto store_pointer_type = _.FindDef(store_pointer->type_id());
  225. dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
  226. break;
  227. }
  228. case SpvOpCopyMemory:
  229. case SpvOpCopyMemorySized: {
  230. auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  231. auto dst_type = _.FindDef(dst->type_id());
  232. dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
  233. auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
  234. auto src_type = _.FindDef(src->type_id());
  235. src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
  236. break;
  237. }
  238. default:
  239. break;
  240. }
  241. return std::make_pair(dst_sc, src_sc);
  242. }
  243. // Returns the number of instruction words taken up by a memory access
  244. // argument and its implied operands.
  245. int MemoryAccessNumWords(uint32_t mask) {
  246. int result = 1; // Count the mask
  247. if (mask & SpvMemoryAccessAlignedMask) ++result;
  248. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++result;
  249. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) ++result;
  250. return result;
  251. }
  252. // Returns the scope ID operand for MakeAvailable memory access with mask
  253. // at the given operand index.
  254. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  255. // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
  256. // OpCooperativeMatrixStoreNV.
  257. uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
  258. uint32_t mask_index) {
  259. assert(mask & SpvMemoryAccessMakePointerAvailableKHRMask);
  260. uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerAvailableKHRMask);
  261. uint32_t index =
  262. mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  263. return inst->GetOperandAs<uint32_t>(index);
  264. }
  265. // This function is only called for OpLoad, OpStore, OpCopyMemory,
  266. // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
  267. // OpCooperativeMatrixStoreNV.
  268. uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
  269. uint32_t mask_index) {
  270. assert(mask & SpvMemoryAccessMakePointerVisibleKHRMask);
  271. uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerVisibleKHRMask);
  272. uint32_t index =
  273. mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  274. return inst->GetOperandAs<uint32_t>(index);
  275. }
  276. bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
  277. for (size_t member_index = 1; member_index < inst->operands().size();
  278. ++member_index) {
  279. const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
  280. const auto member_type = _.FindDef(member_id);
  281. if (member_type->opcode() == SpvOpTypeRuntimeArray) return true;
  282. }
  283. return false;
  284. }
  285. spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
  286. uint32_t index) {
  287. SpvStorageClass dst_sc, src_sc;
  288. std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
  289. if (inst->operands().size() <= index) {
  290. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  291. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  292. return _.diag(SPV_ERROR_INVALID_ID, inst)
  293. << "Memory accesses with PhysicalStorageBufferEXT must use "
  294. "Aligned.";
  295. }
  296. return SPV_SUCCESS;
  297. }
  298. const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
  299. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
  300. if (inst->opcode() == SpvOpLoad ||
  301. inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  302. return _.diag(SPV_ERROR_INVALID_ID, inst)
  303. << "MakePointerAvailableKHR cannot be used with OpLoad.";
  304. }
  305. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  306. return _.diag(SPV_ERROR_INVALID_ID, inst)
  307. << "NonPrivatePointerKHR must be specified if "
  308. "MakePointerAvailableKHR is specified.";
  309. }
  310. // Check the associated scope for MakeAvailableKHR.
  311. const auto available_scope = GetMakeAvailableScope(inst, mask, index);
  312. if (auto error = ValidateMemoryScope(_, inst, available_scope))
  313. return error;
  314. }
  315. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
  316. if (inst->opcode() == SpvOpStore ||
  317. inst->opcode() == SpvOpCooperativeMatrixStoreNV) {
  318. return _.diag(SPV_ERROR_INVALID_ID, inst)
  319. << "MakePointerVisibleKHR cannot be used with OpStore.";
  320. }
  321. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  322. return _.diag(SPV_ERROR_INVALID_ID, inst)
  323. << "NonPrivatePointerKHR must be specified if "
  324. << "MakePointerVisibleKHR is specified.";
  325. }
  326. // Check the associated scope for MakeVisibleKHR.
  327. const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
  328. if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
  329. }
  330. if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
  331. if (dst_sc != SpvStorageClassUniform &&
  332. dst_sc != SpvStorageClassWorkgroup &&
  333. dst_sc != SpvStorageClassCrossWorkgroup &&
  334. dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
  335. dst_sc != SpvStorageClassStorageBuffer &&
  336. dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  337. return _.diag(SPV_ERROR_INVALID_ID, inst)
  338. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  339. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  340. << "storage classes.";
  341. }
  342. if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
  343. src_sc != SpvStorageClassWorkgroup &&
  344. src_sc != SpvStorageClassCrossWorkgroup &&
  345. src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
  346. src_sc != SpvStorageClassStorageBuffer &&
  347. src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  348. return _.diag(SPV_ERROR_INVALID_ID, inst)
  349. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  350. << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  351. << "storage classes.";
  352. }
  353. }
  354. if (!(mask & SpvMemoryAccessAlignedMask)) {
  355. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  356. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  357. return _.diag(SPV_ERROR_INVALID_ID, inst)
  358. << "Memory accesses with PhysicalStorageBufferEXT must use "
  359. "Aligned.";
  360. }
  361. }
  362. return SPV_SUCCESS;
  363. }
  364. spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
  365. auto result_type = _.FindDef(inst->type_id());
  366. if (!result_type || result_type->opcode() != SpvOpTypePointer) {
  367. return _.diag(SPV_ERROR_INVALID_ID, inst)
  368. << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
  369. << "' is not a pointer type.";
  370. }
  371. const auto initializer_index = 3;
  372. const auto storage_class_index = 2;
  373. if (initializer_index < inst->operands().size()) {
  374. const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
  375. const auto initializer = _.FindDef(initializer_id);
  376. const auto is_module_scope_var =
  377. initializer && (initializer->opcode() == SpvOpVariable) &&
  378. (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
  379. SpvStorageClassFunction);
  380. const auto is_constant =
  381. initializer && spvOpcodeIsConstant(initializer->opcode());
  382. if (!initializer || !(is_constant || is_module_scope_var)) {
  383. return _.diag(SPV_ERROR_INVALID_ID, inst)
  384. << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
  385. << "' is not a constant or module-scope variable.";
  386. }
  387. if (initializer->type_id() != result_type->GetOperandAs<uint32_t>(2u)) {
  388. return _.diag(SPV_ERROR_INVALID_ID, inst)
  389. << "Initializer type must match the type pointed to by the Result "
  390. "Type";
  391. }
  392. }
  393. auto storage_class = inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  394. if (storage_class != SpvStorageClassWorkgroup &&
  395. storage_class != SpvStorageClassCrossWorkgroup &&
  396. storage_class != SpvStorageClassPrivate &&
  397. storage_class != SpvStorageClassFunction &&
  398. storage_class != SpvStorageClassRayPayloadNV &&
  399. storage_class != SpvStorageClassIncomingRayPayloadNV &&
  400. storage_class != SpvStorageClassHitAttributeNV &&
  401. storage_class != SpvStorageClassCallableDataNV &&
  402. storage_class != SpvStorageClassIncomingCallableDataNV) {
  403. const auto storage_index = 2;
  404. const auto storage_id = result_type->GetOperandAs<uint32_t>(storage_index);
  405. const auto storage = _.FindDef(storage_id);
  406. bool storage_input_or_output = storage_class == SpvStorageClassInput ||
  407. storage_class == SpvStorageClassOutput;
  408. bool builtin = false;
  409. if (storage_input_or_output) {
  410. for (const Decoration& decoration : _.id_decorations(inst->id())) {
  411. if (decoration.dec_type() == SpvDecorationBuiltIn) {
  412. builtin = true;
  413. break;
  414. }
  415. }
  416. }
  417. if (!(storage_input_or_output && builtin) &&
  418. ContainsInvalidBool(_, storage, storage_input_or_output)) {
  419. return _.diag(SPV_ERROR_INVALID_ID, inst)
  420. << "If OpTypeBool is stored in conjunction with OpVariable, it "
  421. << "can only be used with non-externally visible shader Storage "
  422. << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
  423. }
  424. }
  425. if (!_.IsValidStorageClass(storage_class)) {
  426. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  427. << "Invalid storage class for target environment";
  428. }
  429. if (storage_class == SpvStorageClassGeneric) {
  430. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  431. << "OpVariable storage class cannot be Generic";
  432. }
  433. if (inst->function() && storage_class != SpvStorageClassFunction) {
  434. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  435. << "Variables must have a function[7] storage class inside"
  436. " of a function";
  437. }
  438. if (!inst->function() && storage_class == SpvStorageClassFunction) {
  439. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  440. << "Variables can not have a function[7] storage class "
  441. "outside of a function";
  442. }
  443. // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  444. // storage class.
  445. const auto result_storage_class_index = 1;
  446. const auto result_storage_class =
  447. result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  448. if (storage_class != result_storage_class) {
  449. return _.diag(SPV_ERROR_INVALID_ID, inst)
  450. << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
  451. << "Its Storage Class operand must be the same as the Storage Class "
  452. << "operand of the result type.";
  453. }
  454. // Variable pointer related restrictions.
  455. const auto pointee = _.FindDef(result_type->word(3));
  456. if (_.addressing_model() == SpvAddressingModelLogical &&
  457. !_.options()->relax_logical_pointer) {
  458. // VariablePointersStorageBuffer is implied by VariablePointers.
  459. if (pointee->opcode() == SpvOpTypePointer) {
  460. if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
  461. return _.diag(SPV_ERROR_INVALID_ID, inst)
  462. << "In Logical addressing, variables may not allocate a pointer "
  463. << "type";
  464. } else if (storage_class != SpvStorageClassFunction &&
  465. storage_class != SpvStorageClassPrivate) {
  466. return _.diag(SPV_ERROR_INVALID_ID, inst)
  467. << "In Logical addressing with variable pointers, variables "
  468. << "that allocate pointers must be in Function or Private "
  469. << "storage classes";
  470. }
  471. }
  472. }
  473. // Vulkan 14.5.1: Check type of PushConstant variables.
  474. // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  475. if (spvIsVulkanEnv(_.context()->target_env)) {
  476. if (storage_class == SpvStorageClassPushConstant) {
  477. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  478. return _.diag(SPV_ERROR_INVALID_ID, inst)
  479. << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
  480. << "' has illegal type.\n"
  481. << "From Vulkan spec, section 14.5.1:\n"
  482. << "Such variables must be typed as OpTypeStruct, "
  483. << "or an array of this type";
  484. }
  485. }
  486. if (storage_class == SpvStorageClassUniformConstant) {
  487. if (!IsAllowedTypeOrArrayOfSame(
  488. _, pointee,
  489. {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
  490. SpvOpTypeAccelerationStructureNV})) {
  491. return _.diag(SPV_ERROR_INVALID_ID, inst)
  492. << "UniformConstant OpVariable <id> '" << _.getIdName(inst->id())
  493. << "' has illegal type.\n"
  494. << "From Vulkan spec, section 14.5.2:\n"
  495. << "Variables identified with the UniformConstant storage class "
  496. << "are used only as handles to refer to opaque resources. Such "
  497. << "variables must be typed as OpTypeImage, OpTypeSampler, "
  498. << "OpTypeSampledImage, OpTypeAccelerationStructureNV, "
  499. << "or an array of one of these types.";
  500. }
  501. }
  502. if (storage_class == SpvStorageClassUniform) {
  503. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  504. return _.diag(SPV_ERROR_INVALID_ID, inst)
  505. << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
  506. << "' has illegal type.\n"
  507. << "From Vulkan spec, section 14.5.2:\n"
  508. << "Variables identified with the Uniform storage class are "
  509. << "used to access transparent buffer backed resources. Such "
  510. << "variables must be typed as OpTypeStruct, or an array of "
  511. << "this type";
  512. }
  513. }
  514. if (storage_class == SpvStorageClassStorageBuffer) {
  515. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  516. return _.diag(SPV_ERROR_INVALID_ID, inst)
  517. << "StorageBuffer OpVariable <id> '" << _.getIdName(inst->id())
  518. << "' has illegal type.\n"
  519. << "From Vulkan spec, section 14.5.2:\n"
  520. << "Variables identified with the StorageBuffer storage class "
  521. "are used to access transparent buffer backed resources. "
  522. "Such variables must be typed as OpTypeStruct, or an array "
  523. "of this type";
  524. }
  525. }
  526. }
  527. // WebGPU & Vulkan Appendix A: Check that if contains initializer, then
  528. // storage class is Output, Private, or Function.
  529. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
  530. storage_class != SpvStorageClassPrivate &&
  531. storage_class != SpvStorageClassFunction) {
  532. if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) {
  533. return _.diag(SPV_ERROR_INVALID_ID, inst)
  534. << "OpVariable, <id> '" << _.getIdName(inst->id())
  535. << "', has a disallowed initializer & storage class "
  536. << "combination.\n"
  537. << "From " << spvLogStringForEnv(_.context()->target_env)
  538. << " spec:\n"
  539. << "Variable declarations that include initializers must have "
  540. << "one of the following storage classes: Output, Private, or "
  541. << "Function";
  542. }
  543. }
  544. // WebGPU: All variables with storage class Output, Private, or Function MUST
  545. // have an initializer.
  546. if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 &&
  547. (storage_class == SpvStorageClassOutput ||
  548. storage_class == SpvStorageClassPrivate ||
  549. storage_class == SpvStorageClassFunction)) {
  550. return _.diag(SPV_ERROR_INVALID_ID, inst)
  551. << "OpVariable, <id> '" << _.getIdName(inst->id())
  552. << "', must have an initializer.\n"
  553. << "From WebGPU execution environment spec:\n"
  554. << "All variables in the following storage classes must have an "
  555. << "initializer: Output, Private, or Function";
  556. }
  557. if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
  558. return _.diag(SPV_ERROR_INVALID_ID, inst)
  559. << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  560. }
  561. auto pointee_base = pointee;
  562. while (pointee_base->opcode() == SpvOpTypeArray) {
  563. pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  564. }
  565. if (pointee_base->opcode() == SpvOpTypePointer) {
  566. if (pointee_base->GetOperandAs<uint32_t>(1u) ==
  567. SpvStorageClassPhysicalStorageBufferEXT) {
  568. // check for AliasedPointerEXT/RestrictPointerEXT
  569. bool foundAliased =
  570. _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
  571. bool foundRestrict =
  572. _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
  573. if (!foundAliased && !foundRestrict) {
  574. return _.diag(SPV_ERROR_INVALID_ID, inst)
  575. << "OpVariable " << inst->id()
  576. << ": expected AliasedPointerEXT or RestrictPointerEXT for "
  577. << "PhysicalStorageBufferEXT pointer.";
  578. }
  579. if (foundAliased && foundRestrict) {
  580. return _.diag(SPV_ERROR_INVALID_ID, inst)
  581. << "OpVariable " << inst->id()
  582. << ": can't specify both AliasedPointerEXT and "
  583. << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
  584. }
  585. }
  586. }
  587. // Vulkan specific validation rules for OpTypeRuntimeArray
  588. const auto type_index = 2;
  589. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  590. auto value_type = _.FindDef(value_id);
  591. if (spvIsVulkanEnv(_.context()->target_env)) {
  592. // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
  593. // so should never appear as a bare variable.
  594. // Unless the module has the RuntimeDescriptorArrayEXT capability.
  595. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  596. if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
  597. return _.diag(SPV_ERROR_INVALID_ID, inst)
  598. << "OpVariable, <id> '" << _.getIdName(inst->id())
  599. << "', is attempting to create memory for an illegal type, "
  600. << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
  601. << "appear as the final member of an OpTypeStruct, thus cannot "
  602. << "be instantiated via OpVariable";
  603. } else {
  604. // A bare variable OpTypeRuntimeArray is allowed in this context, but
  605. // still need to check the storage class.
  606. if (storage_class != SpvStorageClassStorageBuffer &&
  607. storage_class != SpvStorageClassUniform &&
  608. storage_class != SpvStorageClassUniformConstant) {
  609. return _.diag(SPV_ERROR_INVALID_ID, inst)
  610. << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
  611. << "containing OpTypeRuntimeArray must have storage class of "
  612. << "StorageBuffer, Uniform, or UniformConstant.";
  613. }
  614. }
  615. }
  616. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  617. // must either have the storage class StorageBuffer and be decorated
  618. // with Block, or it must be in the Uniform storage class and be decorated
  619. // as BufferBlock.
  620. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  621. if (DoesStructContainRTA(_, value_type)) {
  622. if (storage_class == SpvStorageClassStorageBuffer) {
  623. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  624. return _.diag(SPV_ERROR_INVALID_ID, inst)
  625. << "For Vulkan, an OpTypeStruct variable containing an "
  626. << "OpTypeRuntimeArray must be decorated with Block if it "
  627. << "has storage class StorageBuffer.";
  628. }
  629. } else if (storage_class == SpvStorageClassUniform) {
  630. if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
  631. return _.diag(SPV_ERROR_INVALID_ID, inst)
  632. << "For Vulkan, an OpTypeStruct variable containing an "
  633. << "OpTypeRuntimeArray must be decorated with BufferBlock "
  634. << "if it has storage class Uniform.";
  635. }
  636. } else {
  637. return _.diag(SPV_ERROR_INVALID_ID, inst)
  638. << "For Vulkan, OpTypeStruct variables containing "
  639. << "OpTypeRuntimeArray must have storage class of "
  640. << "StorageBuffer or Uniform.";
  641. }
  642. }
  643. }
  644. }
  645. // WebGPU specific validation rules for OpTypeRuntimeArray
  646. if (spvIsWebGPUEnv(_.context()->target_env)) {
  647. // OpTypeRuntimeArray should only ever be in an OpTypeStruct,
  648. // so should never appear as a bare variable.
  649. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  650. return _.diag(SPV_ERROR_INVALID_ID, inst)
  651. << "OpVariable, <id> '" << _.getIdName(inst->id())
  652. << "', is attempting to create memory for an illegal type, "
  653. << "OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray can only "
  654. << "appear as the final member of an OpTypeStruct, thus cannot "
  655. << "be instantiated via OpVariable";
  656. }
  657. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  658. // must have the storage class StorageBuffer and be decorated
  659. // with Block.
  660. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  661. if (DoesStructContainRTA(_, value_type)) {
  662. if (storage_class == SpvStorageClassStorageBuffer) {
  663. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  664. return _.diag(SPV_ERROR_INVALID_ID, inst)
  665. << "For WebGPU, an OpTypeStruct variable containing an "
  666. << "OpTypeRuntimeArray must be decorated with Block if it "
  667. << "has storage class StorageBuffer.";
  668. }
  669. } else {
  670. return _.diag(SPV_ERROR_INVALID_ID, inst)
  671. << "For WebGPU, OpTypeStruct variables containing "
  672. << "OpTypeRuntimeArray must have storage class of "
  673. << "StorageBuffer";
  674. }
  675. }
  676. }
  677. }
  678. // Cooperative matrix types can only be allocated in Function or Private
  679. if ((storage_class != SpvStorageClassFunction &&
  680. storage_class != SpvStorageClassPrivate) &&
  681. ContainsCooperativeMatrix(_, pointee)) {
  682. return _.diag(SPV_ERROR_INVALID_ID, inst)
  683. << "Cooperative matrix types (or types containing them) can only be "
  684. "allocated "
  685. << "in Function or Private storage classes or as function "
  686. "parameters";
  687. }
  688. if (_.HasCapability(SpvCapabilityShader)) {
  689. // Don't allow variables containing 16-bit elements without the appropriate
  690. // capabilities.
  691. if ((!_.HasCapability(SpvCapabilityInt16) &&
  692. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 16)) ||
  693. (!_.HasCapability(SpvCapabilityFloat16) &&
  694. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeFloat, 16))) {
  695. auto underlying_type = value_type;
  696. while (underlying_type->opcode() == SpvOpTypePointer) {
  697. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  698. underlying_type =
  699. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  700. }
  701. bool storage_class_ok = true;
  702. std::string sc_name = _.grammar().lookupOperandName(
  703. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  704. switch (storage_class) {
  705. case SpvStorageClassStorageBuffer:
  706. case SpvStorageClassPhysicalStorageBufferEXT:
  707. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess)) {
  708. storage_class_ok = false;
  709. }
  710. break;
  711. case SpvStorageClassUniform:
  712. if (!_.HasCapability(
  713. SpvCapabilityUniformAndStorageBuffer16BitAccess)) {
  714. if (underlying_type->opcode() == SpvOpTypeArray ||
  715. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  716. underlying_type =
  717. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  718. }
  719. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess) ||
  720. !_.HasDecoration(underlying_type->id(),
  721. SpvDecorationBufferBlock)) {
  722. storage_class_ok = false;
  723. }
  724. }
  725. break;
  726. case SpvStorageClassPushConstant:
  727. if (!_.HasCapability(SpvCapabilityStoragePushConstant16)) {
  728. storage_class_ok = false;
  729. }
  730. break;
  731. case SpvStorageClassInput:
  732. case SpvStorageClassOutput:
  733. if (!_.HasCapability(SpvCapabilityStorageInputOutput16)) {
  734. storage_class_ok = false;
  735. }
  736. break;
  737. default:
  738. return _.diag(SPV_ERROR_INVALID_ID, inst)
  739. << "Cannot allocate a variable containing a 16-bit type in "
  740. << sc_name << " storage class";
  741. }
  742. if (!storage_class_ok) {
  743. return _.diag(SPV_ERROR_INVALID_ID, inst)
  744. << "Allocating a variable containing a 16-bit element in "
  745. << sc_name << " storage class requires an additional capability";
  746. }
  747. }
  748. // Don't allow variables containing 8-bit elements without the appropriate
  749. // capabilities.
  750. if (!_.HasCapability(SpvCapabilityInt8) &&
  751. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 8)) {
  752. auto underlying_type = value_type;
  753. while (underlying_type->opcode() == SpvOpTypePointer) {
  754. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  755. underlying_type =
  756. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  757. }
  758. bool storage_class_ok = true;
  759. std::string sc_name = _.grammar().lookupOperandName(
  760. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  761. switch (storage_class) {
  762. case SpvStorageClassStorageBuffer:
  763. case SpvStorageClassPhysicalStorageBufferEXT:
  764. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess)) {
  765. storage_class_ok = false;
  766. }
  767. break;
  768. case SpvStorageClassUniform:
  769. if (!_.HasCapability(
  770. SpvCapabilityUniformAndStorageBuffer8BitAccess)) {
  771. if (underlying_type->opcode() == SpvOpTypeArray ||
  772. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  773. underlying_type =
  774. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  775. }
  776. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess) ||
  777. !_.HasDecoration(underlying_type->id(),
  778. SpvDecorationBufferBlock)) {
  779. storage_class_ok = false;
  780. }
  781. }
  782. break;
  783. case SpvStorageClassPushConstant:
  784. if (!_.HasCapability(SpvCapabilityStoragePushConstant8)) {
  785. storage_class_ok = false;
  786. }
  787. break;
  788. default:
  789. return _.diag(SPV_ERROR_INVALID_ID, inst)
  790. << "Cannot allocate a variable containing a 8-bit type in "
  791. << sc_name << " storage class";
  792. }
  793. if (!storage_class_ok) {
  794. return _.diag(SPV_ERROR_INVALID_ID, inst)
  795. << "Allocating a variable containing a 8-bit element in "
  796. << sc_name << " storage class requires an additional capability";
  797. }
  798. }
  799. }
  800. return SPV_SUCCESS;
  801. }
  802. spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  803. const auto result_type = _.FindDef(inst->type_id());
  804. if (!result_type) {
  805. return _.diag(SPV_ERROR_INVALID_ID, inst)
  806. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  807. << "' is not defined.";
  808. }
  809. const bool uses_variable_pointers =
  810. _.features().variable_pointers ||
  811. _.features().variable_pointers_storage_buffer;
  812. const auto pointer_index = 2;
  813. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  814. const auto pointer = _.FindDef(pointer_id);
  815. if (!pointer ||
  816. ((_.addressing_model() == SpvAddressingModelLogical) &&
  817. ((!uses_variable_pointers &&
  818. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  819. (uses_variable_pointers &&
  820. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  821. return _.diag(SPV_ERROR_INVALID_ID, inst)
  822. << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
  823. << "' is not a logical pointer.";
  824. }
  825. const auto pointer_type = _.FindDef(pointer->type_id());
  826. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  827. return _.diag(SPV_ERROR_INVALID_ID, inst)
  828. << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
  829. << "' is not a pointer type.";
  830. }
  831. const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  832. if (!pointee_type || result_type->id() != pointee_type->id()) {
  833. return _.diag(SPV_ERROR_INVALID_ID, inst)
  834. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  835. << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
  836. << "'s type.";
  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