validate_memory.cpp 55 KB

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