validate_memory.cpp 66 KB

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