validate_memory.cpp 66 KB

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