validate_memory.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  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 initializer_index = 3;
  374. const auto storage_class_index = 2;
  375. if (initializer_index < inst->operands().size()) {
  376. const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
  377. const auto initializer = _.FindDef(initializer_id);
  378. const auto is_module_scope_var =
  379. initializer && (initializer->opcode() == SpvOpVariable) &&
  380. (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
  381. SpvStorageClassFunction);
  382. const auto is_constant =
  383. initializer && spvOpcodeIsConstant(initializer->opcode());
  384. if (!initializer || !(is_constant || is_module_scope_var)) {
  385. return _.diag(SPV_ERROR_INVALID_ID, inst)
  386. << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
  387. << "' is not a constant or module-scope variable.";
  388. }
  389. if (initializer->type_id() != result_type->GetOperandAs<uint32_t>(2u)) {
  390. return _.diag(SPV_ERROR_INVALID_ID, inst)
  391. << "Initializer type must match the type pointed to by the Result "
  392. "Type";
  393. }
  394. }
  395. auto storage_class = inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  396. if (storage_class != SpvStorageClassWorkgroup &&
  397. storage_class != SpvStorageClassCrossWorkgroup &&
  398. storage_class != SpvStorageClassPrivate &&
  399. storage_class != SpvStorageClassFunction &&
  400. storage_class != SpvStorageClassRayPayloadNV &&
  401. storage_class != SpvStorageClassIncomingRayPayloadNV &&
  402. storage_class != SpvStorageClassHitAttributeNV &&
  403. storage_class != SpvStorageClassCallableDataNV &&
  404. storage_class != SpvStorageClassIncomingCallableDataNV) {
  405. const auto storage_index = 2;
  406. const auto storage_id = result_type->GetOperandAs<uint32_t>(storage_index);
  407. const auto storage = _.FindDef(storage_id);
  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(_, storage, 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. << "Invalid storage class for target environment";
  430. }
  431. if (storage_class == SpvStorageClassGeneric) {
  432. return _.diag(SPV_ERROR_INVALID_BINARY, inst)
  433. << "OpVariable storage class cannot be Generic";
  434. }
  435. if (inst->function() && storage_class != SpvStorageClassFunction) {
  436. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  437. << "Variables must have a function[7] storage class inside"
  438. " of a function";
  439. }
  440. if (!inst->function() && storage_class == SpvStorageClassFunction) {
  441. return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
  442. << "Variables can not have a function[7] storage class "
  443. "outside of a function";
  444. }
  445. // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  446. // storage class.
  447. const auto result_storage_class_index = 1;
  448. const auto result_storage_class =
  449. result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  450. if (storage_class != result_storage_class) {
  451. return _.diag(SPV_ERROR_INVALID_ID, inst)
  452. << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
  453. << "Its Storage Class operand must be the same as the Storage Class "
  454. << "operand of the result type.";
  455. }
  456. // Variable pointer related restrictions.
  457. const auto pointee = _.FindDef(result_type->word(3));
  458. if (_.addressing_model() == SpvAddressingModelLogical &&
  459. !_.options()->relax_logical_pointer) {
  460. // VariablePointersStorageBuffer is implied by VariablePointers.
  461. if (pointee->opcode() == SpvOpTypePointer) {
  462. if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
  463. return _.diag(SPV_ERROR_INVALID_ID, inst)
  464. << "In Logical addressing, variables may not allocate a pointer "
  465. << "type";
  466. } else if (storage_class != SpvStorageClassFunction &&
  467. storage_class != SpvStorageClassPrivate) {
  468. return _.diag(SPV_ERROR_INVALID_ID, inst)
  469. << "In Logical addressing with variable pointers, variables "
  470. << "that allocate pointers must be in Function or Private "
  471. << "storage classes";
  472. }
  473. }
  474. }
  475. // Vulkan 14.5.1: Check type of PushConstant variables.
  476. // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  477. if (spvIsVulkanEnv(_.context()->target_env)) {
  478. if (storage_class == SpvStorageClassPushConstant) {
  479. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  480. return _.diag(SPV_ERROR_INVALID_ID, inst)
  481. << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
  482. << "' has illegal type.\n"
  483. << "From Vulkan spec, section 14.5.1:\n"
  484. << "Such variables must be typed as OpTypeStruct, "
  485. << "or an array of this type";
  486. }
  487. }
  488. if (storage_class == SpvStorageClassUniformConstant) {
  489. if (!IsAllowedTypeOrArrayOfSame(
  490. _, pointee,
  491. {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
  492. SpvOpTypeAccelerationStructureNV,
  493. SpvOpTypeAccelerationStructureKHR, SpvOpTypeRayQueryKHR})) {
  494. return _.diag(SPV_ERROR_INVALID_ID, inst)
  495. << "UniformConstant OpVariable <id> '" << _.getIdName(inst->id())
  496. << "' has illegal type.\n"
  497. << "From Vulkan spec, section 14.5.2:\n"
  498. << "Variables identified with the UniformConstant storage class "
  499. << "are used only as handles to refer to opaque resources. Such "
  500. << "variables must be typed as OpTypeImage, OpTypeSampler, "
  501. << "OpTypeSampledImage, OpTypeAccelerationStructureNV, "
  502. "OpTypeAccelerationStructureKHR, "
  503. "OpTypeRayQueryKHR, "
  504. << "or an array of one of these types.";
  505. }
  506. }
  507. if (storage_class == SpvStorageClassUniform) {
  508. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  509. return _.diag(SPV_ERROR_INVALID_ID, inst)
  510. << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
  511. << "' has illegal type.\n"
  512. << "From Vulkan spec, section 14.5.2:\n"
  513. << "Variables identified with the Uniform storage class are "
  514. << "used to access transparent buffer backed resources. Such "
  515. << "variables must be typed as OpTypeStruct, or an array of "
  516. << "this type";
  517. }
  518. }
  519. if (storage_class == SpvStorageClassStorageBuffer) {
  520. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  521. return _.diag(SPV_ERROR_INVALID_ID, inst)
  522. << "StorageBuffer OpVariable <id> '" << _.getIdName(inst->id())
  523. << "' has illegal type.\n"
  524. << "From Vulkan spec, section 14.5.2:\n"
  525. << "Variables identified with the StorageBuffer storage class "
  526. "are used to access transparent buffer backed resources. "
  527. "Such variables must be typed as OpTypeStruct, or an array "
  528. "of this type";
  529. }
  530. }
  531. }
  532. // WebGPU & Vulkan Appendix A: Check that if contains initializer, then
  533. // storage class is Output, Private, or Function.
  534. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
  535. storage_class != SpvStorageClassPrivate &&
  536. storage_class != SpvStorageClassFunction) {
  537. if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) {
  538. return _.diag(SPV_ERROR_INVALID_ID, inst)
  539. << "OpVariable, <id> '" << _.getIdName(inst->id())
  540. << "', has a disallowed initializer & storage class "
  541. << "combination.\n"
  542. << "From " << spvLogStringForEnv(_.context()->target_env)
  543. << " spec:\n"
  544. << "Variable declarations that include initializers must have "
  545. << "one of the following storage classes: Output, Private, or "
  546. << "Function";
  547. }
  548. }
  549. // WebGPU: All variables with storage class Output, Private, or Function MUST
  550. // have an initializer.
  551. if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 &&
  552. (storage_class == SpvStorageClassOutput ||
  553. storage_class == SpvStorageClassPrivate ||
  554. storage_class == SpvStorageClassFunction)) {
  555. return _.diag(SPV_ERROR_INVALID_ID, inst)
  556. << "OpVariable, <id> '" << _.getIdName(inst->id())
  557. << "', must have an initializer.\n"
  558. << "From WebGPU execution environment spec:\n"
  559. << "All variables in the following storage classes must have an "
  560. << "initializer: Output, Private, or Function";
  561. }
  562. if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
  563. return _.diag(SPV_ERROR_INVALID_ID, inst)
  564. << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  565. }
  566. auto pointee_base = pointee;
  567. while (pointee_base->opcode() == SpvOpTypeArray) {
  568. pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  569. }
  570. if (pointee_base->opcode() == SpvOpTypePointer) {
  571. if (pointee_base->GetOperandAs<uint32_t>(1u) ==
  572. SpvStorageClassPhysicalStorageBufferEXT) {
  573. // check for AliasedPointerEXT/RestrictPointerEXT
  574. bool foundAliased =
  575. _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
  576. bool foundRestrict =
  577. _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
  578. if (!foundAliased && !foundRestrict) {
  579. return _.diag(SPV_ERROR_INVALID_ID, inst)
  580. << "OpVariable " << inst->id()
  581. << ": expected AliasedPointerEXT or RestrictPointerEXT for "
  582. << "PhysicalStorageBufferEXT pointer.";
  583. }
  584. if (foundAliased && foundRestrict) {
  585. return _.diag(SPV_ERROR_INVALID_ID, inst)
  586. << "OpVariable " << inst->id()
  587. << ": can't specify both AliasedPointerEXT and "
  588. << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
  589. }
  590. }
  591. }
  592. // Vulkan specific validation rules for OpTypeRuntimeArray
  593. const auto type_index = 2;
  594. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  595. auto value_type = _.FindDef(value_id);
  596. if (spvIsVulkanEnv(_.context()->target_env)) {
  597. // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
  598. // so should never appear as a bare variable.
  599. // Unless the module has the RuntimeDescriptorArrayEXT capability.
  600. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  601. if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
  602. return _.diag(SPV_ERROR_INVALID_ID, inst)
  603. << "OpVariable, <id> '" << _.getIdName(inst->id())
  604. << "', is attempting to create memory for an illegal type, "
  605. << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
  606. << "appear as the final member of an OpTypeStruct, thus cannot "
  607. << "be instantiated via OpVariable";
  608. } else {
  609. // A bare variable OpTypeRuntimeArray is allowed in this context, but
  610. // still need to check the storage class.
  611. if (storage_class != SpvStorageClassStorageBuffer &&
  612. storage_class != SpvStorageClassUniform &&
  613. storage_class != SpvStorageClassUniformConstant) {
  614. return _.diag(SPV_ERROR_INVALID_ID, inst)
  615. << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
  616. << "containing OpTypeRuntimeArray must have storage class of "
  617. << "StorageBuffer, Uniform, or UniformConstant.";
  618. }
  619. }
  620. }
  621. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  622. // must either have the storage class StorageBuffer and be decorated
  623. // with Block, or it must be in the Uniform storage class and be decorated
  624. // as BufferBlock.
  625. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  626. if (DoesStructContainRTA(_, value_type)) {
  627. if (storage_class == SpvStorageClassStorageBuffer) {
  628. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  629. return _.diag(SPV_ERROR_INVALID_ID, inst)
  630. << "For Vulkan, an OpTypeStruct variable containing an "
  631. << "OpTypeRuntimeArray must be decorated with Block if it "
  632. << "has storage class StorageBuffer.";
  633. }
  634. } else if (storage_class == SpvStorageClassUniform) {
  635. if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
  636. return _.diag(SPV_ERROR_INVALID_ID, inst)
  637. << "For Vulkan, an OpTypeStruct variable containing an "
  638. << "OpTypeRuntimeArray must be decorated with BufferBlock "
  639. << "if it has storage class Uniform.";
  640. }
  641. } else {
  642. return _.diag(SPV_ERROR_INVALID_ID, inst)
  643. << "For Vulkan, OpTypeStruct variables containing "
  644. << "OpTypeRuntimeArray must have storage class of "
  645. << "StorageBuffer or Uniform.";
  646. }
  647. }
  648. }
  649. }
  650. // WebGPU specific validation rules for OpTypeRuntimeArray
  651. if (spvIsWebGPUEnv(_.context()->target_env)) {
  652. // OpTypeRuntimeArray should only ever be in an OpTypeStruct,
  653. // so should never appear as a bare variable.
  654. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  655. return _.diag(SPV_ERROR_INVALID_ID, inst)
  656. << "OpVariable, <id> '" << _.getIdName(inst->id())
  657. << "', is attempting to create memory for an illegal type, "
  658. << "OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray can only "
  659. << "appear as the final member of an OpTypeStruct, thus cannot "
  660. << "be instantiated via OpVariable";
  661. }
  662. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  663. // must have the storage class StorageBuffer and be decorated
  664. // with Block.
  665. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  666. if (DoesStructContainRTA(_, value_type)) {
  667. if (storage_class == SpvStorageClassStorageBuffer) {
  668. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  669. return _.diag(SPV_ERROR_INVALID_ID, inst)
  670. << "For WebGPU, an OpTypeStruct variable containing an "
  671. << "OpTypeRuntimeArray must be decorated with Block if it "
  672. << "has storage class StorageBuffer.";
  673. }
  674. } else {
  675. return _.diag(SPV_ERROR_INVALID_ID, inst)
  676. << "For WebGPU, OpTypeStruct variables containing "
  677. << "OpTypeRuntimeArray must have storage class of "
  678. << "StorageBuffer";
  679. }
  680. }
  681. }
  682. }
  683. // Cooperative matrix types can only be allocated in Function or Private
  684. if ((storage_class != SpvStorageClassFunction &&
  685. storage_class != SpvStorageClassPrivate) &&
  686. ContainsCooperativeMatrix(_, pointee)) {
  687. return _.diag(SPV_ERROR_INVALID_ID, inst)
  688. << "Cooperative matrix types (or types containing them) can only be "
  689. "allocated "
  690. << "in Function or Private storage classes or as function "
  691. "parameters";
  692. }
  693. if (_.HasCapability(SpvCapabilityShader)) {
  694. // Don't allow variables containing 16-bit elements without the appropriate
  695. // capabilities.
  696. if ((!_.HasCapability(SpvCapabilityInt16) &&
  697. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 16)) ||
  698. (!_.HasCapability(SpvCapabilityFloat16) &&
  699. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeFloat, 16))) {
  700. auto underlying_type = value_type;
  701. while (underlying_type->opcode() == SpvOpTypePointer) {
  702. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  703. underlying_type =
  704. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  705. }
  706. bool storage_class_ok = true;
  707. std::string sc_name = _.grammar().lookupOperandName(
  708. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  709. switch (storage_class) {
  710. case SpvStorageClassStorageBuffer:
  711. case SpvStorageClassPhysicalStorageBufferEXT:
  712. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess)) {
  713. storage_class_ok = false;
  714. }
  715. break;
  716. case SpvStorageClassUniform:
  717. if (!_.HasCapability(
  718. SpvCapabilityUniformAndStorageBuffer16BitAccess)) {
  719. if (underlying_type->opcode() == SpvOpTypeArray ||
  720. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  721. underlying_type =
  722. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  723. }
  724. if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess) ||
  725. !_.HasDecoration(underlying_type->id(),
  726. SpvDecorationBufferBlock)) {
  727. storage_class_ok = false;
  728. }
  729. }
  730. break;
  731. case SpvStorageClassPushConstant:
  732. if (!_.HasCapability(SpvCapabilityStoragePushConstant16)) {
  733. storage_class_ok = false;
  734. }
  735. break;
  736. case SpvStorageClassInput:
  737. case SpvStorageClassOutput:
  738. if (!_.HasCapability(SpvCapabilityStorageInputOutput16)) {
  739. storage_class_ok = false;
  740. }
  741. break;
  742. default:
  743. return _.diag(SPV_ERROR_INVALID_ID, inst)
  744. << "Cannot allocate a variable containing a 16-bit type in "
  745. << sc_name << " storage class";
  746. }
  747. if (!storage_class_ok) {
  748. return _.diag(SPV_ERROR_INVALID_ID, inst)
  749. << "Allocating a variable containing a 16-bit element in "
  750. << sc_name << " storage class requires an additional capability";
  751. }
  752. }
  753. // Don't allow variables containing 8-bit elements without the appropriate
  754. // capabilities.
  755. if (!_.HasCapability(SpvCapabilityInt8) &&
  756. _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 8)) {
  757. auto underlying_type = value_type;
  758. while (underlying_type->opcode() == SpvOpTypePointer) {
  759. storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
  760. underlying_type =
  761. _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
  762. }
  763. bool storage_class_ok = true;
  764. std::string sc_name = _.grammar().lookupOperandName(
  765. SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
  766. switch (storage_class) {
  767. case SpvStorageClassStorageBuffer:
  768. case SpvStorageClassPhysicalStorageBufferEXT:
  769. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess)) {
  770. storage_class_ok = false;
  771. }
  772. break;
  773. case SpvStorageClassUniform:
  774. if (!_.HasCapability(
  775. SpvCapabilityUniformAndStorageBuffer8BitAccess)) {
  776. if (underlying_type->opcode() == SpvOpTypeArray ||
  777. underlying_type->opcode() == SpvOpTypeRuntimeArray) {
  778. underlying_type =
  779. _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
  780. }
  781. if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess) ||
  782. !_.HasDecoration(underlying_type->id(),
  783. SpvDecorationBufferBlock)) {
  784. storage_class_ok = false;
  785. }
  786. }
  787. break;
  788. case SpvStorageClassPushConstant:
  789. if (!_.HasCapability(SpvCapabilityStoragePushConstant8)) {
  790. storage_class_ok = false;
  791. }
  792. break;
  793. default:
  794. return _.diag(SPV_ERROR_INVALID_ID, inst)
  795. << "Cannot allocate a variable containing a 8-bit type in "
  796. << sc_name << " storage class";
  797. }
  798. if (!storage_class_ok) {
  799. return _.diag(SPV_ERROR_INVALID_ID, inst)
  800. << "Allocating a variable containing a 8-bit element in "
  801. << sc_name << " storage class requires an additional capability";
  802. }
  803. }
  804. }
  805. return SPV_SUCCESS;
  806. }
  807. spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  808. const auto result_type = _.FindDef(inst->type_id());
  809. if (!result_type) {
  810. return _.diag(SPV_ERROR_INVALID_ID, inst)
  811. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  812. << "' is not defined.";
  813. }
  814. const bool uses_variable_pointers =
  815. _.features().variable_pointers ||
  816. _.features().variable_pointers_storage_buffer;
  817. const auto pointer_index = 2;
  818. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  819. const auto pointer = _.FindDef(pointer_id);
  820. if (!pointer ||
  821. ((_.addressing_model() == SpvAddressingModelLogical) &&
  822. ((!uses_variable_pointers &&
  823. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  824. (uses_variable_pointers &&
  825. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  826. return _.diag(SPV_ERROR_INVALID_ID, inst)
  827. << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
  828. << "' is not a logical pointer.";
  829. }
  830. const auto pointer_type = _.FindDef(pointer->type_id());
  831. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  832. return _.diag(SPV_ERROR_INVALID_ID, inst)
  833. << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
  834. << "' is not a pointer type.";
  835. }
  836. const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  837. if (!pointee_type || result_type->id() != pointee_type->id()) {
  838. return _.diag(SPV_ERROR_INVALID_ID, inst)
  839. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  840. << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
  841. << "'s type.";
  842. }
  843. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  844. if (_.HasCapability(SpvCapabilityShader) &&
  845. _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
  846. result_type->opcode() != SpvOpTypePointer) {
  847. if (result_type->opcode() != SpvOpTypeInt &&
  848. result_type->opcode() != SpvOpTypeFloat &&
  849. result_type->opcode() != SpvOpTypeVector &&
  850. result_type->opcode() != SpvOpTypeMatrix) {
  851. return _.diag(SPV_ERROR_INVALID_ID, inst)
  852. << "8- or 16-bit loads must be a scalar, vector or matrix type";
  853. }
  854. }
  855. return SPV_SUCCESS;
  856. }
  857. spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
  858. const bool uses_variable_pointer =
  859. _.features().variable_pointers ||
  860. _.features().variable_pointers_storage_buffer;
  861. const auto pointer_index = 0;
  862. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  863. const auto pointer = _.FindDef(pointer_id);
  864. if (!pointer ||
  865. (_.addressing_model() == SpvAddressingModelLogical &&
  866. ((!uses_variable_pointer &&
  867. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  868. (uses_variable_pointer &&
  869. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  870. return _.diag(SPV_ERROR_INVALID_ID, inst)
  871. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  872. << "' is not a logical pointer.";
  873. }
  874. const auto pointer_type = _.FindDef(pointer->type_id());
  875. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  876. return _.diag(SPV_ERROR_INVALID_ID, inst)
  877. << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
  878. << "' is not a pointer type.";
  879. }
  880. const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
  881. const auto type = _.FindDef(type_id);
  882. if (!type || SpvOpTypeVoid == type->opcode()) {
  883. return _.diag(SPV_ERROR_INVALID_ID, inst)
  884. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  885. << "'s type is void.";
  886. }
  887. // validate storage class
  888. {
  889. uint32_t data_type;
  890. uint32_t storage_class;
  891. if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
  892. return _.diag(SPV_ERROR_INVALID_ID, inst)
  893. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  894. << "' is not pointer type";
  895. }
  896. if (storage_class == SpvStorageClassUniformConstant ||
  897. storage_class == SpvStorageClassInput ||
  898. storage_class == SpvStorageClassPushConstant) {
  899. return _.diag(SPV_ERROR_INVALID_ID, inst)
  900. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  901. << "' storage class is read-only";
  902. }
  903. if (spvIsVulkanEnv(_.context()->target_env) &&
  904. storage_class == SpvStorageClassUniform) {
  905. auto base_ptr = _.TracePointer(pointer);
  906. if (base_ptr->opcode() == SpvOpVariable) {
  907. // If it's not a variable a different check should catch the problem.
  908. auto base_type = _.FindDef(base_ptr->GetOperandAs<uint32_t>(0));
  909. // Get the pointed-to type.
  910. base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(2u));
  911. if (base_type->opcode() == SpvOpTypeArray ||
  912. base_type->opcode() == SpvOpTypeRuntimeArray) {
  913. base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(1u));
  914. }
  915. if (_.HasDecoration(base_type->id(), SpvDecorationBlock)) {
  916. return _.diag(SPV_ERROR_INVALID_ID, inst)
  917. << "In the Vulkan environment, cannot store to Uniform Blocks";
  918. }
  919. }
  920. }
  921. }
  922. const auto object_index = 1;
  923. const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
  924. const auto object = _.FindDef(object_id);
  925. if (!object || !object->type_id()) {
  926. return _.diag(SPV_ERROR_INVALID_ID, inst)
  927. << "OpStore Object <id> '" << _.getIdName(object_id)
  928. << "' is not an object.";
  929. }
  930. const auto object_type = _.FindDef(object->type_id());
  931. if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
  932. return _.diag(SPV_ERROR_INVALID_ID, inst)
  933. << "OpStore Object <id> '" << _.getIdName(object_id)
  934. << "'s type is void.";
  935. }
  936. if (type->id() != object_type->id()) {
  937. if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
  938. object_type->opcode() != SpvOpTypeStruct) {
  939. return _.diag(SPV_ERROR_INVALID_ID, inst)
  940. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  941. << "'s type does not match Object <id> '"
  942. << _.getIdName(object->id()) << "'s type.";
  943. }
  944. // TODO: Check for layout compatible matricies and arrays as well.
  945. if (!AreLayoutCompatibleStructs(_, type, object_type)) {
  946. return _.diag(SPV_ERROR_INVALID_ID, inst)
  947. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  948. << "'s layout does not match Object <id> '"
  949. << _.getIdName(object->id()) << "'s layout.";
  950. }
  951. }
  952. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  953. if (_.HasCapability(SpvCapabilityShader) &&
  954. _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
  955. object_type->opcode() != SpvOpTypePointer) {
  956. if (object_type->opcode() != SpvOpTypeInt &&
  957. object_type->opcode() != SpvOpTypeFloat &&
  958. object_type->opcode() != SpvOpTypeVector &&
  959. object_type->opcode() != SpvOpTypeMatrix) {
  960. return _.diag(SPV_ERROR_INVALID_ID, inst)
  961. << "8- or 16-bit stores must be a scalar, vector or matrix type";
  962. }
  963. }
  964. return SPV_SUCCESS;
  965. }
  966. spv_result_t ValidateCopyMemoryMemoryAccess(ValidationState_t& _,
  967. const Instruction* inst) {
  968. assert(inst->opcode() == SpvOpCopyMemory ||
  969. inst->opcode() == SpvOpCopyMemorySized);
  970. const uint32_t first_access_index = inst->opcode() == SpvOpCopyMemory ? 2 : 3;
  971. if (inst->operands().size() > first_access_index) {
  972. if (auto error = CheckMemoryAccess(_, inst, first_access_index))
  973. return error;
  974. const auto first_access = inst->GetOperandAs<uint32_t>(first_access_index);
  975. const uint32_t second_access_index =
  976. first_access_index + MemoryAccessNumWords(first_access);
  977. if (inst->operands().size() > second_access_index) {
  978. if (_.features().copy_memory_permits_two_memory_accesses) {
  979. if (auto error = CheckMemoryAccess(_, inst, second_access_index))
  980. return error;
  981. // In the two-access form in SPIR-V 1.4 and later:
  982. // - the first is the target (write) access and it can't have
  983. // make-visible.
  984. // - the second is the source (read) access and it can't have
  985. // make-available.
  986. if (first_access & SpvMemoryAccessMakePointerVisibleKHRMask) {
  987. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  988. << "Target memory access must not include "
  989. "MakePointerVisibleKHR";
  990. }
  991. const auto second_access =
  992. inst->GetOperandAs<uint32_t>(second_access_index);
  993. if (second_access & SpvMemoryAccessMakePointerAvailableKHRMask) {
  994. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  995. << "Source memory access must not include "
  996. "MakePointerAvailableKHR";
  997. }
  998. } else {
  999. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  1000. << spvOpcodeString(static_cast<SpvOp>(inst->opcode()))
  1001. << " with two memory access operands requires SPIR-V 1.4 or "
  1002. "later";
  1003. }
  1004. }
  1005. }
  1006. return SPV_SUCCESS;
  1007. }
  1008. spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
  1009. const auto target_index = 0;
  1010. const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
  1011. const auto target = _.FindDef(target_id);
  1012. if (!target) {
  1013. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1014. << "Target operand <id> '" << _.getIdName(target_id)
  1015. << "' is not defined.";
  1016. }
  1017. const auto source_index = 1;
  1018. const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
  1019. const auto source = _.FindDef(source_id);
  1020. if (!source) {
  1021. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1022. << "Source operand <id> '" << _.getIdName(source_id)
  1023. << "' is not defined.";
  1024. }
  1025. const auto target_pointer_type = _.FindDef(target->type_id());
  1026. if (!target_pointer_type ||
  1027. target_pointer_type->opcode() != SpvOpTypePointer) {
  1028. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1029. << "Target operand <id> '" << _.getIdName(target_id)
  1030. << "' is not a pointer.";
  1031. }
  1032. const auto source_pointer_type = _.FindDef(source->type_id());
  1033. if (!source_pointer_type ||
  1034. source_pointer_type->opcode() != SpvOpTypePointer) {
  1035. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1036. << "Source operand <id> '" << _.getIdName(source_id)
  1037. << "' is not a pointer.";
  1038. }
  1039. if (inst->opcode() == SpvOpCopyMemory) {
  1040. const auto target_type =
  1041. _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  1042. if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
  1043. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1044. << "Target operand <id> '" << _.getIdName(target_id)
  1045. << "' cannot be a void pointer.";
  1046. }
  1047. const auto source_type =
  1048. _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
  1049. if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
  1050. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1051. << "Source operand <id> '" << _.getIdName(source_id)
  1052. << "' cannot be a void pointer.";
  1053. }
  1054. if (target_type->id() != source_type->id()) {
  1055. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1056. << "Target <id> '" << _.getIdName(source_id)
  1057. << "'s type does not match Source <id> '"
  1058. << _.getIdName(source_type->id()) << "'s type.";
  1059. }
  1060. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  1061. } else {
  1062. const auto size_id = inst->GetOperandAs<uint32_t>(2);
  1063. const auto size = _.FindDef(size_id);
  1064. if (!size) {
  1065. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1066. << "Size operand <id> '" << _.getIdName(size_id)
  1067. << "' is not defined.";
  1068. }
  1069. const auto size_type = _.FindDef(size->type_id());
  1070. if (!_.IsIntScalarType(size_type->id())) {
  1071. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1072. << "Size operand <id> '" << _.getIdName(size_id)
  1073. << "' must be a scalar integer type.";
  1074. }
  1075. bool is_zero = true;
  1076. switch (size->opcode()) {
  1077. case SpvOpConstantNull:
  1078. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1079. << "Size operand <id> '" << _.getIdName(size_id)
  1080. << "' cannot be a constant zero.";
  1081. case SpvOpConstant:
  1082. if (size_type->word(3) == 1 &&
  1083. size->word(size->words().size() - 1) & 0x80000000) {
  1084. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1085. << "Size operand <id> '" << _.getIdName(size_id)
  1086. << "' cannot have the sign bit set to 1.";
  1087. }
  1088. for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
  1089. is_zero &= (size->word(i) == 0);
  1090. }
  1091. if (is_zero) {
  1092. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1093. << "Size operand <id> '" << _.getIdName(size_id)
  1094. << "' cannot be a constant zero.";
  1095. }
  1096. break;
  1097. default:
  1098. // Cannot infer any other opcodes.
  1099. break;
  1100. }
  1101. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  1102. }
  1103. if (auto error = ValidateCopyMemoryMemoryAccess(_, inst)) return error;
  1104. // Get past the pointers to avoid checking a pointer copy.
  1105. auto sub_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  1106. while (sub_type->opcode() == SpvOpTypePointer) {
  1107. sub_type = _.FindDef(sub_type->GetOperandAs<uint32_t>(2));
  1108. }
  1109. if (_.HasCapability(SpvCapabilityShader) &&
  1110. _.ContainsLimitedUseIntOrFloatType(sub_type->id())) {
  1111. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1112. << "Cannot copy memory of objects containing 8- or 16-bit types";
  1113. }
  1114. return SPV_SUCCESS;
  1115. }
  1116. spv_result_t ValidateAccessChain(ValidationState_t& _,
  1117. const Instruction* inst) {
  1118. std::string instr_name =
  1119. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1120. // The result type must be OpTypePointer.
  1121. auto result_type = _.FindDef(inst->type_id());
  1122. if (SpvOpTypePointer != result_type->opcode()) {
  1123. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1124. << "The Result Type of " << instr_name << " <id> '"
  1125. << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
  1126. << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
  1127. }
  1128. // Result type is a pointer. Find out what it's pointing to.
  1129. // This will be used to make sure the indexing results in the same type.
  1130. // OpTypePointer word 3 is the type being pointed to.
  1131. const auto result_type_pointee = _.FindDef(result_type->word(3));
  1132. // Base must be a pointer, pointing to the base of a composite object.
  1133. const auto base_index = 2;
  1134. const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
  1135. const auto base = _.FindDef(base_id);
  1136. const auto base_type = _.FindDef(base->type_id());
  1137. if (!base_type || SpvOpTypePointer != base_type->opcode()) {
  1138. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1139. << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
  1140. << " instruction must be a pointer.";
  1141. }
  1142. // The result pointer storage class and base pointer storage class must match.
  1143. // Word 2 of OpTypePointer is the Storage Class.
  1144. auto result_type_storage_class = result_type->word(2);
  1145. auto base_type_storage_class = base_type->word(2);
  1146. if (result_type_storage_class != base_type_storage_class) {
  1147. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1148. << "The result pointer storage class and base "
  1149. "pointer storage class in "
  1150. << instr_name << " do not match.";
  1151. }
  1152. // The type pointed to by OpTypePointer (word 3) must be a composite type.
  1153. auto type_pointee = _.FindDef(base_type->word(3));
  1154. // Check Universal Limit (SPIR-V Spec. Section 2.17).
  1155. // The number of indexes passed to OpAccessChain may not exceed 255
  1156. // The instruction includes 4 words + N words (for N indexes)
  1157. size_t num_indexes = inst->words().size() - 4;
  1158. if (inst->opcode() == SpvOpPtrAccessChain ||
  1159. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  1160. // In pointer access chains, the element operand is required, but not
  1161. // counted as an index.
  1162. --num_indexes;
  1163. }
  1164. const size_t num_indexes_limit =
  1165. _.options()->universal_limits_.max_access_chain_indexes;
  1166. if (num_indexes > num_indexes_limit) {
  1167. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1168. << "The number of indexes in " << instr_name << " may not exceed "
  1169. << num_indexes_limit << ". Found " << num_indexes << " indexes.";
  1170. }
  1171. // Indexes walk the type hierarchy to the desired depth, potentially down to
  1172. // scalar granularity. The first index in Indexes will select the top-level
  1173. // member/element/component/element of the base composite. All composite
  1174. // constituents use zero-based numbering, as described by their OpType...
  1175. // instruction. The second index will apply similarly to that result, and so
  1176. // on. Once any non-composite type is reached, there must be no remaining
  1177. // (unused) indexes.
  1178. auto starting_index = 4;
  1179. if (inst->opcode() == SpvOpPtrAccessChain ||
  1180. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  1181. ++starting_index;
  1182. }
  1183. for (size_t i = starting_index; i < inst->words().size(); ++i) {
  1184. const uint32_t cur_word = inst->words()[i];
  1185. // Earlier ID checks ensure that cur_word definition exists.
  1186. auto cur_word_instr = _.FindDef(cur_word);
  1187. // The index must be a scalar integer type (See OpAccessChain in the Spec.)
  1188. auto index_type = _.FindDef(cur_word_instr->type_id());
  1189. if (!index_type || SpvOpTypeInt != index_type->opcode()) {
  1190. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1191. << "Indexes passed to " << instr_name
  1192. << " must be of type integer.";
  1193. }
  1194. switch (type_pointee->opcode()) {
  1195. case SpvOpTypeMatrix:
  1196. case SpvOpTypeVector:
  1197. case SpvOpTypeCooperativeMatrixNV:
  1198. case SpvOpTypeArray:
  1199. case SpvOpTypeRuntimeArray: {
  1200. // In OpTypeMatrix, OpTypeVector, SpvOpTypeCooperativeMatrixNV,
  1201. // OpTypeArray, and OpTypeRuntimeArray, word 2 is the Element Type.
  1202. type_pointee = _.FindDef(type_pointee->word(2));
  1203. break;
  1204. }
  1205. case SpvOpTypeStruct: {
  1206. // In case of structures, there is an additional constraint on the
  1207. // index: the index must be an OpConstant.
  1208. if (SpvOpConstant != cur_word_instr->opcode()) {
  1209. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1210. << "The <id> passed to " << instr_name
  1211. << " to index into a "
  1212. "structure must be an OpConstant.";
  1213. }
  1214. // Get the index value from the OpConstant (word 3 of OpConstant).
  1215. // OpConstant could be a signed integer. But it's okay to treat it as
  1216. // unsigned because a negative constant int would never be seen as
  1217. // correct as a struct offset, since structs can't have more than 2
  1218. // billion members.
  1219. const uint32_t cur_index = cur_word_instr->word(3);
  1220. // The index points to the struct member we want, therefore, the index
  1221. // should be less than the number of struct members.
  1222. const uint32_t num_struct_members =
  1223. static_cast<uint32_t>(type_pointee->words().size() - 2);
  1224. if (cur_index >= num_struct_members) {
  1225. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1226. << "Index is out of bounds: " << instr_name
  1227. << " can not find index " << cur_index
  1228. << " into the structure <id> '"
  1229. << _.getIdName(type_pointee->id()) << "'. This structure has "
  1230. << num_struct_members << " members. Largest valid index is "
  1231. << num_struct_members - 1 << ".";
  1232. }
  1233. // Struct members IDs start at word 2 of OpTypeStruct.
  1234. auto structMemberId = type_pointee->word(cur_index + 2);
  1235. type_pointee = _.FindDef(structMemberId);
  1236. break;
  1237. }
  1238. default: {
  1239. // Give an error. reached non-composite type while indexes still remain.
  1240. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  1241. << instr_name
  1242. << " reached non-composite type while indexes "
  1243. "still remain to be traversed.";
  1244. }
  1245. }
  1246. }
  1247. // At this point, we have fully walked down from the base using the indeces.
  1248. // The type being pointed to should be the same as the result type.
  1249. if (type_pointee->id() != result_type_pointee->id()) {
  1250. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1251. << instr_name << " result type (Op"
  1252. << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
  1253. << ") does not match the type that results from indexing into the "
  1254. "base "
  1255. "<id> (Op"
  1256. << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
  1257. << ").";
  1258. }
  1259. return SPV_SUCCESS;
  1260. }
  1261. spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
  1262. const Instruction* inst) {
  1263. if (_.addressing_model() == SpvAddressingModelLogical) {
  1264. if (!_.features().variable_pointers &&
  1265. !_.features().variable_pointers_storage_buffer) {
  1266. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  1267. << "Generating variable pointers requires capability "
  1268. << "VariablePointers or VariablePointersStorageBuffer";
  1269. }
  1270. }
  1271. return ValidateAccessChain(_, inst);
  1272. }
  1273. spv_result_t ValidateArrayLength(ValidationState_t& state,
  1274. const Instruction* inst) {
  1275. std::string instr_name =
  1276. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1277. // Result type must be a 32-bit unsigned int.
  1278. auto result_type = state.FindDef(inst->type_id());
  1279. if (result_type->opcode() != SpvOpTypeInt ||
  1280. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1281. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1282. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1283. << "The Result Type of " << instr_name << " <id> '"
  1284. << state.getIdName(inst->id())
  1285. << "' must be OpTypeInt with width 32 and signedness 0.";
  1286. }
  1287. // The structure that is passed in must be an pointer to a structure, whose
  1288. // last element is a runtime array.
  1289. auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
  1290. auto pointer_type = state.FindDef(pointer->type_id());
  1291. if (pointer_type->opcode() != SpvOpTypePointer) {
  1292. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1293. << "The Struture's type in " << instr_name << " <id> '"
  1294. << state.getIdName(inst->id())
  1295. << "' must be a pointer to an OpTypeStruct.";
  1296. }
  1297. auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  1298. if (structure_type->opcode() != SpvOpTypeStruct) {
  1299. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1300. << "The Struture's type in " << instr_name << " <id> '"
  1301. << state.getIdName(inst->id())
  1302. << "' must be a pointer to an OpTypeStruct.";
  1303. }
  1304. auto num_of_members = structure_type->operands().size() - 1;
  1305. auto last_member =
  1306. state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
  1307. if (last_member->opcode() != SpvOpTypeRuntimeArray) {
  1308. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1309. << "The Struture's last member in " << instr_name << " <id> '"
  1310. << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
  1311. }
  1312. // The array member must the the index of the last element (the run time
  1313. // array).
  1314. if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
  1315. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1316. << "The array member in " << instr_name << " <id> '"
  1317. << state.getIdName(inst->id())
  1318. << "' must be an the last member of the struct.";
  1319. }
  1320. return SPV_SUCCESS;
  1321. }
  1322. spv_result_t ValidateCooperativeMatrixLengthNV(ValidationState_t& state,
  1323. const Instruction* inst) {
  1324. std::string instr_name =
  1325. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  1326. // Result type must be a 32-bit unsigned int.
  1327. auto result_type = state.FindDef(inst->type_id());
  1328. if (result_type->opcode() != SpvOpTypeInt ||
  1329. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  1330. result_type->GetOperandAs<uint32_t>(2) != 0) {
  1331. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1332. << "The Result Type of " << instr_name << " <id> '"
  1333. << state.getIdName(inst->id())
  1334. << "' must be OpTypeInt with width 32 and signedness 0.";
  1335. }
  1336. auto type_id = inst->GetOperandAs<uint32_t>(2);
  1337. auto type = state.FindDef(type_id);
  1338. if (type->opcode() != SpvOpTypeCooperativeMatrixNV) {
  1339. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1340. << "The type in " << instr_name << " <id> '"
  1341. << state.getIdName(type_id)
  1342. << "' must be OpTypeCooperativeMatrixNV.";
  1343. }
  1344. return SPV_SUCCESS;
  1345. }
  1346. spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
  1347. const Instruction* inst) {
  1348. uint32_t type_id;
  1349. const char* opname;
  1350. if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  1351. type_id = inst->type_id();
  1352. opname = "SpvOpCooperativeMatrixLoadNV";
  1353. } else {
  1354. // get Object operand's type
  1355. type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
  1356. opname = "SpvOpCooperativeMatrixStoreNV";
  1357. }
  1358. auto matrix_type = _.FindDef(type_id);
  1359. if (matrix_type->opcode() != SpvOpTypeCooperativeMatrixNV) {
  1360. if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
  1361. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1362. << "SpvOpCooperativeMatrixLoadNV Result Type <id> '"
  1363. << _.getIdName(type_id) << "' is not a cooperative matrix type.";
  1364. } else {
  1365. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1366. << "SpvOpCooperativeMatrixStoreNV Object type <id> '"
  1367. << _.getIdName(type_id) << "' is not a cooperative matrix type.";
  1368. }
  1369. }
  1370. const bool uses_variable_pointers =
  1371. _.features().variable_pointers ||
  1372. _.features().variable_pointers_storage_buffer;
  1373. const auto pointer_index =
  1374. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 2u : 0u;
  1375. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  1376. const auto pointer = _.FindDef(pointer_id);
  1377. if (!pointer ||
  1378. ((_.addressing_model() == SpvAddressingModelLogical) &&
  1379. ((!uses_variable_pointers &&
  1380. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  1381. (uses_variable_pointers &&
  1382. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  1383. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1384. << opname << " Pointer <id> '" << _.getIdName(pointer_id)
  1385. << "' is not a logical pointer.";
  1386. }
  1387. const auto pointer_type_id = pointer->type_id();
  1388. const auto pointer_type = _.FindDef(pointer_type_id);
  1389. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  1390. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1391. << opname << " type for pointer <id> '" << _.getIdName(pointer_id)
  1392. << "' is not a pointer type.";
  1393. }
  1394. const auto storage_class_index = 1u;
  1395. const auto storage_class =
  1396. pointer_type->GetOperandAs<uint32_t>(storage_class_index);
  1397. if (storage_class != SpvStorageClassWorkgroup &&
  1398. storage_class != SpvStorageClassStorageBuffer &&
  1399. storage_class != SpvStorageClassPhysicalStorageBufferEXT) {
  1400. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1401. << opname << " storage class for pointer type <id> '"
  1402. << _.getIdName(pointer_type_id)
  1403. << "' is not Workgroup or StorageBuffer.";
  1404. }
  1405. const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
  1406. const auto pointee_type = _.FindDef(pointee_id);
  1407. if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
  1408. _.IsFloatScalarOrVectorType(pointee_id))) {
  1409. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1410. << opname << " Pointer <id> '" << _.getIdName(pointer->id())
  1411. << "'s Type must be a scalar or vector type.";
  1412. }
  1413. const auto stride_index =
  1414. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 3u : 2u;
  1415. const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
  1416. const auto stride = _.FindDef(stride_id);
  1417. if (!stride || !_.IsIntScalarType(stride->type_id())) {
  1418. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1419. << "Stride operand <id> '" << _.getIdName(stride_id)
  1420. << "' must be a scalar integer type.";
  1421. }
  1422. const auto colmajor_index =
  1423. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 4u : 3u;
  1424. const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
  1425. const auto colmajor = _.FindDef(colmajor_id);
  1426. if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
  1427. !(spvOpcodeIsConstant(colmajor->opcode()) ||
  1428. spvOpcodeIsSpecConstant(colmajor->opcode()))) {
  1429. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1430. << "Column Major operand <id> '" << _.getIdName(colmajor_id)
  1431. << "' must be a boolean constant instruction.";
  1432. }
  1433. const auto memory_access_index =
  1434. (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 5u : 4u;
  1435. if (inst->operands().size() > memory_access_index) {
  1436. if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
  1437. return error;
  1438. }
  1439. return SPV_SUCCESS;
  1440. }
  1441. spv_result_t ValidatePtrComparison(ValidationState_t& _,
  1442. const Instruction* inst) {
  1443. if (_.addressing_model() == SpvAddressingModelLogical &&
  1444. !_.features().variable_pointers_storage_buffer) {
  1445. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1446. << "Instruction cannot be used without a variable pointers "
  1447. "capability";
  1448. }
  1449. const auto result_type = _.FindDef(inst->type_id());
  1450. if (inst->opcode() == SpvOpPtrDiff) {
  1451. if (!result_type || result_type->opcode() != SpvOpTypeInt) {
  1452. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1453. << "Result Type must be an integer scalar";
  1454. }
  1455. } else {
  1456. if (!result_type || result_type->opcode() != SpvOpTypeBool) {
  1457. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1458. << "Result Type must be OpTypeBool";
  1459. }
  1460. }
  1461. const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
  1462. const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
  1463. if (!op1 || !op2 || op1->type_id() != op2->type_id()) {
  1464. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1465. << "The types of Operand 1 and Operand 2 must match";
  1466. }
  1467. const auto op1_type = _.FindDef(op1->type_id());
  1468. if (!op1_type || op1_type->opcode() != SpvOpTypePointer) {
  1469. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1470. << "Operand type must be a pointer";
  1471. }
  1472. SpvStorageClass sc = op1_type->GetOperandAs<SpvStorageClass>(1u);
  1473. if (_.addressing_model() == SpvAddressingModelLogical) {
  1474. if (sc != SpvStorageClassWorkgroup && sc != SpvStorageClassStorageBuffer) {
  1475. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1476. << "Invalid pointer storage class";
  1477. }
  1478. if (sc == SpvStorageClassWorkgroup && !_.features().variable_pointers) {
  1479. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1480. << "Workgroup storage class pointer requires VariablePointers "
  1481. "capability to be specified";
  1482. }
  1483. } else if (sc == SpvStorageClassPhysicalStorageBuffer) {
  1484. return _.diag(SPV_ERROR_INVALID_ID, inst)
  1485. << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
  1486. }
  1487. return SPV_SUCCESS;
  1488. }
  1489. } // namespace
  1490. spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
  1491. switch (inst->opcode()) {
  1492. case SpvOpVariable:
  1493. if (auto error = ValidateVariable(_, inst)) return error;
  1494. break;
  1495. case SpvOpLoad:
  1496. if (auto error = ValidateLoad(_, inst)) return error;
  1497. break;
  1498. case SpvOpStore:
  1499. if (auto error = ValidateStore(_, inst)) return error;
  1500. break;
  1501. case SpvOpCopyMemory:
  1502. case SpvOpCopyMemorySized:
  1503. if (auto error = ValidateCopyMemory(_, inst)) return error;
  1504. break;
  1505. case SpvOpPtrAccessChain:
  1506. if (auto error = ValidatePtrAccessChain(_, inst)) return error;
  1507. break;
  1508. case SpvOpAccessChain:
  1509. case SpvOpInBoundsAccessChain:
  1510. case SpvOpInBoundsPtrAccessChain:
  1511. if (auto error = ValidateAccessChain(_, inst)) return error;
  1512. break;
  1513. case SpvOpArrayLength:
  1514. if (auto error = ValidateArrayLength(_, inst)) return error;
  1515. break;
  1516. case SpvOpCooperativeMatrixLoadNV:
  1517. case SpvOpCooperativeMatrixStoreNV:
  1518. if (auto error = ValidateCooperativeMatrixLoadStoreNV(_, inst))
  1519. return error;
  1520. break;
  1521. case SpvOpCooperativeMatrixLengthNV:
  1522. if (auto error = ValidateCooperativeMatrixLengthNV(_, inst)) return error;
  1523. break;
  1524. case SpvOpPtrEqual:
  1525. case SpvOpPtrNotEqual:
  1526. case SpvOpPtrDiff:
  1527. if (auto error = ValidatePtrComparison(_, inst)) return error;
  1528. break;
  1529. case SpvOpImageTexelPointer:
  1530. case SpvOpGenericPtrMemSemantics:
  1531. default:
  1532. break;
  1533. }
  1534. return SPV_SUCCESS;
  1535. }
  1536. } // namespace val
  1537. } // namespace spvtools