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