validate_memory.cpp 67 KB

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