• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 #include <algorithm>
18 #include <string>
19 #include <vector>
20 
21 #include "source/opcode.h"
22 #include "source/spirv_target_env.h"
23 #include "source/val/instruction.h"
24 #include "source/val/validate.h"
25 #include "source/val/validate_scopes.h"
26 #include "source/val/validation_state.h"
27 
28 namespace spvtools {
29 namespace val {
30 namespace {
31 
32 bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
33                                 const Instruction*);
34 bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
35                                  const Instruction*);
36 bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
37                                const Instruction*);
38 bool HasConflictingMemberOffsets(const std::set<Decoration>&,
39                                  const std::set<Decoration>&);
40 
IsAllowedTypeOrArrayOfSame(ValidationState_t & _,const Instruction * type,std::initializer_list<spv::Op> allowed)41 bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction* type,
42                                 std::initializer_list<spv::Op> allowed) {
43   if (std::find(allowed.begin(), allowed.end(), type->opcode()) !=
44       allowed.end()) {
45     return true;
46   }
47   if (type->opcode() == spv::Op::OpTypeArray ||
48       type->opcode() == spv::Op::OpTypeRuntimeArray) {
49     auto elem_type = _.FindDef(type->word(2));
50     return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
51            allowed.end();
52   }
53   return false;
54 }
55 
56 // Returns true if the two instructions represent structs that, as far as the
57 // validator can tell, have the exact same data layout.
AreLayoutCompatibleStructs(ValidationState_t & _,const Instruction * type1,const Instruction * type2)58 bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
59                                 const Instruction* type2) {
60   if (type1->opcode() != spv::Op::OpTypeStruct) {
61     return false;
62   }
63   if (type2->opcode() != spv::Op::OpTypeStruct) {
64     return false;
65   }
66 
67   if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
68 
69   return HaveSameLayoutDecorations(_, type1, type2);
70 }
71 
72 // Returns true if the operands to the OpTypeStruct instruction defining the
73 // types are the same or are layout compatible types. |type1| and |type2| must
74 // be OpTypeStruct instructions.
HaveLayoutCompatibleMembers(ValidationState_t & _,const Instruction * type1,const Instruction * type2)75 bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
76                                  const Instruction* type2) {
77   assert(type1->opcode() == spv::Op::OpTypeStruct &&
78          "type1 must be an OpTypeStruct instruction.");
79   assert(type2->opcode() == spv::Op::OpTypeStruct &&
80          "type2 must be an OpTypeStruct instruction.");
81   const auto& type1_operands = type1->operands();
82   const auto& type2_operands = type2->operands();
83   if (type1_operands.size() != type2_operands.size()) {
84     return false;
85   }
86 
87   for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
88     if (type1->word(operand) != type2->word(operand)) {
89       auto def1 = _.FindDef(type1->word(operand));
90       auto def2 = _.FindDef(type2->word(operand));
91       if (!AreLayoutCompatibleStructs(_, def1, def2)) {
92         return false;
93       }
94     }
95   }
96   return true;
97 }
98 
99 // Returns true if all decorations that affect the data layout of the struct
100 // (like Offset), are the same for the two types. |type1| and |type2| must be
101 // OpTypeStruct instructions.
HaveSameLayoutDecorations(ValidationState_t & _,const Instruction * type1,const Instruction * type2)102 bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
103                                const Instruction* type2) {
104   assert(type1->opcode() == spv::Op::OpTypeStruct &&
105          "type1 must be an OpTypeStruct instruction.");
106   assert(type2->opcode() == spv::Op::OpTypeStruct &&
107          "type2 must be an OpTypeStruct instruction.");
108   const std::set<Decoration>& type1_decorations = _.id_decorations(type1->id());
109   const std::set<Decoration>& type2_decorations = _.id_decorations(type2->id());
110 
111   // TODO: Will have to add other check for arrays an matricies if we want to
112   // handle them.
113   if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
114     return false;
115   }
116 
117   return true;
118 }
119 
HasConflictingMemberOffsets(const std::set<Decoration> & type1_decorations,const std::set<Decoration> & type2_decorations)120 bool HasConflictingMemberOffsets(
121     const std::set<Decoration>& type1_decorations,
122     const std::set<Decoration>& type2_decorations) {
123   {
124     // We are interested in conflicting decoration.  If a decoration is in one
125     // list but not the other, then we will assume the code is correct.  We are
126     // looking for things we know to be wrong.
127     //
128     // We do not have to traverse type2_decoration because, after traversing
129     // type1_decorations, anything new will not be found in
130     // type1_decoration.  Therefore, it cannot lead to a conflict.
131     for (const Decoration& decoration : type1_decorations) {
132       switch (decoration.dec_type()) {
133         case spv::Decoration::Offset: {
134           // Since these affect the layout of the struct, they must be present
135           // in both structs.
136           auto compare = [&decoration](const Decoration& rhs) {
137             if (rhs.dec_type() != spv::Decoration::Offset) return false;
138             return decoration.struct_member_index() ==
139                    rhs.struct_member_index();
140           };
141           auto i = std::find_if(type2_decorations.begin(),
142                                 type2_decorations.end(), compare);
143           if (i != type2_decorations.end() &&
144               decoration.params().front() != i->params().front()) {
145             return true;
146           }
147         } break;
148         default:
149           // This decoration does not affect the layout of the structure, so
150           // just moving on.
151           break;
152       }
153     }
154   }
155   return false;
156 }
157 
158 // If |skip_builtin| is true, returns true if |storage| contains bool within
159 // it and no storage that contains the bool is builtin.
160 // If |skip_builtin| is false, returns true if |storage| contains bool within
161 // it.
ContainsInvalidBool(ValidationState_t & _,const Instruction * storage,bool skip_builtin)162 bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
163                          bool skip_builtin) {
164   if (skip_builtin) {
165     for (const Decoration& decoration : _.id_decorations(storage->id())) {
166       if (decoration.dec_type() == spv::Decoration::BuiltIn) return false;
167     }
168   }
169 
170   const size_t elem_type_index = 1;
171   uint32_t elem_type_id;
172   Instruction* elem_type;
173 
174   switch (storage->opcode()) {
175     case spv::Op::OpTypeBool:
176       return true;
177     case spv::Op::OpTypeVector:
178     case spv::Op::OpTypeMatrix:
179     case spv::Op::OpTypeArray:
180     case spv::Op::OpTypeRuntimeArray:
181       elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
182       elem_type = _.FindDef(elem_type_id);
183       return ContainsInvalidBool(_, elem_type, skip_builtin);
184     case spv::Op::OpTypeStruct:
185       for (size_t member_type_index = 1;
186            member_type_index < storage->operands().size();
187            ++member_type_index) {
188         auto member_type_id =
189             storage->GetOperandAs<uint32_t>(member_type_index);
190         auto member_type = _.FindDef(member_type_id);
191         if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
192       }
193     default:
194       break;
195   }
196   return false;
197 }
198 
ContainsCooperativeMatrix(ValidationState_t & _,const Instruction * storage)199 bool ContainsCooperativeMatrix(ValidationState_t& _,
200                                const Instruction* storage) {
201   const size_t elem_type_index = 1;
202   uint32_t elem_type_id;
203   Instruction* elem_type;
204 
205   switch (storage->opcode()) {
206     case spv::Op::OpTypeCooperativeMatrixNV:
207     case spv::Op::OpTypeCooperativeMatrixKHR:
208       return true;
209     case spv::Op::OpTypeArray:
210     case spv::Op::OpTypeRuntimeArray:
211       elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
212       elem_type = _.FindDef(elem_type_id);
213       return ContainsCooperativeMatrix(_, elem_type);
214     case spv::Op::OpTypeStruct:
215       for (size_t member_type_index = 1;
216            member_type_index < storage->operands().size();
217            ++member_type_index) {
218         auto member_type_id =
219             storage->GetOperandAs<uint32_t>(member_type_index);
220         auto member_type = _.FindDef(member_type_id);
221         if (ContainsCooperativeMatrix(_, member_type)) return true;
222       }
223       break;
224     default:
225       break;
226   }
227   return false;
228 }
229 
GetStorageClass(ValidationState_t & _,const Instruction * inst)230 std::pair<spv::StorageClass, spv::StorageClass> GetStorageClass(
231     ValidationState_t& _, const Instruction* inst) {
232   spv::StorageClass dst_sc = spv::StorageClass::Max;
233   spv::StorageClass src_sc = spv::StorageClass::Max;
234   switch (inst->opcode()) {
235     case spv::Op::OpCooperativeMatrixLoadNV:
236     case spv::Op::OpCooperativeMatrixLoadKHR:
237     case spv::Op::OpLoad: {
238       auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
239       auto load_pointer_type = _.FindDef(load_pointer->type_id());
240       dst_sc = load_pointer_type->GetOperandAs<spv::StorageClass>(1);
241       break;
242     }
243     case spv::Op::OpCooperativeMatrixStoreNV:
244     case spv::Op::OpCooperativeMatrixStoreKHR:
245     case spv::Op::OpStore: {
246       auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
247       auto store_pointer_type = _.FindDef(store_pointer->type_id());
248       dst_sc = store_pointer_type->GetOperandAs<spv::StorageClass>(1);
249       break;
250     }
251     case spv::Op::OpCopyMemory:
252     case spv::Op::OpCopyMemorySized: {
253       auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
254       auto dst_type = _.FindDef(dst->type_id());
255       dst_sc = dst_type->GetOperandAs<spv::StorageClass>(1);
256       auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
257       auto src_type = _.FindDef(src->type_id());
258       src_sc = src_type->GetOperandAs<spv::StorageClass>(1);
259       break;
260     }
261     default:
262       break;
263   }
264 
265   return std::make_pair(dst_sc, src_sc);
266 }
267 
268 // Returns the number of instruction words taken up by a memory access
269 // argument and its implied operands.
MemoryAccessNumWords(uint32_t mask)270 int MemoryAccessNumWords(uint32_t mask) {
271   int result = 1;  // Count the mask
272   if (mask & uint32_t(spv::MemoryAccessMask::Aligned)) ++result;
273   if (mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) ++result;
274   if (mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) ++result;
275   return result;
276 }
277 
278 // Returns the scope ID operand for MakeAvailable memory access with mask
279 // at the given operand index.
280 // This function is only called for OpLoad, OpStore, OpCopyMemory and
281 // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
282 // OpCooperativeMatrixStoreNV.
GetMakeAvailableScope(const Instruction * inst,uint32_t mask,uint32_t mask_index)283 uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
284                                uint32_t mask_index) {
285   assert(mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR));
286   uint32_t this_bit = uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR);
287   uint32_t index =
288       mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
289   return inst->GetOperandAs<uint32_t>(index);
290 }
291 
292 // This function is only called for OpLoad, OpStore, OpCopyMemory,
293 // OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
294 // OpCooperativeMatrixStoreNV.
GetMakeVisibleScope(const Instruction * inst,uint32_t mask,uint32_t mask_index)295 uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
296                              uint32_t mask_index) {
297   assert(mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR));
298   uint32_t this_bit = uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR);
299   uint32_t index =
300       mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
301   return inst->GetOperandAs<uint32_t>(index);
302 }
303 
DoesStructContainRTA(const ValidationState_t & _,const Instruction * inst)304 bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
305   for (size_t member_index = 1; member_index < inst->operands().size();
306        ++member_index) {
307     const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
308     const auto member_type = _.FindDef(member_id);
309     if (member_type->opcode() == spv::Op::OpTypeRuntimeArray) return true;
310   }
311   return false;
312 }
313 
CheckMemoryAccess(ValidationState_t & _,const Instruction * inst,uint32_t index)314 spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
315                                uint32_t index) {
316   spv::StorageClass dst_sc, src_sc;
317   std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
318   if (inst->operands().size() <= index) {
319     // Cases where lack of some operand is invalid
320     if (src_sc == spv::StorageClass::PhysicalStorageBuffer ||
321         dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
322       return _.diag(SPV_ERROR_INVALID_ID, inst)
323              << _.VkErrorID(4708)
324              << "Memory accesses with PhysicalStorageBuffer must use Aligned.";
325     }
326     return SPV_SUCCESS;
327   }
328 
329   const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
330   if (mask & uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) {
331     if (inst->opcode() == spv::Op::OpLoad ||
332         inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV ||
333         inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
334       return _.diag(SPV_ERROR_INVALID_ID, inst)
335              << "MakePointerAvailableKHR cannot be used with OpLoad.";
336     }
337 
338     if (!(mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR))) {
339       return _.diag(SPV_ERROR_INVALID_ID, inst)
340              << "NonPrivatePointerKHR must be specified if "
341                 "MakePointerAvailableKHR is specified.";
342     }
343 
344     // Check the associated scope for MakeAvailableKHR.
345     const auto available_scope = GetMakeAvailableScope(inst, mask, index);
346     if (auto error = ValidateMemoryScope(_, inst, available_scope))
347       return error;
348   }
349 
350   if (mask & uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) {
351     if (inst->opcode() == spv::Op::OpStore ||
352         inst->opcode() == spv::Op::OpCooperativeMatrixStoreNV ||
353         inst->opcode() == spv::Op::OpCooperativeMatrixStoreKHR) {
354       return _.diag(SPV_ERROR_INVALID_ID, inst)
355              << "MakePointerVisibleKHR cannot be used with OpStore.";
356     }
357 
358     if (!(mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR))) {
359       return _.diag(SPV_ERROR_INVALID_ID, inst)
360              << "NonPrivatePointerKHR must be specified if "
361              << "MakePointerVisibleKHR is specified.";
362     }
363 
364     // Check the associated scope for MakeVisibleKHR.
365     const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
366     if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
367   }
368 
369   if (mask & uint32_t(spv::MemoryAccessMask::NonPrivatePointerKHR)) {
370     if (dst_sc != spv::StorageClass::Uniform &&
371         dst_sc != spv::StorageClass::Workgroup &&
372         dst_sc != spv::StorageClass::CrossWorkgroup &&
373         dst_sc != spv::StorageClass::Generic &&
374         dst_sc != spv::StorageClass::Image &&
375         dst_sc != spv::StorageClass::StorageBuffer &&
376         dst_sc != spv::StorageClass::PhysicalStorageBuffer) {
377       return _.diag(SPV_ERROR_INVALID_ID, inst)
378              << "NonPrivatePointerKHR requires a pointer in Uniform, "
379              << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
380              << "storage classes.";
381     }
382     if (src_sc != spv::StorageClass::Max &&
383         src_sc != spv::StorageClass::Uniform &&
384         src_sc != spv::StorageClass::Workgroup &&
385         src_sc != spv::StorageClass::CrossWorkgroup &&
386         src_sc != spv::StorageClass::Generic &&
387         src_sc != spv::StorageClass::Image &&
388         src_sc != spv::StorageClass::StorageBuffer &&
389         src_sc != spv::StorageClass::PhysicalStorageBuffer) {
390       return _.diag(SPV_ERROR_INVALID_ID, inst)
391              << "NonPrivatePointerKHR requires a pointer in Uniform, "
392              << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
393              << "storage classes.";
394     }
395   }
396 
397   if (!(mask & uint32_t(spv::MemoryAccessMask::Aligned))) {
398     if (src_sc == spv::StorageClass::PhysicalStorageBuffer ||
399         dst_sc == spv::StorageClass::PhysicalStorageBuffer) {
400       return _.diag(SPV_ERROR_INVALID_ID, inst)
401              << _.VkErrorID(4708)
402              << "Memory accesses with PhysicalStorageBuffer must use Aligned.";
403     }
404   }
405 
406   return SPV_SUCCESS;
407 }
408 
ValidateVariable(ValidationState_t & _,const Instruction * inst)409 spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
410   auto result_type = _.FindDef(inst->type_id());
411   if (!result_type || result_type->opcode() != spv::Op::OpTypePointer) {
412     return _.diag(SPV_ERROR_INVALID_ID, inst)
413            << "OpVariable Result Type <id> " << _.getIdName(inst->type_id())
414            << " is not a pointer type.";
415   }
416 
417   const auto type_index = 2;
418   const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
419   auto value_type = _.FindDef(value_id);
420 
421   const auto initializer_index = 3;
422   const auto storage_class_index = 2;
423   if (initializer_index < inst->operands().size()) {
424     const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
425     const auto initializer = _.FindDef(initializer_id);
426     const auto is_module_scope_var =
427         initializer && (initializer->opcode() == spv::Op::OpVariable) &&
428         (initializer->GetOperandAs<spv::StorageClass>(storage_class_index) !=
429          spv::StorageClass::Function);
430     const auto is_constant =
431         initializer && spvOpcodeIsConstant(initializer->opcode());
432     if (!initializer || !(is_constant || is_module_scope_var)) {
433       return _.diag(SPV_ERROR_INVALID_ID, inst)
434              << "OpVariable Initializer <id> " << _.getIdName(initializer_id)
435              << " is not a constant or module-scope variable.";
436     }
437     if (initializer->type_id() != value_id) {
438       return _.diag(SPV_ERROR_INVALID_ID, inst)
439              << "Initializer type must match the type pointed to by the Result "
440                 "Type";
441     }
442   }
443 
444   auto storage_class =
445       inst->GetOperandAs<spv::StorageClass>(storage_class_index);
446   if (storage_class != spv::StorageClass::Workgroup &&
447       storage_class != spv::StorageClass::CrossWorkgroup &&
448       storage_class != spv::StorageClass::Private &&
449       storage_class != spv::StorageClass::Function &&
450       storage_class != spv::StorageClass::UniformConstant &&
451       storage_class != spv::StorageClass::RayPayloadKHR &&
452       storage_class != spv::StorageClass::IncomingRayPayloadKHR &&
453       storage_class != spv::StorageClass::HitAttributeKHR &&
454       storage_class != spv::StorageClass::CallableDataKHR &&
455       storage_class != spv::StorageClass::IncomingCallableDataKHR &&
456       storage_class != spv::StorageClass::TaskPayloadWorkgroupEXT &&
457       storage_class != spv::StorageClass::HitObjectAttributeNV) {
458     bool storage_input_or_output = storage_class == spv::StorageClass::Input ||
459                                    storage_class == spv::StorageClass::Output;
460     bool builtin = false;
461     if (storage_input_or_output) {
462       for (const Decoration& decoration : _.id_decorations(inst->id())) {
463         if (decoration.dec_type() == spv::Decoration::BuiltIn) {
464           builtin = true;
465           break;
466         }
467       }
468     }
469     if (!builtin &&
470         ContainsInvalidBool(_, value_type, storage_input_or_output)) {
471       if (storage_input_or_output) {
472         return _.diag(SPV_ERROR_INVALID_ID, inst)
473                << _.VkErrorID(7290)
474                << "If OpTypeBool is stored in conjunction with OpVariable "
475                   "using Input or Output Storage Classes it requires a BuiltIn "
476                   "decoration";
477 
478       } else {
479         return _.diag(SPV_ERROR_INVALID_ID, inst)
480                << "If OpTypeBool is stored in conjunction with OpVariable, it "
481                   "can only be used with non-externally visible shader Storage "
482                   "Classes: Workgroup, CrossWorkgroup, Private, Function, "
483                   "Input, Output, RayPayloadKHR, IncomingRayPayloadKHR, "
484                   "HitAttributeKHR, CallableDataKHR, "
485                   "IncomingCallableDataKHR, or UniformConstant";
486       }
487     }
488   }
489 
490   if (!_.IsValidStorageClass(storage_class)) {
491     return _.diag(SPV_ERROR_INVALID_BINARY, inst)
492            << _.VkErrorID(4643)
493            << "Invalid storage class for target environment";
494   }
495 
496   if (storage_class == spv::StorageClass::Generic) {
497     return _.diag(SPV_ERROR_INVALID_BINARY, inst)
498            << "OpVariable storage class cannot be Generic";
499   }
500 
501   if (inst->function() && storage_class != spv::StorageClass::Function) {
502     return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
503            << "Variables must have a function[7] storage class inside"
504               " of a function";
505   }
506 
507   if (!inst->function() && storage_class == spv::StorageClass::Function) {
508     return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
509            << "Variables can not have a function[7] storage class "
510               "outside of a function";
511   }
512 
513   // SPIR-V 3.32.8: Check that pointer type and variable type have the same
514   // storage class.
515   const auto result_storage_class_index = 1;
516   const auto result_storage_class =
517       result_type->GetOperandAs<spv::StorageClass>(result_storage_class_index);
518   if (storage_class != result_storage_class) {
519     return _.diag(SPV_ERROR_INVALID_ID, inst)
520            << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
521            << "Its Storage Class operand must be the same as the Storage Class "
522            << "operand of the result type.";
523   }
524 
525   // Variable pointer related restrictions.
526   const auto pointee = _.FindDef(result_type->word(3));
527   if (_.addressing_model() == spv::AddressingModel::Logical &&
528       !_.options()->relax_logical_pointer) {
529     // VariablePointersStorageBuffer is implied by VariablePointers.
530     if (pointee->opcode() == spv::Op::OpTypePointer) {
531       if (!_.HasCapability(spv::Capability::VariablePointersStorageBuffer)) {
532         return _.diag(SPV_ERROR_INVALID_ID, inst)
533                << "In Logical addressing, variables may not allocate a pointer "
534                << "type";
535       } else if (storage_class != spv::StorageClass::Function &&
536                  storage_class != spv::StorageClass::Private) {
537         return _.diag(SPV_ERROR_INVALID_ID, inst)
538                << "In Logical addressing with variable pointers, variables "
539                << "that allocate pointers must be in Function or Private "
540                << "storage classes";
541       }
542     }
543   }
544 
545   if (spvIsVulkanEnv(_.context()->target_env)) {
546     // Vulkan Push Constant Interface section: Check type of PushConstant
547     // variables.
548     if (storage_class == spv::StorageClass::PushConstant) {
549       if (pointee->opcode() != spv::Op::OpTypeStruct) {
550         return _.diag(SPV_ERROR_INVALID_ID, inst)
551                << _.VkErrorID(6808) << "PushConstant OpVariable <id> "
552                << _.getIdName(inst->id()) << " has illegal type.\n"
553                << "From Vulkan spec, Push Constant Interface section:\n"
554                << "Such variables must be typed as OpTypeStruct";
555       }
556     }
557 
558     // Vulkan Descriptor Set Interface: Check type of UniformConstant and
559     // Uniform variables.
560     if (storage_class == spv::StorageClass::UniformConstant) {
561       if (!IsAllowedTypeOrArrayOfSame(
562               _, pointee,
563               {spv::Op::OpTypeImage, spv::Op::OpTypeSampler,
564                spv::Op::OpTypeSampledImage,
565                spv::Op::OpTypeAccelerationStructureKHR})) {
566         return _.diag(SPV_ERROR_INVALID_ID, inst)
567                << _.VkErrorID(4655) << "UniformConstant OpVariable <id> "
568                << _.getIdName(inst->id()) << " has illegal type.\n"
569                << "Variables identified with the UniformConstant storage class "
570                << "are used only as handles to refer to opaque resources. Such "
571                << "variables must be typed as OpTypeImage, OpTypeSampler, "
572                << "OpTypeSampledImage, OpTypeAccelerationStructureKHR, "
573                << "or an array of one of these types.";
574       }
575     }
576 
577     if (storage_class == spv::StorageClass::Uniform) {
578       if (!IsAllowedTypeOrArrayOfSame(_, pointee, {spv::Op::OpTypeStruct})) {
579         return _.diag(SPV_ERROR_INVALID_ID, inst)
580                << _.VkErrorID(6807) << "Uniform OpVariable <id> "
581                << _.getIdName(inst->id()) << " has illegal type.\n"
582                << "From Vulkan spec:\n"
583                << "Variables identified with the Uniform storage class are "
584                << "used to access transparent buffer backed resources. Such "
585                << "variables must be typed as OpTypeStruct, or an array of "
586                << "this type";
587       }
588     }
589 
590     if (storage_class == spv::StorageClass::StorageBuffer) {
591       if (!IsAllowedTypeOrArrayOfSame(_, pointee, {spv::Op::OpTypeStruct})) {
592         return _.diag(SPV_ERROR_INVALID_ID, inst)
593                << _.VkErrorID(6807) << "StorageBuffer OpVariable <id> "
594                << _.getIdName(inst->id()) << " has illegal type.\n"
595                << "From Vulkan spec:\n"
596                << "Variables identified with the StorageBuffer storage class "
597                   "are used to access transparent buffer backed resources. "
598                   "Such variables must be typed as OpTypeStruct, or an array "
599                   "of this type";
600       }
601     }
602 
603     // Check for invalid use of Invariant
604     if (storage_class != spv::StorageClass::Input &&
605         storage_class != spv::StorageClass::Output) {
606       if (_.HasDecoration(inst->id(), spv::Decoration::Invariant)) {
607         return _.diag(SPV_ERROR_INVALID_ID, inst)
608                << _.VkErrorID(4677)
609                << "Variable decorated with Invariant must only be identified "
610                   "with the Input or Output storage class in Vulkan "
611                   "environment.";
612       }
613       // Need to check if only the members in a struct are decorated
614       if (value_type && value_type->opcode() == spv::Op::OpTypeStruct) {
615         if (_.HasDecoration(value_id, spv::Decoration::Invariant)) {
616           return _.diag(SPV_ERROR_INVALID_ID, inst)
617                  << _.VkErrorID(4677)
618                  << "Variable struct member decorated with Invariant must only "
619                     "be identified with the Input or Output storage class in "
620                     "Vulkan environment.";
621         }
622       }
623     }
624 
625     // Initializers in Vulkan are only allowed in some storage clases
626     if (inst->operands().size() > 3) {
627       if (storage_class == spv::StorageClass::Workgroup) {
628         auto init_id = inst->GetOperandAs<uint32_t>(3);
629         auto init = _.FindDef(init_id);
630         if (init->opcode() != spv::Op::OpConstantNull) {
631           return _.diag(SPV_ERROR_INVALID_ID, inst)
632                  << _.VkErrorID(4734) << "OpVariable, <id> "
633                  << _.getIdName(inst->id())
634                  << ", initializers are limited to OpConstantNull in "
635                     "Workgroup "
636                     "storage class";
637         }
638       } else if (storage_class != spv::StorageClass::Output &&
639                  storage_class != spv::StorageClass::Private &&
640                  storage_class != spv::StorageClass::Function) {
641         return _.diag(SPV_ERROR_INVALID_ID, inst)
642                << _.VkErrorID(4651) << "OpVariable, <id> "
643                << _.getIdName(inst->id())
644                << ", has a disallowed initializer & storage class "
645                << "combination.\n"
646                << "From " << spvLogStringForEnv(_.context()->target_env)
647                << " spec:\n"
648                << "Variable declarations that include initializers must have "
649                << "one of the following storage classes: Output, Private, "
650                << "Function or Workgroup";
651       }
652     }
653   }
654 
655   if (inst->operands().size() > 3) {
656     if (storage_class == spv::StorageClass::TaskPayloadWorkgroupEXT) {
657       return _.diag(SPV_ERROR_INVALID_ID, inst)
658              << "OpVariable, <id> " << _.getIdName(inst->id())
659              << ", initializer are not allowed for TaskPayloadWorkgroupEXT";
660     }
661     if (storage_class == spv::StorageClass::Input) {
662       return _.diag(SPV_ERROR_INVALID_ID, inst)
663              << "OpVariable, <id> " << _.getIdName(inst->id())
664              << ", initializer are not allowed for Input";
665     }
666     if (storage_class == spv::StorageClass::HitObjectAttributeNV) {
667       return _.diag(SPV_ERROR_INVALID_ID, inst)
668              << "OpVariable, <id> " << _.getIdName(inst->id())
669              << ", initializer are not allowed for HitObjectAttributeNV";
670     }
671   }
672 
673   if (storage_class == spv::StorageClass::PhysicalStorageBuffer) {
674     return _.diag(SPV_ERROR_INVALID_ID, inst)
675            << "PhysicalStorageBuffer must not be used with OpVariable.";
676   }
677 
678   auto pointee_base = pointee;
679   while (pointee_base->opcode() == spv::Op::OpTypeArray) {
680     pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
681   }
682   if (pointee_base->opcode() == spv::Op::OpTypePointer) {
683     if (pointee_base->GetOperandAs<spv::StorageClass>(1u) ==
684         spv::StorageClass::PhysicalStorageBuffer) {
685       // check for AliasedPointer/RestrictPointer
686       bool foundAliased =
687           _.HasDecoration(inst->id(), spv::Decoration::AliasedPointer);
688       bool foundRestrict =
689           _.HasDecoration(inst->id(), spv::Decoration::RestrictPointer);
690       if (!foundAliased && !foundRestrict) {
691         return _.diag(SPV_ERROR_INVALID_ID, inst)
692                << "OpVariable " << inst->id()
693                << ": expected AliasedPointer or RestrictPointer for "
694                << "PhysicalStorageBuffer pointer.";
695       }
696       if (foundAliased && foundRestrict) {
697         return _.diag(SPV_ERROR_INVALID_ID, inst)
698                << "OpVariable " << inst->id()
699                << ": can't specify both AliasedPointer and "
700                << "RestrictPointer for PhysicalStorageBuffer pointer.";
701       }
702     }
703   }
704 
705   // Vulkan specific validation rules for OpTypeRuntimeArray
706   if (spvIsVulkanEnv(_.context()->target_env)) {
707     // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
708     // so should never appear as a bare variable.
709     // Unless the module has the RuntimeDescriptorArrayEXT capability.
710     if (value_type && value_type->opcode() == spv::Op::OpTypeRuntimeArray) {
711       if (!_.HasCapability(spv::Capability::RuntimeDescriptorArrayEXT)) {
712         return _.diag(SPV_ERROR_INVALID_ID, inst)
713                << _.VkErrorID(4680) << "OpVariable, <id> "
714                << _.getIdName(inst->id())
715                << ", is attempting to create memory for an illegal type, "
716                << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
717                << "appear as the final member of an OpTypeStruct, thus cannot "
718                << "be instantiated via OpVariable";
719       } else {
720         // A bare variable OpTypeRuntimeArray is allowed in this context, but
721         // still need to check the storage class.
722         if (storage_class != spv::StorageClass::StorageBuffer &&
723             storage_class != spv::StorageClass::Uniform &&
724             storage_class != spv::StorageClass::UniformConstant) {
725           return _.diag(SPV_ERROR_INVALID_ID, inst)
726                  << _.VkErrorID(4680)
727                  << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
728                  << "containing OpTypeRuntimeArray must have storage class of "
729                  << "StorageBuffer, Uniform, or UniformConstant.";
730         }
731       }
732     }
733 
734     // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
735     // must either have the storage class StorageBuffer and be decorated
736     // with Block, or it must be in the Uniform storage class and be decorated
737     // as BufferBlock.
738     if (value_type && value_type->opcode() == spv::Op::OpTypeStruct) {
739       if (DoesStructContainRTA(_, value_type)) {
740         if (storage_class == spv::StorageClass::StorageBuffer ||
741             storage_class == spv::StorageClass::PhysicalStorageBuffer) {
742           if (!_.HasDecoration(value_id, spv::Decoration::Block)) {
743             return _.diag(SPV_ERROR_INVALID_ID, inst)
744                    << _.VkErrorID(4680)
745                    << "For Vulkan, an OpTypeStruct variable containing an "
746                    << "OpTypeRuntimeArray must be decorated with Block if it "
747                    << "has storage class StorageBuffer or "
748                       "PhysicalStorageBuffer.";
749           }
750         } else if (storage_class == spv::StorageClass::Uniform) {
751           if (!_.HasDecoration(value_id, spv::Decoration::BufferBlock)) {
752             return _.diag(SPV_ERROR_INVALID_ID, inst)
753                    << _.VkErrorID(4680)
754                    << "For Vulkan, an OpTypeStruct variable containing an "
755                    << "OpTypeRuntimeArray must be decorated with BufferBlock "
756                    << "if it has storage class Uniform.";
757           }
758         } else {
759           return _.diag(SPV_ERROR_INVALID_ID, inst)
760                  << _.VkErrorID(4680)
761                  << "For Vulkan, OpTypeStruct variables containing "
762                  << "OpTypeRuntimeArray must have storage class of "
763                  << "StorageBuffer, PhysicalStorageBuffer, or Uniform.";
764         }
765       }
766     }
767   }
768 
769   // Cooperative matrix types can only be allocated in Function or Private
770   if ((storage_class != spv::StorageClass::Function &&
771        storage_class != spv::StorageClass::Private) &&
772       ContainsCooperativeMatrix(_, pointee)) {
773     return _.diag(SPV_ERROR_INVALID_ID, inst)
774            << "Cooperative matrix types (or types containing them) can only be "
775               "allocated "
776            << "in Function or Private storage classes or as function "
777               "parameters";
778   }
779 
780   if (_.HasCapability(spv::Capability::Shader)) {
781     // Don't allow variables containing 16-bit elements without the appropriate
782     // capabilities.
783     if ((!_.HasCapability(spv::Capability::Int16) &&
784          _.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeInt, 16)) ||
785         (!_.HasCapability(spv::Capability::Float16) &&
786          _.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeFloat, 16))) {
787       auto underlying_type = value_type;
788       while (underlying_type->opcode() == spv::Op::OpTypePointer) {
789         storage_class = underlying_type->GetOperandAs<spv::StorageClass>(1u);
790         underlying_type =
791             _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
792       }
793       bool storage_class_ok = true;
794       std::string sc_name = _.grammar().lookupOperandName(
795           SPV_OPERAND_TYPE_STORAGE_CLASS, uint32_t(storage_class));
796       switch (storage_class) {
797         case spv::StorageClass::StorageBuffer:
798         case spv::StorageClass::PhysicalStorageBuffer:
799           if (!_.HasCapability(spv::Capability::StorageBuffer16BitAccess)) {
800             storage_class_ok = false;
801           }
802           break;
803         case spv::StorageClass::Uniform:
804           if (!_.HasCapability(
805                   spv::Capability::UniformAndStorageBuffer16BitAccess)) {
806             if (underlying_type->opcode() == spv::Op::OpTypeArray ||
807                 underlying_type->opcode() == spv::Op::OpTypeRuntimeArray) {
808               underlying_type =
809                   _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
810             }
811             if (!_.HasCapability(spv::Capability::StorageBuffer16BitAccess) ||
812                 !_.HasDecoration(underlying_type->id(),
813                                  spv::Decoration::BufferBlock)) {
814               storage_class_ok = false;
815             }
816           }
817           break;
818         case spv::StorageClass::PushConstant:
819           if (!_.HasCapability(spv::Capability::StoragePushConstant16)) {
820             storage_class_ok = false;
821           }
822           break;
823         case spv::StorageClass::Input:
824         case spv::StorageClass::Output:
825           if (!_.HasCapability(spv::Capability::StorageInputOutput16)) {
826             storage_class_ok = false;
827           }
828           break;
829         case spv::StorageClass::Workgroup:
830           if (!_.HasCapability(
831                   spv::Capability::
832                       WorkgroupMemoryExplicitLayout16BitAccessKHR)) {
833             storage_class_ok = false;
834           }
835           break;
836         default:
837           return _.diag(SPV_ERROR_INVALID_ID, inst)
838                  << "Cannot allocate a variable containing a 16-bit type in "
839                  << sc_name << " storage class";
840       }
841       if (!storage_class_ok) {
842         return _.diag(SPV_ERROR_INVALID_ID, inst)
843                << "Allocating a variable containing a 16-bit element in "
844                << sc_name << " storage class requires an additional capability";
845       }
846     }
847     // Don't allow variables containing 8-bit elements without the appropriate
848     // capabilities.
849     if (!_.HasCapability(spv::Capability::Int8) &&
850         _.ContainsSizedIntOrFloatType(value_id, spv::Op::OpTypeInt, 8)) {
851       auto underlying_type = value_type;
852       while (underlying_type->opcode() == spv::Op::OpTypePointer) {
853         storage_class = underlying_type->GetOperandAs<spv::StorageClass>(1u);
854         underlying_type =
855             _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
856       }
857       bool storage_class_ok = true;
858       std::string sc_name = _.grammar().lookupOperandName(
859           SPV_OPERAND_TYPE_STORAGE_CLASS, uint32_t(storage_class));
860       switch (storage_class) {
861         case spv::StorageClass::StorageBuffer:
862         case spv::StorageClass::PhysicalStorageBuffer:
863           if (!_.HasCapability(spv::Capability::StorageBuffer8BitAccess)) {
864             storage_class_ok = false;
865           }
866           break;
867         case spv::StorageClass::Uniform:
868           if (!_.HasCapability(
869                   spv::Capability::UniformAndStorageBuffer8BitAccess)) {
870             if (underlying_type->opcode() == spv::Op::OpTypeArray ||
871                 underlying_type->opcode() == spv::Op::OpTypeRuntimeArray) {
872               underlying_type =
873                   _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
874             }
875             if (!_.HasCapability(spv::Capability::StorageBuffer8BitAccess) ||
876                 !_.HasDecoration(underlying_type->id(),
877                                  spv::Decoration::BufferBlock)) {
878               storage_class_ok = false;
879             }
880           }
881           break;
882         case spv::StorageClass::PushConstant:
883           if (!_.HasCapability(spv::Capability::StoragePushConstant8)) {
884             storage_class_ok = false;
885           }
886           break;
887         case spv::StorageClass::Workgroup:
888           if (!_.HasCapability(
889                   spv::Capability::
890                       WorkgroupMemoryExplicitLayout8BitAccessKHR)) {
891             storage_class_ok = false;
892           }
893           break;
894         default:
895           return _.diag(SPV_ERROR_INVALID_ID, inst)
896                  << "Cannot allocate a variable containing a 8-bit type in "
897                  << sc_name << " storage class";
898       }
899       if (!storage_class_ok) {
900         return _.diag(SPV_ERROR_INVALID_ID, inst)
901                << "Allocating a variable containing a 8-bit element in "
902                << sc_name << " storage class requires an additional capability";
903       }
904     }
905   }
906 
907   return SPV_SUCCESS;
908 }
909 
ValidateLoad(ValidationState_t & _,const Instruction * inst)910 spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
911   const auto result_type = _.FindDef(inst->type_id());
912   if (!result_type) {
913     return _.diag(SPV_ERROR_INVALID_ID, inst)
914            << "OpLoad Result Type <id> " << _.getIdName(inst->type_id())
915            << " is not defined.";
916   }
917 
918   const auto pointer_index = 2;
919   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
920   const auto pointer = _.FindDef(pointer_id);
921   if (!pointer ||
922       ((_.addressing_model() == spv::AddressingModel::Logical) &&
923        ((!_.features().variable_pointers &&
924          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
925         (_.features().variable_pointers &&
926          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
927     return _.diag(SPV_ERROR_INVALID_ID, inst)
928            << "OpLoad Pointer <id> " << _.getIdName(pointer_id)
929            << " is not a logical pointer.";
930   }
931 
932   const auto pointer_type = _.FindDef(pointer->type_id());
933   if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
934     return _.diag(SPV_ERROR_INVALID_ID, inst)
935            << "OpLoad type for pointer <id> " << _.getIdName(pointer_id)
936            << " is not a pointer type.";
937   }
938 
939   uint32_t pointee_data_type;
940   spv::StorageClass storage_class;
941   if (!_.GetPointerTypeInfo(pointer_type->id(), &pointee_data_type,
942                             &storage_class) ||
943       result_type->id() != pointee_data_type) {
944     return _.diag(SPV_ERROR_INVALID_ID, inst)
945            << "OpLoad Result Type <id> " << _.getIdName(inst->type_id())
946            << " does not match Pointer <id> " << _.getIdName(pointer->id())
947            << "s type.";
948   }
949 
950   if (!_.options()->before_hlsl_legalization &&
951       _.ContainsRuntimeArray(inst->type_id())) {
952     return _.diag(SPV_ERROR_INVALID_ID, inst)
953            << "Cannot load a runtime-sized array";
954   }
955 
956   if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
957 
958   if (_.HasCapability(spv::Capability::Shader) &&
959       _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
960       result_type->opcode() != spv::Op::OpTypePointer) {
961     if (result_type->opcode() != spv::Op::OpTypeInt &&
962         result_type->opcode() != spv::Op::OpTypeFloat &&
963         result_type->opcode() != spv::Op::OpTypeVector &&
964         result_type->opcode() != spv::Op::OpTypeMatrix) {
965       return _.diag(SPV_ERROR_INVALID_ID, inst)
966              << "8- or 16-bit loads must be a scalar, vector or matrix type";
967     }
968   }
969 
970   _.RegisterQCOMImageProcessingTextureConsumer(pointer_id, inst, nullptr);
971 
972   return SPV_SUCCESS;
973 }
974 
ValidateStore(ValidationState_t & _,const Instruction * inst)975 spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
976   const auto pointer_index = 0;
977   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
978   const auto pointer = _.FindDef(pointer_id);
979   if (!pointer ||
980       (_.addressing_model() == spv::AddressingModel::Logical &&
981        ((!_.features().variable_pointers &&
982          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
983         (_.features().variable_pointers &&
984          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
985     return _.diag(SPV_ERROR_INVALID_ID, inst)
986            << "OpStore Pointer <id> " << _.getIdName(pointer_id)
987            << " is not a logical pointer.";
988   }
989   const auto pointer_type = _.FindDef(pointer->type_id());
990   if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
991     return _.diag(SPV_ERROR_INVALID_ID, inst)
992            << "OpStore type for pointer <id> " << _.getIdName(pointer_id)
993            << " is not a pointer type.";
994   }
995   const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
996   const auto type = _.FindDef(type_id);
997   if (!type || spv::Op::OpTypeVoid == type->opcode()) {
998     return _.diag(SPV_ERROR_INVALID_ID, inst)
999            << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1000            << "s type is void.";
1001   }
1002 
1003   // validate storage class
1004   {
1005     uint32_t data_type;
1006     spv::StorageClass storage_class;
1007     if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
1008       return _.diag(SPV_ERROR_INVALID_ID, inst)
1009              << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1010              << " is not pointer type";
1011     }
1012 
1013     if (storage_class == spv::StorageClass::UniformConstant ||
1014         storage_class == spv::StorageClass::Input ||
1015         storage_class == spv::StorageClass::PushConstant) {
1016       return _.diag(SPV_ERROR_INVALID_ID, inst)
1017              << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1018              << " storage class is read-only";
1019     } else if (storage_class == spv::StorageClass::ShaderRecordBufferKHR) {
1020       return _.diag(SPV_ERROR_INVALID_ID, inst)
1021              << "ShaderRecordBufferKHR Storage Class variables are read only";
1022     } else if (storage_class == spv::StorageClass::HitAttributeKHR) {
1023       std::string errorVUID = _.VkErrorID(4703);
1024       _.function(inst->function()->id())
1025           ->RegisterExecutionModelLimitation(
1026               [errorVUID](spv::ExecutionModel model, std::string* message) {
1027                 if (model == spv::ExecutionModel::AnyHitKHR ||
1028                     model == spv::ExecutionModel::ClosestHitKHR) {
1029                   if (message) {
1030                     *message =
1031                         errorVUID +
1032                         "HitAttributeKHR Storage Class variables are read only "
1033                         "with AnyHitKHR and ClosestHitKHR";
1034                   }
1035                   return false;
1036                 }
1037                 return true;
1038               });
1039     }
1040 
1041     if (spvIsVulkanEnv(_.context()->target_env) &&
1042         storage_class == spv::StorageClass::Uniform) {
1043       auto base_ptr = _.TracePointer(pointer);
1044       if (base_ptr->opcode() == spv::Op::OpVariable) {
1045         // If it's not a variable a different check should catch the problem.
1046         auto base_type = _.FindDef(base_ptr->GetOperandAs<uint32_t>(0));
1047         // Get the pointed-to type.
1048         base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(2u));
1049         if (base_type->opcode() == spv::Op::OpTypeArray ||
1050             base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
1051           base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(1u));
1052         }
1053         if (_.HasDecoration(base_type->id(), spv::Decoration::Block)) {
1054           return _.diag(SPV_ERROR_INVALID_ID, inst)
1055                  << _.VkErrorID(6925)
1056                  << "In the Vulkan environment, cannot store to Uniform Blocks";
1057         }
1058       }
1059     }
1060   }
1061 
1062   const auto object_index = 1;
1063   const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
1064   const auto object = _.FindDef(object_id);
1065   if (!object || !object->type_id()) {
1066     return _.diag(SPV_ERROR_INVALID_ID, inst)
1067            << "OpStore Object <id> " << _.getIdName(object_id)
1068            << " is not an object.";
1069   }
1070   const auto object_type = _.FindDef(object->type_id());
1071   if (!object_type || spv::Op::OpTypeVoid == object_type->opcode()) {
1072     return _.diag(SPV_ERROR_INVALID_ID, inst)
1073            << "OpStore Object <id> " << _.getIdName(object_id)
1074            << "s type is void.";
1075   }
1076 
1077   if (type->id() != object_type->id()) {
1078     if (!_.options()->relax_struct_store ||
1079         type->opcode() != spv::Op::OpTypeStruct ||
1080         object_type->opcode() != spv::Op::OpTypeStruct) {
1081       return _.diag(SPV_ERROR_INVALID_ID, inst)
1082              << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1083              << "s type does not match Object <id> "
1084              << _.getIdName(object->id()) << "s type.";
1085     }
1086 
1087     // TODO: Check for layout compatible matricies and arrays as well.
1088     if (!AreLayoutCompatibleStructs(_, type, object_type)) {
1089       return _.diag(SPV_ERROR_INVALID_ID, inst)
1090              << "OpStore Pointer <id> " << _.getIdName(pointer_id)
1091              << "s layout does not match Object <id> "
1092              << _.getIdName(object->id()) << "s layout.";
1093     }
1094   }
1095 
1096   if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
1097 
1098   if (_.HasCapability(spv::Capability::Shader) &&
1099       _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
1100       object_type->opcode() != spv::Op::OpTypePointer) {
1101     if (object_type->opcode() != spv::Op::OpTypeInt &&
1102         object_type->opcode() != spv::Op::OpTypeFloat &&
1103         object_type->opcode() != spv::Op::OpTypeVector &&
1104         object_type->opcode() != spv::Op::OpTypeMatrix) {
1105       return _.diag(SPV_ERROR_INVALID_ID, inst)
1106              << "8- or 16-bit stores must be a scalar, vector or matrix type";
1107     }
1108   }
1109 
1110   return SPV_SUCCESS;
1111 }
1112 
ValidateCopyMemoryMemoryAccess(ValidationState_t & _,const Instruction * inst)1113 spv_result_t ValidateCopyMemoryMemoryAccess(ValidationState_t& _,
1114                                             const Instruction* inst) {
1115   assert(inst->opcode() == spv::Op::OpCopyMemory ||
1116          inst->opcode() == spv::Op::OpCopyMemorySized);
1117   const uint32_t first_access_index =
1118       inst->opcode() == spv::Op::OpCopyMemory ? 2 : 3;
1119   if (inst->operands().size() > first_access_index) {
1120     if (auto error = CheckMemoryAccess(_, inst, first_access_index))
1121       return error;
1122 
1123     const auto first_access = inst->GetOperandAs<uint32_t>(first_access_index);
1124     const uint32_t second_access_index =
1125         first_access_index + MemoryAccessNumWords(first_access);
1126     if (inst->operands().size() > second_access_index) {
1127       if (_.features().copy_memory_permits_two_memory_accesses) {
1128         if (auto error = CheckMemoryAccess(_, inst, second_access_index))
1129           return error;
1130 
1131         // In the two-access form in SPIR-V 1.4 and later:
1132         //  - the first is the target (write) access and it can't have
1133         //  make-visible.
1134         //  - the second is the source (read) access and it can't have
1135         //  make-available.
1136         if (first_access &
1137             uint32_t(spv::MemoryAccessMask::MakePointerVisibleKHR)) {
1138           return _.diag(SPV_ERROR_INVALID_DATA, inst)
1139                  << "Target memory access must not include "
1140                     "MakePointerVisibleKHR";
1141         }
1142         const auto second_access =
1143             inst->GetOperandAs<uint32_t>(second_access_index);
1144         if (second_access &
1145             uint32_t(spv::MemoryAccessMask::MakePointerAvailableKHR)) {
1146           return _.diag(SPV_ERROR_INVALID_DATA, inst)
1147                  << "Source memory access must not include "
1148                     "MakePointerAvailableKHR";
1149         }
1150       } else {
1151         return _.diag(SPV_ERROR_INVALID_DATA, inst)
1152                << spvOpcodeString(static_cast<spv::Op>(inst->opcode()))
1153                << " with two memory access operands requires SPIR-V 1.4 or "
1154                   "later";
1155       }
1156     }
1157   }
1158   return SPV_SUCCESS;
1159 }
1160 
ValidateCopyMemory(ValidationState_t & _,const Instruction * inst)1161 spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
1162   const auto target_index = 0;
1163   const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
1164   const auto target = _.FindDef(target_id);
1165   if (!target) {
1166     return _.diag(SPV_ERROR_INVALID_ID, inst)
1167            << "Target operand <id> " << _.getIdName(target_id)
1168            << " is not defined.";
1169   }
1170 
1171   const auto source_index = 1;
1172   const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
1173   const auto source = _.FindDef(source_id);
1174   if (!source) {
1175     return _.diag(SPV_ERROR_INVALID_ID, inst)
1176            << "Source operand <id> " << _.getIdName(source_id)
1177            << " is not defined.";
1178   }
1179 
1180   const auto target_pointer_type = _.FindDef(target->type_id());
1181   if (!target_pointer_type ||
1182       target_pointer_type->opcode() != spv::Op::OpTypePointer) {
1183     return _.diag(SPV_ERROR_INVALID_ID, inst)
1184            << "Target operand <id> " << _.getIdName(target_id)
1185            << " is not a pointer.";
1186   }
1187 
1188   const auto source_pointer_type = _.FindDef(source->type_id());
1189   if (!source_pointer_type ||
1190       source_pointer_type->opcode() != spv::Op::OpTypePointer) {
1191     return _.diag(SPV_ERROR_INVALID_ID, inst)
1192            << "Source operand <id> " << _.getIdName(source_id)
1193            << " is not a pointer.";
1194   }
1195 
1196   if (inst->opcode() == spv::Op::OpCopyMemory) {
1197     const auto target_type =
1198         _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
1199     if (!target_type || target_type->opcode() == spv::Op::OpTypeVoid) {
1200       return _.diag(SPV_ERROR_INVALID_ID, inst)
1201              << "Target operand <id> " << _.getIdName(target_id)
1202              << " cannot be a void pointer.";
1203     }
1204 
1205     const auto source_type =
1206         _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
1207     if (!source_type || source_type->opcode() == spv::Op::OpTypeVoid) {
1208       return _.diag(SPV_ERROR_INVALID_ID, inst)
1209              << "Source operand <id> " << _.getIdName(source_id)
1210              << " cannot be a void pointer.";
1211     }
1212 
1213     if (target_type->id() != source_type->id()) {
1214       return _.diag(SPV_ERROR_INVALID_ID, inst)
1215              << "Target <id> " << _.getIdName(source_id)
1216              << "s type does not match Source <id> "
1217              << _.getIdName(source_type->id()) << "s type.";
1218     }
1219   } else {
1220     const auto size_id = inst->GetOperandAs<uint32_t>(2);
1221     const auto size = _.FindDef(size_id);
1222     if (!size) {
1223       return _.diag(SPV_ERROR_INVALID_ID, inst)
1224              << "Size operand <id> " << _.getIdName(size_id)
1225              << " is not defined.";
1226     }
1227 
1228     const auto size_type = _.FindDef(size->type_id());
1229     if (!_.IsIntScalarType(size_type->id())) {
1230       return _.diag(SPV_ERROR_INVALID_ID, inst)
1231              << "Size operand <id> " << _.getIdName(size_id)
1232              << " must be a scalar integer type.";
1233     }
1234 
1235     bool is_zero = true;
1236     switch (size->opcode()) {
1237       case spv::Op::OpConstantNull:
1238         return _.diag(SPV_ERROR_INVALID_ID, inst)
1239                << "Size operand <id> " << _.getIdName(size_id)
1240                << " cannot be a constant zero.";
1241       case spv::Op::OpConstant:
1242         if (size_type->word(3) == 1 &&
1243             size->word(size->words().size() - 1) & 0x80000000) {
1244           return _.diag(SPV_ERROR_INVALID_ID, inst)
1245                  << "Size operand <id> " << _.getIdName(size_id)
1246                  << " cannot have the sign bit set to 1.";
1247         }
1248         for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
1249           is_zero &= (size->word(i) == 0);
1250         }
1251         if (is_zero) {
1252           return _.diag(SPV_ERROR_INVALID_ID, inst)
1253                  << "Size operand <id> " << _.getIdName(size_id)
1254                  << " cannot be a constant zero.";
1255         }
1256         break;
1257       default:
1258         // Cannot infer any other opcodes.
1259         break;
1260     }
1261   }
1262   if (auto error = ValidateCopyMemoryMemoryAccess(_, inst)) return error;
1263 
1264   // Get past the pointers to avoid checking a pointer copy.
1265   auto sub_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
1266   while (sub_type->opcode() == spv::Op::OpTypePointer) {
1267     sub_type = _.FindDef(sub_type->GetOperandAs<uint32_t>(2));
1268   }
1269   if (_.HasCapability(spv::Capability::Shader) &&
1270       _.ContainsLimitedUseIntOrFloatType(sub_type->id())) {
1271     return _.diag(SPV_ERROR_INVALID_ID, inst)
1272            << "Cannot copy memory of objects containing 8- or 16-bit types";
1273   }
1274 
1275   return SPV_SUCCESS;
1276 }
1277 
ValidateAccessChain(ValidationState_t & _,const Instruction * inst)1278 spv_result_t ValidateAccessChain(ValidationState_t& _,
1279                                  const Instruction* inst) {
1280   std::string instr_name =
1281       "Op" + std::string(spvOpcodeString(static_cast<spv::Op>(inst->opcode())));
1282 
1283   // The result type must be OpTypePointer.
1284   auto result_type = _.FindDef(inst->type_id());
1285   if (spv::Op::OpTypePointer != result_type->opcode()) {
1286     return _.diag(SPV_ERROR_INVALID_ID, inst)
1287            << "The Result Type of " << instr_name << " <id> "
1288            << _.getIdName(inst->id()) << " must be OpTypePointer. Found Op"
1289            << spvOpcodeString(static_cast<spv::Op>(result_type->opcode()))
1290            << ".";
1291   }
1292 
1293   // Result type is a pointer. Find out what it's pointing to.
1294   // This will be used to make sure the indexing results in the same type.
1295   // OpTypePointer word 3 is the type being pointed to.
1296   const auto result_type_pointee = _.FindDef(result_type->word(3));
1297 
1298   // Base must be a pointer, pointing to the base of a composite object.
1299   const auto base_index = 2;
1300   const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
1301   const auto base = _.FindDef(base_id);
1302   const auto base_type = _.FindDef(base->type_id());
1303   if (!base_type || spv::Op::OpTypePointer != base_type->opcode()) {
1304     return _.diag(SPV_ERROR_INVALID_ID, inst)
1305            << "The Base <id> " << _.getIdName(base_id) << " in " << instr_name
1306            << " instruction must be a pointer.";
1307   }
1308 
1309   // The result pointer storage class and base pointer storage class must match.
1310   // Word 2 of OpTypePointer is the Storage Class.
1311   auto result_type_storage_class = result_type->word(2);
1312   auto base_type_storage_class = base_type->word(2);
1313   if (result_type_storage_class != base_type_storage_class) {
1314     return _.diag(SPV_ERROR_INVALID_ID, inst)
1315            << "The result pointer storage class and base "
1316               "pointer storage class in "
1317            << instr_name << " do not match.";
1318   }
1319 
1320   // The type pointed to by OpTypePointer (word 3) must be a composite type.
1321   auto type_pointee = _.FindDef(base_type->word(3));
1322 
1323   // Check Universal Limit (SPIR-V Spec. Section 2.17).
1324   // The number of indexes passed to OpAccessChain may not exceed 255
1325   // The instruction includes 4 words + N words (for N indexes)
1326   size_t num_indexes = inst->words().size() - 4;
1327   if (inst->opcode() == spv::Op::OpPtrAccessChain ||
1328       inst->opcode() == spv::Op::OpInBoundsPtrAccessChain) {
1329     // In pointer access chains, the element operand is required, but not
1330     // counted as an index.
1331     --num_indexes;
1332   }
1333   const size_t num_indexes_limit =
1334       _.options()->universal_limits_.max_access_chain_indexes;
1335   if (num_indexes > num_indexes_limit) {
1336     return _.diag(SPV_ERROR_INVALID_ID, inst)
1337            << "The number of indexes in " << instr_name << " may not exceed "
1338            << num_indexes_limit << ". Found " << num_indexes << " indexes.";
1339   }
1340   // Indexes walk the type hierarchy to the desired depth, potentially down to
1341   // scalar granularity. The first index in Indexes will select the top-level
1342   // member/element/component/element of the base composite. All composite
1343   // constituents use zero-based numbering, as described by their OpType...
1344   // instruction. The second index will apply similarly to that result, and so
1345   // on. Once any non-composite type is reached, there must be no remaining
1346   // (unused) indexes.
1347   auto starting_index = 4;
1348   if (inst->opcode() == spv::Op::OpPtrAccessChain ||
1349       inst->opcode() == spv::Op::OpInBoundsPtrAccessChain) {
1350     ++starting_index;
1351   }
1352   for (size_t i = starting_index; i < inst->words().size(); ++i) {
1353     const uint32_t cur_word = inst->words()[i];
1354     // Earlier ID checks ensure that cur_word definition exists.
1355     auto cur_word_instr = _.FindDef(cur_word);
1356     // The index must be a scalar integer type (See OpAccessChain in the Spec.)
1357     auto index_type = _.FindDef(cur_word_instr->type_id());
1358     if (!index_type || spv::Op::OpTypeInt != index_type->opcode()) {
1359       return _.diag(SPV_ERROR_INVALID_ID, inst)
1360              << "Indexes passed to " << instr_name
1361              << " must be of type integer.";
1362     }
1363     switch (type_pointee->opcode()) {
1364       case spv::Op::OpTypeMatrix:
1365       case spv::Op::OpTypeVector:
1366       case spv::Op::OpTypeCooperativeMatrixNV:
1367       case spv::Op::OpTypeCooperativeMatrixKHR:
1368       case spv::Op::OpTypeArray:
1369       case spv::Op::OpTypeRuntimeArray: {
1370         // In OpTypeMatrix, OpTypeVector, spv::Op::OpTypeCooperativeMatrixNV,
1371         // OpTypeArray, and OpTypeRuntimeArray, word 2 is the Element Type.
1372         type_pointee = _.FindDef(type_pointee->word(2));
1373         break;
1374       }
1375       case spv::Op::OpTypeStruct: {
1376         // In case of structures, there is an additional constraint on the
1377         // index: the index must be an OpConstant.
1378         int64_t cur_index;
1379         if (!_.EvalConstantValInt64(cur_word, &cur_index)) {
1380           return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1381                  << "The <id> passed to " << instr_name
1382                  << " to index into a "
1383                     "structure must be an OpConstant.";
1384         }
1385 
1386         // The index points to the struct member we want, therefore, the index
1387         // should be less than the number of struct members.
1388         const int64_t num_struct_members =
1389             static_cast<int64_t>(type_pointee->words().size() - 2);
1390         if (cur_index >= num_struct_members || cur_index < 0) {
1391           return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1392                  << "Index is out of bounds: " << instr_name
1393                  << " cannot find index " << cur_index
1394                  << " into the structure <id> "
1395                  << _.getIdName(type_pointee->id()) << ". This structure has "
1396                  << num_struct_members << " members. Largest valid index is "
1397                  << num_struct_members - 1 << ".";
1398         }
1399         // Struct members IDs start at word 2 of OpTypeStruct.
1400         const size_t word_index = static_cast<size_t>(cur_index) + 2;
1401         auto structMemberId = type_pointee->word(word_index);
1402         type_pointee = _.FindDef(structMemberId);
1403         break;
1404       }
1405       default: {
1406         // Give an error. reached non-composite type while indexes still remain.
1407         return _.diag(SPV_ERROR_INVALID_ID, inst)
1408                << instr_name
1409                << " reached non-composite type while indexes "
1410                   "still remain to be traversed.";
1411       }
1412     }
1413   }
1414   // At this point, we have fully walked down from the base using the indices.
1415   // The type being pointed to should be the same as the result type.
1416   if (type_pointee->id() != result_type_pointee->id()) {
1417     return _.diag(SPV_ERROR_INVALID_ID, inst)
1418            << instr_name << " result type (Op"
1419            << spvOpcodeString(
1420                   static_cast<spv::Op>(result_type_pointee->opcode()))
1421            << ") does not match the type that results from indexing into the "
1422               "base "
1423               "<id> (Op"
1424            << spvOpcodeString(static_cast<spv::Op>(type_pointee->opcode()))
1425            << ").";
1426   }
1427 
1428   return SPV_SUCCESS;
1429 }
1430 
ValidateRawAccessChain(ValidationState_t & _,const Instruction * inst)1431 spv_result_t ValidateRawAccessChain(ValidationState_t& _,
1432                                     const Instruction* inst) {
1433   std::string instr_name = "Op" + std::string(spvOpcodeString(inst->opcode()));
1434 
1435   // The result type must be OpTypePointer.
1436   const auto result_type = _.FindDef(inst->type_id());
1437   if (spv::Op::OpTypePointer != result_type->opcode()) {
1438     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1439            << "The Result Type of " << instr_name << " <id> "
1440            << _.getIdName(inst->id()) << " must be OpTypePointer. Found Op"
1441            << spvOpcodeString(result_type->opcode()) << '.';
1442   }
1443 
1444   // The pointed storage class must be valid.
1445   const auto storage_class = result_type->GetOperandAs<spv::StorageClass>(1);
1446   if (storage_class != spv::StorageClass::StorageBuffer &&
1447       storage_class != spv::StorageClass::PhysicalStorageBuffer &&
1448       storage_class != spv::StorageClass::Uniform) {
1449     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1450            << "The Result Type of " << instr_name << " <id> "
1451            << _.getIdName(inst->id())
1452            << " must point to a storage class of "
1453               "StorageBuffer, PhysicalStorageBuffer, or Uniform.";
1454   }
1455 
1456   // The pointed type must not be one in the list below.
1457   const auto result_type_pointee =
1458       _.FindDef(result_type->GetOperandAs<uint32_t>(2));
1459   if (result_type_pointee->opcode() == spv::Op::OpTypeArray ||
1460       result_type_pointee->opcode() == spv::Op::OpTypeMatrix ||
1461       result_type_pointee->opcode() == spv::Op::OpTypeStruct) {
1462     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1463            << "The Result Type of " << instr_name << " <id> "
1464            << _.getIdName(inst->id())
1465            << " must not point to "
1466               "OpTypeArray, OpTypeMatrix, or OpTypeStruct.";
1467   }
1468 
1469   // Validate Stride is a OpConstant.
1470   const auto stride = _.FindDef(inst->GetOperandAs<uint32_t>(3));
1471   if (stride->opcode() != spv::Op::OpConstant) {
1472     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1473            << "The Stride of " << instr_name << " <id> "
1474            << _.getIdName(inst->id()) << " must be OpConstant. Found Op"
1475            << spvOpcodeString(stride->opcode()) << '.';
1476   }
1477   // Stride type must be OpTypeInt
1478   const auto stride_type = _.FindDef(stride->type_id());
1479   if (stride_type->opcode() != spv::Op::OpTypeInt) {
1480     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1481            << "The type of Stride of " << instr_name << " <id> "
1482            << _.getIdName(inst->id()) << " must be OpTypeInt. Found Op"
1483            << spvOpcodeString(stride_type->opcode()) << '.';
1484   }
1485 
1486   // Index and Offset type must be OpTypeInt with a width of 32
1487   const auto ValidateType = [&](const char* name,
1488                                 int operandIndex) -> spv_result_t {
1489     const auto value = _.FindDef(inst->GetOperandAs<uint32_t>(operandIndex));
1490     const auto value_type = _.FindDef(value->type_id());
1491     if (value_type->opcode() != spv::Op::OpTypeInt) {
1492       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1493              << "The type of " << name << " of " << instr_name << " <id> "
1494              << _.getIdName(inst->id()) << " must be OpTypeInt. Found Op"
1495              << spvOpcodeString(value_type->opcode()) << '.';
1496     }
1497     const auto width = value_type->GetOperandAs<uint32_t>(1);
1498     if (width != 32) {
1499       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1500              << "The integer width of " << name << " of " << instr_name
1501              << " <id> " << _.getIdName(inst->id()) << " must be 32. Found "
1502              << width << '.';
1503     }
1504     return SPV_SUCCESS;
1505   };
1506   spv_result_t result;
1507   result = ValidateType("Index", 4);
1508   if (result != SPV_SUCCESS) {
1509     return result;
1510   }
1511   result = ValidateType("Offset", 5);
1512   if (result != SPV_SUCCESS) {
1513     return result;
1514   }
1515 
1516   uint32_t access_operands = 0;
1517   if (inst->operands().size() >= 7) {
1518     access_operands = inst->GetOperandAs<uint32_t>(6);
1519   }
1520   if (access_operands &
1521       uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerElementNV)) {
1522     uint64_t stride_value = 0;
1523     if (_.EvalConstantValUint64(stride->id(), &stride_value) &&
1524         stride_value == 0) {
1525       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1526              << "Stride must not be zero when per-element robustness is used.";
1527     }
1528   }
1529   if (access_operands &
1530           uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerComponentNV) ||
1531       access_operands &
1532           uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerElementNV)) {
1533     if (storage_class == spv::StorageClass::PhysicalStorageBuffer) {
1534       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1535              << "Storage class cannot be PhysicalStorageBuffer when "
1536                 "raw access chain robustness is used.";
1537     }
1538   }
1539   if (access_operands &
1540           uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerComponentNV) &&
1541       access_operands &
1542           uint32_t(spv::RawAccessChainOperandsMask::RobustnessPerElementNV)) {
1543     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1544            << "Per-component robustness and per-element robustness are "
1545               "mutually exclusive.";
1546   }
1547 
1548   return SPV_SUCCESS;
1549 }
1550 
ValidatePtrAccessChain(ValidationState_t & _,const Instruction * inst)1551 spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
1552                                     const Instruction* inst) {
1553   if (_.addressing_model() == spv::AddressingModel::Logical) {
1554     if (!_.features().variable_pointers) {
1555       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1556              << "Generating variable pointers requires capability "
1557              << "VariablePointers or VariablePointersStorageBuffer";
1558     }
1559   }
1560 
1561   // Need to call first, will make sure Base is a valid ID
1562   if (auto error = ValidateAccessChain(_, inst)) return error;
1563 
1564   const auto base_id = inst->GetOperandAs<uint32_t>(2);
1565   const auto base = _.FindDef(base_id);
1566   const auto base_type = _.FindDef(base->type_id());
1567   const auto base_type_storage_class =
1568       base_type->GetOperandAs<spv::StorageClass>(1);
1569 
1570   if (_.HasCapability(spv::Capability::Shader) &&
1571       (base_type_storage_class == spv::StorageClass::Uniform ||
1572        base_type_storage_class == spv::StorageClass::StorageBuffer ||
1573        base_type_storage_class == spv::StorageClass::PhysicalStorageBuffer ||
1574        base_type_storage_class == spv::StorageClass::PushConstant ||
1575        (_.HasCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR) &&
1576         base_type_storage_class == spv::StorageClass::Workgroup)) &&
1577       !_.HasDecoration(base_type->id(), spv::Decoration::ArrayStride)) {
1578     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1579            << "OpPtrAccessChain must have a Base whose type is decorated "
1580               "with ArrayStride";
1581   }
1582 
1583   if (spvIsVulkanEnv(_.context()->target_env)) {
1584     if (base_type_storage_class == spv::StorageClass::Workgroup) {
1585       if (!_.HasCapability(spv::Capability::VariablePointers)) {
1586         return _.diag(SPV_ERROR_INVALID_DATA, inst)
1587                << _.VkErrorID(7651)
1588                << "OpPtrAccessChain Base operand pointing to Workgroup "
1589                   "storage class must use VariablePointers capability";
1590       }
1591     } else if (base_type_storage_class == spv::StorageClass::StorageBuffer) {
1592       if (!_.features().variable_pointers) {
1593         return _.diag(SPV_ERROR_INVALID_DATA, inst)
1594                << _.VkErrorID(7652)
1595                << "OpPtrAccessChain Base operand pointing to StorageBuffer "
1596                   "storage class must use VariablePointers or "
1597                   "VariablePointersStorageBuffer capability";
1598       }
1599     } else if (base_type_storage_class !=
1600                spv::StorageClass::PhysicalStorageBuffer) {
1601       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1602              << _.VkErrorID(7650)
1603              << "OpPtrAccessChain Base operand must point to Workgroup, "
1604                 "StorageBuffer, or PhysicalStorageBuffer storage class";
1605     }
1606   }
1607 
1608   return SPV_SUCCESS;
1609 }
1610 
ValidateArrayLength(ValidationState_t & state,const Instruction * inst)1611 spv_result_t ValidateArrayLength(ValidationState_t& state,
1612                                  const Instruction* inst) {
1613   std::string instr_name =
1614       "Op" + std::string(spvOpcodeString(static_cast<spv::Op>(inst->opcode())));
1615 
1616   // Result type must be a 32-bit unsigned int.
1617   auto result_type = state.FindDef(inst->type_id());
1618   if (result_type->opcode() != spv::Op::OpTypeInt ||
1619       result_type->GetOperandAs<uint32_t>(1) != 32 ||
1620       result_type->GetOperandAs<uint32_t>(2) != 0) {
1621     return state.diag(SPV_ERROR_INVALID_ID, inst)
1622            << "The Result Type of " << instr_name << " <id> "
1623            << state.getIdName(inst->id())
1624            << " must be OpTypeInt with width 32 and signedness 0.";
1625   }
1626 
1627   // The structure that is passed in must be an pointer to a structure, whose
1628   // last element is a runtime array.
1629   auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
1630   auto pointer_type = state.FindDef(pointer->type_id());
1631   if (pointer_type->opcode() != spv::Op::OpTypePointer) {
1632     return state.diag(SPV_ERROR_INVALID_ID, inst)
1633            << "The Structure's type in " << instr_name << " <id> "
1634            << state.getIdName(inst->id())
1635            << " must be a pointer to an OpTypeStruct.";
1636   }
1637 
1638   auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
1639   if (structure_type->opcode() != spv::Op::OpTypeStruct) {
1640     return state.diag(SPV_ERROR_INVALID_ID, inst)
1641            << "The Structure's type in " << instr_name << " <id> "
1642            << state.getIdName(inst->id())
1643            << " must be a pointer to an OpTypeStruct.";
1644   }
1645 
1646   auto num_of_members = structure_type->operands().size() - 1;
1647   auto last_member =
1648       state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
1649   if (last_member->opcode() != spv::Op::OpTypeRuntimeArray) {
1650     return state.diag(SPV_ERROR_INVALID_ID, inst)
1651            << "The Structure's last member in " << instr_name << " <id> "
1652            << state.getIdName(inst->id()) << " must be an OpTypeRuntimeArray.";
1653   }
1654 
1655   // The array member must the index of the last element (the run time
1656   // array).
1657   if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
1658     return state.diag(SPV_ERROR_INVALID_ID, inst)
1659            << "The array member in " << instr_name << " <id> "
1660            << state.getIdName(inst->id())
1661            << " must be an the last member of the struct.";
1662   }
1663   return SPV_SUCCESS;
1664 }
1665 
ValidateCooperativeMatrixLengthNV(ValidationState_t & state,const Instruction * inst)1666 spv_result_t ValidateCooperativeMatrixLengthNV(ValidationState_t& state,
1667                                                const Instruction* inst) {
1668   std::string instr_name =
1669       "Op" + std::string(spvOpcodeString(static_cast<spv::Op>(inst->opcode())));
1670 
1671   // Result type must be a 32-bit unsigned int.
1672   auto result_type = state.FindDef(inst->type_id());
1673   if (result_type->opcode() != spv::Op::OpTypeInt ||
1674       result_type->GetOperandAs<uint32_t>(1) != 32 ||
1675       result_type->GetOperandAs<uint32_t>(2) != 0) {
1676     return state.diag(SPV_ERROR_INVALID_ID, inst)
1677            << "The Result Type of " << instr_name << " <id> "
1678            << state.getIdName(inst->id())
1679            << " must be OpTypeInt with width 32 and signedness 0.";
1680   }
1681 
1682   bool isKhr = inst->opcode() == spv::Op::OpCooperativeMatrixLengthKHR;
1683   auto type_id = inst->GetOperandAs<uint32_t>(2);
1684   auto type = state.FindDef(type_id);
1685   if (isKhr && type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
1686     return state.diag(SPV_ERROR_INVALID_ID, inst)
1687            << "The type in " << instr_name << " <id> "
1688            << state.getIdName(type_id)
1689            << " must be OpTypeCooperativeMatrixKHR.";
1690   } else if (!isKhr && type->opcode() != spv::Op::OpTypeCooperativeMatrixNV) {
1691     return state.diag(SPV_ERROR_INVALID_ID, inst)
1692            << "The type in " << instr_name << " <id> "
1693            << state.getIdName(type_id) << " must be OpTypeCooperativeMatrixNV.";
1694   }
1695   return SPV_SUCCESS;
1696 }
1697 
ValidateCooperativeMatrixLoadStoreNV(ValidationState_t & _,const Instruction * inst)1698 spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
1699                                                   const Instruction* inst) {
1700   uint32_t type_id;
1701   const char* opname;
1702   if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) {
1703     type_id = inst->type_id();
1704     opname = "spv::Op::OpCooperativeMatrixLoadNV";
1705   } else {
1706     // get Object operand's type
1707     type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
1708     opname = "spv::Op::OpCooperativeMatrixStoreNV";
1709   }
1710 
1711   auto matrix_type = _.FindDef(type_id);
1712 
1713   if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixNV) {
1714     if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) {
1715       return _.diag(SPV_ERROR_INVALID_ID, inst)
1716              << "spv::Op::OpCooperativeMatrixLoadNV Result Type <id> "
1717              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1718     } else {
1719       return _.diag(SPV_ERROR_INVALID_ID, inst)
1720              << "spv::Op::OpCooperativeMatrixStoreNV Object type <id> "
1721              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1722     }
1723   }
1724 
1725   const auto pointer_index =
1726       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 2u : 0u;
1727   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
1728   const auto pointer = _.FindDef(pointer_id);
1729   if (!pointer ||
1730       ((_.addressing_model() == spv::AddressingModel::Logical) &&
1731        ((!_.features().variable_pointers &&
1732          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
1733         (_.features().variable_pointers &&
1734          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
1735     return _.diag(SPV_ERROR_INVALID_ID, inst)
1736            << opname << " Pointer <id> " << _.getIdName(pointer_id)
1737            << " is not a logical pointer.";
1738   }
1739 
1740   const auto pointer_type_id = pointer->type_id();
1741   const auto pointer_type = _.FindDef(pointer_type_id);
1742   if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
1743     return _.diag(SPV_ERROR_INVALID_ID, inst)
1744            << opname << " type for pointer <id> " << _.getIdName(pointer_id)
1745            << " is not a pointer type.";
1746   }
1747 
1748   const auto storage_class_index = 1u;
1749   const auto storage_class =
1750       pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
1751 
1752   if (storage_class != spv::StorageClass::Workgroup &&
1753       storage_class != spv::StorageClass::StorageBuffer &&
1754       storage_class != spv::StorageClass::PhysicalStorageBuffer) {
1755     return _.diag(SPV_ERROR_INVALID_ID, inst)
1756            << opname << " storage class for pointer type <id> "
1757            << _.getIdName(pointer_type_id)
1758            << " is not Workgroup or StorageBuffer.";
1759   }
1760 
1761   const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
1762   const auto pointee_type = _.FindDef(pointee_id);
1763   if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
1764                          _.IsFloatScalarOrVectorType(pointee_id))) {
1765     return _.diag(SPV_ERROR_INVALID_ID, inst)
1766            << opname << " Pointer <id> " << _.getIdName(pointer->id())
1767            << "s Type must be a scalar or vector type.";
1768   }
1769 
1770   const auto stride_index =
1771       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 3u : 2u;
1772   const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
1773   const auto stride = _.FindDef(stride_id);
1774   if (!stride || !_.IsIntScalarType(stride->type_id())) {
1775     return _.diag(SPV_ERROR_INVALID_ID, inst)
1776            << "Stride operand <id> " << _.getIdName(stride_id)
1777            << " must be a scalar integer type.";
1778   }
1779 
1780   const auto colmajor_index =
1781       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 4u : 3u;
1782   const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
1783   const auto colmajor = _.FindDef(colmajor_id);
1784   if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
1785       !(spvOpcodeIsConstant(colmajor->opcode()) ||
1786         spvOpcodeIsSpecConstant(colmajor->opcode()))) {
1787     return _.diag(SPV_ERROR_INVALID_ID, inst)
1788            << "Column Major operand <id> " << _.getIdName(colmajor_id)
1789            << " must be a boolean constant instruction.";
1790   }
1791 
1792   const auto memory_access_index =
1793       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 5u : 4u;
1794   if (inst->operands().size() > memory_access_index) {
1795     if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
1796       return error;
1797   }
1798 
1799   return SPV_SUCCESS;
1800 }
1801 
ValidateCooperativeMatrixLoadStoreKHR(ValidationState_t & _,const Instruction * inst)1802 spv_result_t ValidateCooperativeMatrixLoadStoreKHR(ValidationState_t& _,
1803                                                    const Instruction* inst) {
1804   uint32_t type_id;
1805   const char* opname;
1806   if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
1807     type_id = inst->type_id();
1808     opname = "spv::Op::OpCooperativeMatrixLoadKHR";
1809   } else {
1810     // get Object operand's type
1811     type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
1812     opname = "spv::Op::OpCooperativeMatrixStoreKHR";
1813   }
1814 
1815   auto matrix_type = _.FindDef(type_id);
1816 
1817   if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
1818     if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
1819       return _.diag(SPV_ERROR_INVALID_ID, inst)
1820              << "spv::Op::OpCooperativeMatrixLoadKHR Result Type <id> "
1821              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1822     } else {
1823       return _.diag(SPV_ERROR_INVALID_ID, inst)
1824              << "spv::Op::OpCooperativeMatrixStoreKHR Object type <id> "
1825              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1826     }
1827   }
1828 
1829   const auto pointer_index =
1830       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 2u : 0u;
1831   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
1832   const auto pointer = _.FindDef(pointer_id);
1833   if (!pointer ||
1834       ((_.addressing_model() == spv::AddressingModel::Logical) &&
1835        ((!_.features().variable_pointers &&
1836          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
1837         (_.features().variable_pointers &&
1838          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
1839     return _.diag(SPV_ERROR_INVALID_ID, inst)
1840            << opname << " Pointer <id> " << _.getIdName(pointer_id)
1841            << " is not a logical pointer.";
1842   }
1843 
1844   const auto pointer_type_id = pointer->type_id();
1845   const auto pointer_type = _.FindDef(pointer_type_id);
1846   if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
1847     return _.diag(SPV_ERROR_INVALID_ID, inst)
1848            << opname << " type for pointer <id> " << _.getIdName(pointer_id)
1849            << " is not a pointer type.";
1850   }
1851 
1852   const auto storage_class_index = 1u;
1853   const auto storage_class =
1854       pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
1855 
1856   if (storage_class != spv::StorageClass::Workgroup &&
1857       storage_class != spv::StorageClass::StorageBuffer &&
1858       storage_class != spv::StorageClass::PhysicalStorageBuffer) {
1859     return _.diag(SPV_ERROR_INVALID_ID, inst)
1860            << _.VkErrorID(8973) << opname
1861            << " storage class for pointer type <id> "
1862            << _.getIdName(pointer_type_id)
1863            << " is not Workgroup, StorageBuffer, or PhysicalStorageBuffer.";
1864   }
1865 
1866   const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
1867   const auto pointee_type = _.FindDef(pointee_id);
1868   if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
1869                          _.IsFloatScalarOrVectorType(pointee_id))) {
1870     return _.diag(SPV_ERROR_INVALID_ID, inst)
1871            << opname << " Pointer <id> " << _.getIdName(pointer->id())
1872            << "s Type must be a scalar or vector type.";
1873   }
1874 
1875   const auto layout_index =
1876       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 3u : 2u;
1877   const auto colmajor_id = inst->GetOperandAs<uint32_t>(layout_index);
1878   const auto colmajor = _.FindDef(colmajor_id);
1879   if (!colmajor || !_.IsIntScalarType(colmajor->type_id()) ||
1880       !(spvOpcodeIsConstant(colmajor->opcode()) ||
1881         spvOpcodeIsSpecConstant(colmajor->opcode()))) {
1882     return _.diag(SPV_ERROR_INVALID_ID, inst)
1883            << "MemoryLayout operand <id> " << _.getIdName(colmajor_id)
1884            << " must be a 32-bit integer constant instruction.";
1885   }
1886 
1887   const auto stride_index =
1888       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 4u : 3u;
1889   if (inst->operands().size() > stride_index) {
1890     const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
1891     const auto stride = _.FindDef(stride_id);
1892     if (!stride || !_.IsIntScalarType(stride->type_id())) {
1893       return _.diag(SPV_ERROR_INVALID_ID, inst)
1894              << "Stride operand <id> " << _.getIdName(stride_id)
1895              << " must be a scalar integer type.";
1896     }
1897   }
1898 
1899   const auto memory_access_index =
1900       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 5u : 4u;
1901   if (inst->operands().size() > memory_access_index) {
1902     if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
1903       return error;
1904   }
1905 
1906   return SPV_SUCCESS;
1907 }
1908 
ValidatePtrComparison(ValidationState_t & _,const Instruction * inst)1909 spv_result_t ValidatePtrComparison(ValidationState_t& _,
1910                                    const Instruction* inst) {
1911   if (_.addressing_model() == spv::AddressingModel::Logical &&
1912       !_.features().variable_pointers) {
1913     return _.diag(SPV_ERROR_INVALID_ID, inst)
1914            << "Instruction cannot for logical addressing model be used without "
1915               "a variable pointers capability";
1916   }
1917 
1918   const auto result_type = _.FindDef(inst->type_id());
1919   if (inst->opcode() == spv::Op::OpPtrDiff) {
1920     if (!result_type || result_type->opcode() != spv::Op::OpTypeInt) {
1921       return _.diag(SPV_ERROR_INVALID_ID, inst)
1922              << "Result Type must be an integer scalar";
1923     }
1924   } else {
1925     if (!result_type || result_type->opcode() != spv::Op::OpTypeBool) {
1926       return _.diag(SPV_ERROR_INVALID_ID, inst)
1927              << "Result Type must be OpTypeBool";
1928     }
1929   }
1930 
1931   const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
1932   const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
1933   if (!op1 || !op2 || op1->type_id() != op2->type_id()) {
1934     return _.diag(SPV_ERROR_INVALID_ID, inst)
1935            << "The types of Operand 1 and Operand 2 must match";
1936   }
1937   const auto op1_type = _.FindDef(op1->type_id());
1938   if (!op1_type || op1_type->opcode() != spv::Op::OpTypePointer) {
1939     return _.diag(SPV_ERROR_INVALID_ID, inst)
1940            << "Operand type must be a pointer";
1941   }
1942 
1943   spv::StorageClass sc = op1_type->GetOperandAs<spv::StorageClass>(1u);
1944   if (_.addressing_model() == spv::AddressingModel::Logical) {
1945     if (sc != spv::StorageClass::Workgroup &&
1946         sc != spv::StorageClass::StorageBuffer) {
1947       return _.diag(SPV_ERROR_INVALID_ID, inst)
1948              << "Invalid pointer storage class";
1949     }
1950 
1951     if (sc == spv::StorageClass::Workgroup &&
1952         !_.HasCapability(spv::Capability::VariablePointers)) {
1953       return _.diag(SPV_ERROR_INVALID_ID, inst)
1954              << "Workgroup storage class pointer requires VariablePointers "
1955                 "capability to be specified";
1956     }
1957   } else if (sc == spv::StorageClass::PhysicalStorageBuffer) {
1958     return _.diag(SPV_ERROR_INVALID_ID, inst)
1959            << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
1960   }
1961 
1962   return SPV_SUCCESS;
1963 }
1964 
1965 }  // namespace
1966 
MemoryPass(ValidationState_t & _,const Instruction * inst)1967 spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
1968   switch (inst->opcode()) {
1969     case spv::Op::OpVariable:
1970       if (auto error = ValidateVariable(_, inst)) return error;
1971       break;
1972     case spv::Op::OpLoad:
1973       if (auto error = ValidateLoad(_, inst)) return error;
1974       break;
1975     case spv::Op::OpStore:
1976       if (auto error = ValidateStore(_, inst)) return error;
1977       break;
1978     case spv::Op::OpCopyMemory:
1979     case spv::Op::OpCopyMemorySized:
1980       if (auto error = ValidateCopyMemory(_, inst)) return error;
1981       break;
1982     case spv::Op::OpPtrAccessChain:
1983       if (auto error = ValidatePtrAccessChain(_, inst)) return error;
1984       break;
1985     case spv::Op::OpAccessChain:
1986     case spv::Op::OpInBoundsAccessChain:
1987     case spv::Op::OpInBoundsPtrAccessChain:
1988       if (auto error = ValidateAccessChain(_, inst)) return error;
1989       break;
1990     case spv::Op::OpRawAccessChainNV:
1991       if (auto error = ValidateRawAccessChain(_, inst)) return error;
1992       break;
1993     case spv::Op::OpArrayLength:
1994       if (auto error = ValidateArrayLength(_, inst)) return error;
1995       break;
1996     case spv::Op::OpCooperativeMatrixLoadNV:
1997     case spv::Op::OpCooperativeMatrixStoreNV:
1998       if (auto error = ValidateCooperativeMatrixLoadStoreNV(_, inst))
1999         return error;
2000       break;
2001     case spv::Op::OpCooperativeMatrixLengthKHR:
2002     case spv::Op::OpCooperativeMatrixLengthNV:
2003       if (auto error = ValidateCooperativeMatrixLengthNV(_, inst)) return error;
2004       break;
2005     case spv::Op::OpCooperativeMatrixLoadKHR:
2006     case spv::Op::OpCooperativeMatrixStoreKHR:
2007       if (auto error = ValidateCooperativeMatrixLoadStoreKHR(_, inst))
2008         return error;
2009       break;
2010     case spv::Op::OpPtrEqual:
2011     case spv::Op::OpPtrNotEqual:
2012     case spv::Op::OpPtrDiff:
2013       if (auto error = ValidatePtrComparison(_, inst)) return error;
2014       break;
2015     case spv::Op::OpImageTexelPointer:
2016     case spv::Op::OpGenericPtrMemSemantics:
2017     default:
2018       break;
2019   }
2020 
2021   return SPV_SUCCESS;
2022 }
2023 }  // namespace val
2024 }  // namespace spvtools
2025