validate_memory.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
  182. ValidationState_t& _, const Instruction* inst) {
  183. SpvStorageClass dst_sc = SpvStorageClassMax;
  184. SpvStorageClass src_sc = SpvStorageClassMax;
  185. switch (inst->opcode()) {
  186. case SpvOpLoad: {
  187. auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
  188. auto load_pointer_type = _.FindDef(load_pointer->type_id());
  189. dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
  190. break;
  191. }
  192. case SpvOpStore: {
  193. auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  194. auto store_pointer_type = _.FindDef(store_pointer->type_id());
  195. dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
  196. break;
  197. }
  198. case SpvOpCopyMemory:
  199. case SpvOpCopyMemorySized: {
  200. auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
  201. auto dst_type = _.FindDef(dst->type_id());
  202. dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
  203. auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
  204. auto src_type = _.FindDef(src->type_id());
  205. src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
  206. break;
  207. }
  208. default:
  209. break;
  210. }
  211. return std::make_pair(dst_sc, src_sc);
  212. }
  213. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  214. // OpCopyMemorySized.
  215. uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask) {
  216. uint32_t offset = 1;
  217. if (mask & SpvMemoryAccessAlignedMask) ++offset;
  218. uint32_t scope_id = 0;
  219. switch (inst->opcode()) {
  220. case SpvOpLoad:
  221. case SpvOpCopyMemorySized:
  222. return inst->GetOperandAs<uint32_t>(3 + offset);
  223. case SpvOpStore:
  224. case SpvOpCopyMemory:
  225. return inst->GetOperandAs<uint32_t>(2 + offset);
  226. default:
  227. assert(false && "unexpected opcode");
  228. break;
  229. }
  230. return scope_id;
  231. }
  232. // This function is only called for OpLoad, OpStore, OpCopyMemory and
  233. // OpCopyMemorySized.
  234. uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask) {
  235. uint32_t offset = 1;
  236. if (mask & SpvMemoryAccessAlignedMask) ++offset;
  237. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++offset;
  238. uint32_t scope_id = 0;
  239. switch (inst->opcode()) {
  240. case SpvOpLoad:
  241. case SpvOpCopyMemorySized:
  242. return inst->GetOperandAs<uint32_t>(3 + offset);
  243. case SpvOpStore:
  244. case SpvOpCopyMemory:
  245. return inst->GetOperandAs<uint32_t>(2 + offset);
  246. default:
  247. assert(false && "unexpected opcode");
  248. break;
  249. }
  250. return scope_id;
  251. }
  252. spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
  253. uint32_t index) {
  254. SpvStorageClass dst_sc, src_sc;
  255. std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
  256. if (inst->operands().size() <= index) {
  257. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  258. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  259. return _.diag(SPV_ERROR_INVALID_ID, inst) << "Memory accesses with "
  260. "PhysicalStorageBufferEXT "
  261. "must use Aligned.";
  262. }
  263. return SPV_SUCCESS;
  264. }
  265. uint32_t mask = inst->GetOperandAs<uint32_t>(index);
  266. if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
  267. if (inst->opcode() == SpvOpLoad) {
  268. return _.diag(SPV_ERROR_INVALID_ID, inst)
  269. << "MakePointerAvailableKHR cannot be used with OpLoad.";
  270. }
  271. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  272. return _.diag(SPV_ERROR_INVALID_ID, inst)
  273. << "NonPrivatePointerKHR must be specified if "
  274. "MakePointerAvailableKHR is specified.";
  275. }
  276. // Check the associated scope for MakeAvailableKHR.
  277. const auto available_scope = GetMakeAvailableScope(inst, mask);
  278. if (auto error = ValidateMemoryScope(_, inst, available_scope))
  279. return error;
  280. }
  281. if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
  282. if (inst->opcode() == SpvOpStore) {
  283. return _.diag(SPV_ERROR_INVALID_ID, inst)
  284. << "MakePointerVisibleKHR cannot be used with OpStore.";
  285. }
  286. if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
  287. return _.diag(SPV_ERROR_INVALID_ID, inst)
  288. << "NonPrivatePointerKHR must be specified if "
  289. "MakePointerVisibleKHR is specified.";
  290. }
  291. // Check the associated scope for MakeVisibleKHR.
  292. const auto visible_scope = GetMakeVisibleScope(inst, mask);
  293. if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
  294. }
  295. if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
  296. if (dst_sc != SpvStorageClassUniform &&
  297. dst_sc != SpvStorageClassWorkgroup &&
  298. dst_sc != SpvStorageClassCrossWorkgroup &&
  299. dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
  300. dst_sc != SpvStorageClassStorageBuffer &&
  301. dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  302. return _.diag(SPV_ERROR_INVALID_ID, inst)
  303. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  304. "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  305. "storage classes.";
  306. }
  307. if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
  308. src_sc != SpvStorageClassWorkgroup &&
  309. src_sc != SpvStorageClassCrossWorkgroup &&
  310. src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
  311. src_sc != SpvStorageClassStorageBuffer &&
  312. src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
  313. return _.diag(SPV_ERROR_INVALID_ID, inst)
  314. << "NonPrivatePointerKHR requires a pointer in Uniform, "
  315. "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
  316. "storage classes.";
  317. }
  318. }
  319. if (!(mask & SpvMemoryAccessAlignedMask)) {
  320. if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
  321. dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
  322. return _.diag(SPV_ERROR_INVALID_ID, inst) << "Memory accesses with "
  323. "PhysicalStorageBufferEXT "
  324. "must use Aligned.";
  325. }
  326. }
  327. return SPV_SUCCESS;
  328. }
  329. spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
  330. auto result_type = _.FindDef(inst->type_id());
  331. if (!result_type || result_type->opcode() != SpvOpTypePointer) {
  332. return _.diag(SPV_ERROR_INVALID_ID, inst)
  333. << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
  334. << "' is not a pointer type.";
  335. }
  336. const auto initializer_index = 3;
  337. const auto storage_class_index = 2;
  338. if (initializer_index < inst->operands().size()) {
  339. const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
  340. const auto initializer = _.FindDef(initializer_id);
  341. const auto is_module_scope_var =
  342. initializer && (initializer->opcode() == SpvOpVariable) &&
  343. (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
  344. SpvStorageClassFunction);
  345. const auto is_constant =
  346. initializer && spvOpcodeIsConstant(initializer->opcode());
  347. if (!initializer || !(is_constant || is_module_scope_var)) {
  348. return _.diag(SPV_ERROR_INVALID_ID, inst)
  349. << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
  350. << "' is not a constant or module-scope variable.";
  351. }
  352. }
  353. const auto storage_class =
  354. inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  355. if (storage_class != SpvStorageClassWorkgroup &&
  356. storage_class != SpvStorageClassCrossWorkgroup &&
  357. storage_class != SpvStorageClassPrivate &&
  358. storage_class != SpvStorageClassFunction &&
  359. storage_class != SpvStorageClassRayPayloadNV &&
  360. storage_class != SpvStorageClassIncomingRayPayloadNV &&
  361. storage_class != SpvStorageClassHitAttributeNV &&
  362. storage_class != SpvStorageClassCallableDataNV &&
  363. storage_class != SpvStorageClassIncomingCallableDataNV) {
  364. const auto storage_index = 2;
  365. const auto storage_id = result_type->GetOperandAs<uint32_t>(storage_index);
  366. const auto storage = _.FindDef(storage_id);
  367. bool storage_input_or_output = storage_class == SpvStorageClassInput ||
  368. storage_class == SpvStorageClassOutput;
  369. bool builtin = false;
  370. if (storage_input_or_output) {
  371. for (const Decoration& decoration : _.id_decorations(inst->id())) {
  372. if (decoration.dec_type() == SpvDecorationBuiltIn) {
  373. builtin = true;
  374. break;
  375. }
  376. }
  377. }
  378. if (!(storage_input_or_output && builtin) &&
  379. ContainsInvalidBool(_, storage, storage_input_or_output)) {
  380. return _.diag(SPV_ERROR_INVALID_ID, inst)
  381. << "If OpTypeBool is stored in conjunction with OpVariable, it "
  382. << "can only be used with non-externally visible shader Storage "
  383. << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
  384. }
  385. }
  386. // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  387. // storage class.
  388. const auto result_storage_class_index = 1;
  389. const auto result_storage_class =
  390. result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  391. if (storage_class != result_storage_class) {
  392. return _.diag(SPV_ERROR_INVALID_ID, inst)
  393. << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
  394. << "Its Storage Class operand must be the same as the Storage Class "
  395. << "operand of the result type.";
  396. }
  397. // Variable pointer related restrictions.
  398. const auto pointee = _.FindDef(result_type->word(3));
  399. if (_.addressing_model() == SpvAddressingModelLogical &&
  400. !_.options()->relax_logical_pointer) {
  401. // VariablePointersStorageBuffer is implied by VariablePointers.
  402. if (pointee->opcode() == SpvOpTypePointer) {
  403. if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
  404. return _.diag(SPV_ERROR_INVALID_ID, inst) << "In Logical addressing, "
  405. "variables may not "
  406. "allocate a pointer type";
  407. } else if (storage_class != SpvStorageClassFunction &&
  408. storage_class != SpvStorageClassPrivate) {
  409. return _.diag(SPV_ERROR_INVALID_ID, inst)
  410. << "In Logical addressing with variable pointers, variables "
  411. "that allocate pointers must be in Function or Private "
  412. "storage classes";
  413. }
  414. }
  415. }
  416. // Vulkan 14.5.1: Check type of PushConstant variables.
  417. // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  418. if (spvIsVulkanEnv(_.context()->target_env)) {
  419. if (storage_class == SpvStorageClassPushConstant) {
  420. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  421. return _.diag(SPV_ERROR_INVALID_ID, inst)
  422. << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
  423. << "' has illegal type.\n"
  424. << "From Vulkan spec, section 14.5.1:\n"
  425. << "Such variables must be typed as OpTypeStruct, "
  426. << "or an array of this type";
  427. }
  428. }
  429. if (storage_class == SpvStorageClassUniformConstant) {
  430. if (!IsAllowedTypeOrArrayOfSame(
  431. _, pointee,
  432. {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
  433. SpvOpTypeAccelerationStructureNV})) {
  434. return _.diag(SPV_ERROR_INVALID_ID, inst)
  435. << "UniformConstant OpVariable <id> '" << _.getIdName(inst->id())
  436. << "' has illegal type.\n"
  437. << "From Vulkan spec, section 14.5.2:\n"
  438. << "Variables identified with the UniformConstant storage class "
  439. << "are used only as handles to refer to opaque resources. Such "
  440. << "variables must be typed as OpTypeImage, OpTypeSampler, "
  441. << "OpTypeSampledImage, OpTypeAccelerationStructureNV, "
  442. << "or an array of one of these types.";
  443. }
  444. }
  445. if (storage_class == SpvStorageClassUniform) {
  446. if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
  447. return _.diag(SPV_ERROR_INVALID_ID, inst)
  448. << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
  449. << "' has illegal type.\n"
  450. << "From Vulkan spec, section 14.5.2:\n"
  451. << "Variables identified with the Uniform storage class are "
  452. "used "
  453. << "to access transparent buffer backed resources. Such "
  454. "variables "
  455. << "must be typed as OpTypeStruct, or an array of this type";
  456. }
  457. }
  458. }
  459. // WebGPU & Vulkan Appendix A: Check that if contains initializer, then
  460. // storage class is Output, Private, or Function.
  461. if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
  462. storage_class != SpvStorageClassPrivate &&
  463. storage_class != SpvStorageClassFunction) {
  464. if (spvIsVulkanEnv(_.context()->target_env)) {
  465. return _.diag(SPV_ERROR_INVALID_ID, inst)
  466. << "OpVariable, <id> '" << _.getIdName(inst->id())
  467. << "', has a disallowed initializer & storage class "
  468. << "combination.\n"
  469. << "From Vulkan spec, Appendix A:\n"
  470. << "Variable declarations that include initializers must have "
  471. << "one of the following storage classes: Output, Private, or "
  472. << "Function";
  473. }
  474. if (spvIsWebGPUEnv(_.context()->target_env)) {
  475. return _.diag(SPV_ERROR_INVALID_ID, inst)
  476. << "OpVariable, <id> '" << _.getIdName(inst->id())
  477. << "', has a disallowed initializer & storage class "
  478. << "combination.\n"
  479. << "From WebGPU execution environment spec:\n"
  480. << "Variable declarations that include initializers must have "
  481. << "one of the following storage classes: Output, Private, or "
  482. << "Function";
  483. }
  484. }
  485. // WebGPU: All variables with storage class Output, Private, or Function MUST
  486. // have an initializer.
  487. if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 &&
  488. (storage_class == SpvStorageClassOutput ||
  489. storage_class == SpvStorageClassPrivate ||
  490. storage_class == SpvStorageClassFunction)) {
  491. return _.diag(SPV_ERROR_INVALID_ID, inst)
  492. << "OpVariable, <id> '" << _.getIdName(inst->id())
  493. << "', must have an initializer.\n"
  494. << "From WebGPU execution environment spec:\n"
  495. << "All variables in the following storage classes must have an "
  496. << "initializer: Output, Private, or Function";
  497. }
  498. if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
  499. return _.diag(SPV_ERROR_INVALID_ID, inst)
  500. << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  501. }
  502. auto pointee_base = pointee;
  503. while (pointee_base->opcode() == SpvOpTypeArray) {
  504. pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  505. }
  506. if (pointee_base->opcode() == SpvOpTypePointer) {
  507. if (pointee_base->GetOperandAs<uint32_t>(1u) ==
  508. SpvStorageClassPhysicalStorageBufferEXT) {
  509. // check for AliasedPointerEXT/RestrictPointerEXT
  510. bool foundAliased =
  511. _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
  512. bool foundRestrict =
  513. _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
  514. if (!foundAliased && !foundRestrict) {
  515. return _.diag(SPV_ERROR_INVALID_ID, inst)
  516. << "OpVariable " << inst->id()
  517. << ": expected AliasedPointerEXT or RestrictPointerEXT for "
  518. "PhysicalStorageBufferEXT pointer.";
  519. }
  520. if (foundAliased && foundRestrict) {
  521. return _.diag(SPV_ERROR_INVALID_ID, inst)
  522. << "OpVariable " << inst->id()
  523. << ": can't specify both AliasedPointerEXT and "
  524. "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
  525. }
  526. }
  527. }
  528. // Vulkan specific validation rules for OpTypeRuntimeArray
  529. if (spvIsVulkanEnv(_.context()->target_env)) {
  530. const auto type_index = 2;
  531. const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  532. auto value_type = _.FindDef(value_id);
  533. // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
  534. // so should never appear as a bare variable.
  535. // Unless the module has the RuntimeDescriptorArrayEXT capability.
  536. if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
  537. if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
  538. return _.diag(SPV_ERROR_INVALID_ID, inst)
  539. << "OpVariable, <id> '" << _.getIdName(inst->id())
  540. << "', is attempting to create memory for an illegal type, "
  541. "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
  542. "appear as the final member of an OpTypeStruct, thus cannot "
  543. "be instantiated via OpVariable";
  544. } else {
  545. // A bare variable OpTypeRuntimeArray is allowed in this context, but
  546. // still need to check the storage class.
  547. if (storage_class != SpvStorageClassStorageBuffer &&
  548. storage_class != SpvStorageClassUniform &&
  549. storage_class != SpvStorageClassUniformConstant) {
  550. return _.diag(SPV_ERROR_INVALID_ID, inst)
  551. << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
  552. "containing OpTypeRuntimeArray must have storage class of "
  553. "StorageBuffer, Uniform, or UniformConstant.";
  554. }
  555. }
  556. }
  557. // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
  558. // must either have the storage class StorageBuffer and be decorated
  559. // with Block, or it must be in the Uniform storage class and be decorated
  560. // as BufferBlock.
  561. if (value_type && value_type->opcode() == SpvOpTypeStruct) {
  562. bool contains_RTA = false;
  563. for (size_t member_type_index = 1;
  564. member_type_index < value_type->operands().size();
  565. ++member_type_index) {
  566. const auto member_type_id =
  567. value_type->GetOperandAs<uint32_t>(member_type_index);
  568. const auto member_type = _.FindDef(member_type_id);
  569. if (member_type->opcode() == SpvOpTypeRuntimeArray) {
  570. contains_RTA = true;
  571. break;
  572. }
  573. }
  574. if (contains_RTA) {
  575. if (storage_class == SpvStorageClassStorageBuffer) {
  576. if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
  577. return _.diag(SPV_ERROR_INVALID_ID, inst)
  578. << "For Vulkan, an OpTypeStruct variable containing an "
  579. "OpTypeRuntimeArray must be decorated with Block if it "
  580. "has storage class StorageBuffer.";
  581. }
  582. } else if (storage_class == SpvStorageClassUniform) {
  583. if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
  584. return _.diag(SPV_ERROR_INVALID_ID, inst)
  585. << "For Vulkan, an OpTypeStruct variable containing an "
  586. "OpTypeRuntimeArray must be decorated with BufferBlock "
  587. "if it has storage class Uniform.";
  588. }
  589. } else {
  590. return _.diag(SPV_ERROR_INVALID_ID, inst)
  591. << "For Vulkan, OpTypeStruct variables containing "
  592. "OpTypeRuntimeArray must have storage class of "
  593. "StorageBuffer or Uniform.";
  594. }
  595. }
  596. }
  597. }
  598. return SPV_SUCCESS;
  599. }
  600. spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  601. const auto result_type = _.FindDef(inst->type_id());
  602. if (!result_type) {
  603. return _.diag(SPV_ERROR_INVALID_ID, inst)
  604. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  605. << "' is not defined.";
  606. }
  607. const bool uses_variable_pointers =
  608. _.features().variable_pointers ||
  609. _.features().variable_pointers_storage_buffer;
  610. const auto pointer_index = 2;
  611. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  612. const auto pointer = _.FindDef(pointer_id);
  613. if (!pointer ||
  614. ((_.addressing_model() == SpvAddressingModelLogical) &&
  615. ((!uses_variable_pointers &&
  616. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  617. (uses_variable_pointers &&
  618. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  619. return _.diag(SPV_ERROR_INVALID_ID, inst)
  620. << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
  621. << "' is not a logical pointer.";
  622. }
  623. const auto pointer_type = _.FindDef(pointer->type_id());
  624. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  625. return _.diag(SPV_ERROR_INVALID_ID, inst)
  626. << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
  627. << "' is not a pointer type.";
  628. }
  629. const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  630. if (!pointee_type || result_type->id() != pointee_type->id()) {
  631. return _.diag(SPV_ERROR_INVALID_ID, inst)
  632. << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
  633. << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
  634. << "'s type.";
  635. }
  636. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  637. return SPV_SUCCESS;
  638. }
  639. spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
  640. const bool uses_variable_pointer =
  641. _.features().variable_pointers ||
  642. _.features().variable_pointers_storage_buffer;
  643. const auto pointer_index = 0;
  644. const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  645. const auto pointer = _.FindDef(pointer_id);
  646. if (!pointer ||
  647. (_.addressing_model() == SpvAddressingModelLogical &&
  648. ((!uses_variable_pointer &&
  649. !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
  650. (uses_variable_pointer &&
  651. !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
  652. return _.diag(SPV_ERROR_INVALID_ID, inst)
  653. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  654. << "' is not a logical pointer.";
  655. }
  656. const auto pointer_type = _.FindDef(pointer->type_id());
  657. if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
  658. return _.diag(SPV_ERROR_INVALID_ID, inst)
  659. << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
  660. << "' is not a pointer type.";
  661. }
  662. const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
  663. const auto type = _.FindDef(type_id);
  664. if (!type || SpvOpTypeVoid == type->opcode()) {
  665. return _.diag(SPV_ERROR_INVALID_ID, inst)
  666. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  667. << "'s type is void.";
  668. }
  669. // validate storage class
  670. {
  671. uint32_t data_type;
  672. uint32_t storage_class;
  673. if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
  674. return _.diag(SPV_ERROR_INVALID_ID, inst)
  675. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  676. << "' is not pointer type";
  677. }
  678. if (storage_class == SpvStorageClassUniformConstant ||
  679. storage_class == SpvStorageClassInput ||
  680. storage_class == SpvStorageClassPushConstant) {
  681. return _.diag(SPV_ERROR_INVALID_ID, inst)
  682. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  683. << "' storage class is read-only";
  684. }
  685. }
  686. const auto object_index = 1;
  687. const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
  688. const auto object = _.FindDef(object_id);
  689. if (!object || !object->type_id()) {
  690. return _.diag(SPV_ERROR_INVALID_ID, inst)
  691. << "OpStore Object <id> '" << _.getIdName(object_id)
  692. << "' is not an object.";
  693. }
  694. const auto object_type = _.FindDef(object->type_id());
  695. if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
  696. return _.diag(SPV_ERROR_INVALID_ID, inst)
  697. << "OpStore Object <id> '" << _.getIdName(object_id)
  698. << "'s type is void.";
  699. }
  700. if (type->id() != object_type->id()) {
  701. if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
  702. object_type->opcode() != SpvOpTypeStruct) {
  703. return _.diag(SPV_ERROR_INVALID_ID, inst)
  704. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  705. << "'s type does not match Object <id> '"
  706. << _.getIdName(object->id()) << "'s type.";
  707. }
  708. // TODO: Check for layout compatible matricies and arrays as well.
  709. if (!AreLayoutCompatibleStructs(_, type, object_type)) {
  710. return _.diag(SPV_ERROR_INVALID_ID, inst)
  711. << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
  712. << "'s layout does not match Object <id> '"
  713. << _.getIdName(object->id()) << "'s layout.";
  714. }
  715. }
  716. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  717. return SPV_SUCCESS;
  718. }
  719. spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
  720. const auto target_index = 0;
  721. const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
  722. const auto target = _.FindDef(target_id);
  723. if (!target) {
  724. return _.diag(SPV_ERROR_INVALID_ID, inst)
  725. << "Target operand <id> '" << _.getIdName(target_id)
  726. << "' is not defined.";
  727. }
  728. const auto source_index = 1;
  729. const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
  730. const auto source = _.FindDef(source_id);
  731. if (!source) {
  732. return _.diag(SPV_ERROR_INVALID_ID, inst)
  733. << "Source operand <id> '" << _.getIdName(source_id)
  734. << "' is not defined.";
  735. }
  736. const auto target_pointer_type = _.FindDef(target->type_id());
  737. if (!target_pointer_type ||
  738. target_pointer_type->opcode() != SpvOpTypePointer) {
  739. return _.diag(SPV_ERROR_INVALID_ID, inst)
  740. << "Target operand <id> '" << _.getIdName(target_id)
  741. << "' is not a pointer.";
  742. }
  743. const auto source_pointer_type = _.FindDef(source->type_id());
  744. if (!source_pointer_type ||
  745. source_pointer_type->opcode() != SpvOpTypePointer) {
  746. return _.diag(SPV_ERROR_INVALID_ID, inst)
  747. << "Source operand <id> '" << _.getIdName(source_id)
  748. << "' is not a pointer.";
  749. }
  750. if (inst->opcode() == SpvOpCopyMemory) {
  751. const auto target_type =
  752. _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  753. if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
  754. return _.diag(SPV_ERROR_INVALID_ID, inst)
  755. << "Target operand <id> '" << _.getIdName(target_id)
  756. << "' cannot be a void pointer.";
  757. }
  758. const auto source_type =
  759. _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
  760. if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
  761. return _.diag(SPV_ERROR_INVALID_ID, inst)
  762. << "Source operand <id> '" << _.getIdName(source_id)
  763. << "' cannot be a void pointer.";
  764. }
  765. if (target_type->id() != source_type->id()) {
  766. return _.diag(SPV_ERROR_INVALID_ID, inst)
  767. << "Target <id> '" << _.getIdName(source_id)
  768. << "'s type does not match Source <id> '"
  769. << _.getIdName(source_type->id()) << "'s type.";
  770. }
  771. if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  772. } else {
  773. const auto size_id = inst->GetOperandAs<uint32_t>(2);
  774. const auto size = _.FindDef(size_id);
  775. if (!size) {
  776. return _.diag(SPV_ERROR_INVALID_ID, inst)
  777. << "Size operand <id> '" << _.getIdName(size_id)
  778. << "' is not defined.";
  779. }
  780. const auto size_type = _.FindDef(size->type_id());
  781. if (!_.IsIntScalarType(size_type->id())) {
  782. return _.diag(SPV_ERROR_INVALID_ID, inst)
  783. << "Size operand <id> '" << _.getIdName(size_id)
  784. << "' must be a scalar integer type.";
  785. }
  786. bool is_zero = true;
  787. switch (size->opcode()) {
  788. case SpvOpConstantNull:
  789. return _.diag(SPV_ERROR_INVALID_ID, inst)
  790. << "Size operand <id> '" << _.getIdName(size_id)
  791. << "' cannot be a constant zero.";
  792. case SpvOpConstant:
  793. if (size_type->word(3) == 1 &&
  794. size->word(size->words().size() - 1) & 0x80000000) {
  795. return _.diag(SPV_ERROR_INVALID_ID, inst)
  796. << "Size operand <id> '" << _.getIdName(size_id)
  797. << "' cannot have the sign bit set to 1.";
  798. }
  799. for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
  800. is_zero &= (size->word(i) == 0);
  801. }
  802. if (is_zero) {
  803. return _.diag(SPV_ERROR_INVALID_ID, inst)
  804. << "Size operand <id> '" << _.getIdName(size_id)
  805. << "' cannot be a constant zero.";
  806. }
  807. break;
  808. default:
  809. // Cannot infer any other opcodes.
  810. break;
  811. }
  812. if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  813. }
  814. return SPV_SUCCESS;
  815. }
  816. spv_result_t ValidateAccessChain(ValidationState_t& _,
  817. const Instruction* inst) {
  818. std::string instr_name =
  819. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  820. // The result type must be OpTypePointer.
  821. auto result_type = _.FindDef(inst->type_id());
  822. if (SpvOpTypePointer != result_type->opcode()) {
  823. return _.diag(SPV_ERROR_INVALID_ID, inst)
  824. << "The Result Type of " << instr_name << " <id> '"
  825. << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
  826. << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
  827. }
  828. // Result type is a pointer. Find out what it's pointing to.
  829. // This will be used to make sure the indexing results in the same type.
  830. // OpTypePointer word 3 is the type being pointed to.
  831. const auto result_type_pointee = _.FindDef(result_type->word(3));
  832. // Base must be a pointer, pointing to the base of a composite object.
  833. const auto base_index = 2;
  834. const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
  835. const auto base = _.FindDef(base_id);
  836. const auto base_type = _.FindDef(base->type_id());
  837. if (!base_type || SpvOpTypePointer != base_type->opcode()) {
  838. return _.diag(SPV_ERROR_INVALID_ID, inst)
  839. << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
  840. << " instruction must be a pointer.";
  841. }
  842. // The result pointer storage class and base pointer storage class must match.
  843. // Word 2 of OpTypePointer is the Storage Class.
  844. auto result_type_storage_class = result_type->word(2);
  845. auto base_type_storage_class = base_type->word(2);
  846. if (result_type_storage_class != base_type_storage_class) {
  847. return _.diag(SPV_ERROR_INVALID_ID, inst)
  848. << "The result pointer storage class and base "
  849. "pointer storage class in "
  850. << instr_name << " do not match.";
  851. }
  852. // The type pointed to by OpTypePointer (word 3) must be a composite type.
  853. auto type_pointee = _.FindDef(base_type->word(3));
  854. // Check Universal Limit (SPIR-V Spec. Section 2.17).
  855. // The number of indexes passed to OpAccessChain may not exceed 255
  856. // The instruction includes 4 words + N words (for N indexes)
  857. size_t num_indexes = inst->words().size() - 4;
  858. if (inst->opcode() == SpvOpPtrAccessChain ||
  859. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  860. // In pointer access chains, the element operand is required, but not
  861. // counted as an index.
  862. --num_indexes;
  863. }
  864. const size_t num_indexes_limit =
  865. _.options()->universal_limits_.max_access_chain_indexes;
  866. if (num_indexes > num_indexes_limit) {
  867. return _.diag(SPV_ERROR_INVALID_ID, inst)
  868. << "The number of indexes in " << instr_name << " may not exceed "
  869. << num_indexes_limit << ". Found " << num_indexes << " indexes.";
  870. }
  871. // Indexes walk the type hierarchy to the desired depth, potentially down to
  872. // scalar granularity. The first index in Indexes will select the top-level
  873. // member/element/component/element of the base composite. All composite
  874. // constituents use zero-based numbering, as described by their OpType...
  875. // instruction. The second index will apply similarly to that result, and so
  876. // on. Once any non-composite type is reached, there must be no remaining
  877. // (unused) indexes.
  878. auto starting_index = 4;
  879. if (inst->opcode() == SpvOpPtrAccessChain ||
  880. inst->opcode() == SpvOpInBoundsPtrAccessChain) {
  881. ++starting_index;
  882. }
  883. for (size_t i = starting_index; i < inst->words().size(); ++i) {
  884. const uint32_t cur_word = inst->words()[i];
  885. // Earlier ID checks ensure that cur_word definition exists.
  886. auto cur_word_instr = _.FindDef(cur_word);
  887. // The index must be a scalar integer type (See OpAccessChain in the Spec.)
  888. auto index_type = _.FindDef(cur_word_instr->type_id());
  889. if (!index_type || SpvOpTypeInt != index_type->opcode()) {
  890. return _.diag(SPV_ERROR_INVALID_ID, inst)
  891. << "Indexes passed to " << instr_name
  892. << " must be of type integer.";
  893. }
  894. switch (type_pointee->opcode()) {
  895. case SpvOpTypeMatrix:
  896. case SpvOpTypeVector:
  897. case SpvOpTypeArray:
  898. case SpvOpTypeRuntimeArray: {
  899. // In OpTypeMatrix, OpTypeVector, OpTypeArray, and OpTypeRuntimeArray,
  900. // word 2 is the Element Type.
  901. type_pointee = _.FindDef(type_pointee->word(2));
  902. break;
  903. }
  904. case SpvOpTypeStruct: {
  905. // In case of structures, there is an additional constraint on the
  906. // index: the index must be an OpConstant.
  907. if (SpvOpConstant != cur_word_instr->opcode()) {
  908. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  909. << "The <id> passed to " << instr_name
  910. << " to index into a "
  911. "structure must be an OpConstant.";
  912. }
  913. // Get the index value from the OpConstant (word 3 of OpConstant).
  914. // OpConstant could be a signed integer. But it's okay to treat it as
  915. // unsigned because a negative constant int would never be seen as
  916. // correct as a struct offset, since structs can't have more than 2
  917. // billion members.
  918. const uint32_t cur_index = cur_word_instr->word(3);
  919. // The index points to the struct member we want, therefore, the index
  920. // should be less than the number of struct members.
  921. const uint32_t num_struct_members =
  922. static_cast<uint32_t>(type_pointee->words().size() - 2);
  923. if (cur_index >= num_struct_members) {
  924. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  925. << "Index is out of bounds: " << instr_name
  926. << " can not find index " << cur_index
  927. << " into the structure <id> '"
  928. << _.getIdName(type_pointee->id()) << "'. This structure has "
  929. << num_struct_members << " members. Largest valid index is "
  930. << num_struct_members - 1 << ".";
  931. }
  932. // Struct members IDs start at word 2 of OpTypeStruct.
  933. auto structMemberId = type_pointee->word(cur_index + 2);
  934. type_pointee = _.FindDef(structMemberId);
  935. break;
  936. }
  937. default: {
  938. // Give an error. reached non-composite type while indexes still remain.
  939. return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
  940. << instr_name
  941. << " reached non-composite type while indexes "
  942. "still remain to be traversed.";
  943. }
  944. }
  945. }
  946. // At this point, we have fully walked down from the base using the indeces.
  947. // The type being pointed to should be the same as the result type.
  948. if (type_pointee->id() != result_type_pointee->id()) {
  949. return _.diag(SPV_ERROR_INVALID_ID, inst)
  950. << instr_name << " result type (Op"
  951. << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
  952. << ") does not match the type that results from indexing into the "
  953. "base "
  954. "<id> (Op"
  955. << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
  956. << ").";
  957. }
  958. return SPV_SUCCESS;
  959. }
  960. spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
  961. const Instruction* inst) {
  962. if (_.addressing_model() == SpvAddressingModelLogical) {
  963. if (!_.features().variable_pointers &&
  964. !_.features().variable_pointers_storage_buffer) {
  965. return _.diag(SPV_ERROR_INVALID_DATA, inst)
  966. << "Generating variable pointers requires capability "
  967. << "VariablePointers or VariablePointersStorageBuffer";
  968. }
  969. }
  970. return ValidateAccessChain(_, inst);
  971. }
  972. spv_result_t ValidateArrayLength(ValidationState_t& state,
  973. const Instruction* inst) {
  974. std::string instr_name =
  975. "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
  976. // Result type must be a 32-bit unsigned int.
  977. auto result_type = state.FindDef(inst->type_id());
  978. if (result_type->opcode() != SpvOpTypeInt ||
  979. result_type->GetOperandAs<uint32_t>(1) != 32 ||
  980. result_type->GetOperandAs<uint32_t>(2) != 0) {
  981. return state.diag(SPV_ERROR_INVALID_ID, inst)
  982. << "The Result Type of " << instr_name << " <id> '"
  983. << state.getIdName(inst->id())
  984. << "' must be OpTypeInt with width 32 and signedness 0.";
  985. }
  986. // The structure that is passed in must be an pointer to a structure, whose
  987. // last element is a runtime array.
  988. auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
  989. auto pointer_type = state.FindDef(pointer->type_id());
  990. if (pointer_type->opcode() != SpvOpTypePointer) {
  991. return state.diag(SPV_ERROR_INVALID_ID, inst)
  992. << "The Struture's type in " << instr_name << " <id> '"
  993. << state.getIdName(inst->id())
  994. << "' must be a pointer to an OpTypeStruct.";
  995. }
  996. auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  997. if (structure_type->opcode() != SpvOpTypeStruct) {
  998. return state.diag(SPV_ERROR_INVALID_ID, inst)
  999. << "The Struture's type in " << instr_name << " <id> '"
  1000. << state.getIdName(inst->id())
  1001. << "' must be a pointer to an OpTypeStruct.";
  1002. }
  1003. auto num_of_members = structure_type->operands().size() - 1;
  1004. auto last_member =
  1005. state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
  1006. if (last_member->opcode() != SpvOpTypeRuntimeArray) {
  1007. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1008. << "The Struture's last member in " << instr_name << " <id> '"
  1009. << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
  1010. }
  1011. // The array member must the the index of the last element (the run time
  1012. // array).
  1013. if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
  1014. return state.diag(SPV_ERROR_INVALID_ID, inst)
  1015. << "The array member in " << instr_name << " <id> '"
  1016. << state.getIdName(inst->id())
  1017. << "' must be an the last member of the struct.";
  1018. }
  1019. return SPV_SUCCESS;
  1020. }
  1021. } // namespace
  1022. spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
  1023. switch (inst->opcode()) {
  1024. case SpvOpVariable:
  1025. if (auto error = ValidateVariable(_, inst)) return error;
  1026. break;
  1027. case SpvOpLoad:
  1028. if (auto error = ValidateLoad(_, inst)) return error;
  1029. break;
  1030. case SpvOpStore:
  1031. if (auto error = ValidateStore(_, inst)) return error;
  1032. break;
  1033. case SpvOpCopyMemory:
  1034. case SpvOpCopyMemorySized:
  1035. if (auto error = ValidateCopyMemory(_, inst)) return error;
  1036. break;
  1037. case SpvOpPtrAccessChain:
  1038. if (auto error = ValidatePtrAccessChain(_, inst)) return error;
  1039. break;
  1040. case SpvOpAccessChain:
  1041. case SpvOpInBoundsAccessChain:
  1042. case SpvOpInBoundsPtrAccessChain:
  1043. if (auto error = ValidateAccessChain(_, inst)) return error;
  1044. break;
  1045. case SpvOpArrayLength:
  1046. if (auto error = ValidateArrayLength(_, inst)) return error;
  1047. break;
  1048. case SpvOpImageTexelPointer:
  1049. case SpvOpGenericPtrMemSemantics:
  1050. default:
  1051. break;
  1052. }
  1053. return SPV_SUCCESS;
  1054. }
  1055. } // namespace val
  1056. } // namespace spvtools