validate_memory.cpp 68 KB

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