• 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         if (spv::Op::OpConstant != cur_word_instr->opcode()) {
1378           return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1379                  << "The <id> passed to " << instr_name
1380                  << " to index into a "
1381                     "structure must be an OpConstant.";
1382         }
1383         // Get the index value from the OpConstant (word 3 of OpConstant).
1384         // OpConstant could be a signed integer. But it's okay to treat it as
1385         // unsigned because a negative constant int would never be seen as
1386         // correct as a struct offset, since structs can't have more than 2
1387         // billion members.
1388         const uint32_t cur_index = cur_word_instr->word(3);
1389         // The index points to the struct member we want, therefore, the index
1390         // should be less than the number of struct members.
1391         const uint32_t num_struct_members =
1392             static_cast<uint32_t>(type_pointee->words().size() - 2);
1393         if (cur_index >= num_struct_members) {
1394           return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1395                  << "Index is out of bounds: " << instr_name
1396                  << " can not find index " << cur_index
1397                  << " into the structure <id> "
1398                  << _.getIdName(type_pointee->id()) << ". This structure has "
1399                  << num_struct_members << " members. Largest valid index is "
1400                  << num_struct_members - 1 << ".";
1401         }
1402         // Struct members IDs start at word 2 of OpTypeStruct.
1403         auto structMemberId = type_pointee->word(cur_index + 2);
1404         type_pointee = _.FindDef(structMemberId);
1405         break;
1406       }
1407       default: {
1408         // Give an error. reached non-composite type while indexes still remain.
1409         return _.diag(SPV_ERROR_INVALID_ID, inst)
1410                << instr_name
1411                << " reached non-composite type while indexes "
1412                   "still remain to be traversed.";
1413       }
1414     }
1415   }
1416   // At this point, we have fully walked down from the base using the indeces.
1417   // The type being pointed to should be the same as the result type.
1418   if (type_pointee->id() != result_type_pointee->id()) {
1419     return _.diag(SPV_ERROR_INVALID_ID, inst)
1420            << instr_name << " result type (Op"
1421            << spvOpcodeString(
1422                   static_cast<spv::Op>(result_type_pointee->opcode()))
1423            << ") does not match the type that results from indexing into the "
1424               "base "
1425               "<id> (Op"
1426            << spvOpcodeString(static_cast<spv::Op>(type_pointee->opcode()))
1427            << ").";
1428   }
1429 
1430   return SPV_SUCCESS;
1431 }
1432 
ValidatePtrAccessChain(ValidationState_t & _,const Instruction * inst)1433 spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
1434                                     const Instruction* inst) {
1435   if (_.addressing_model() == spv::AddressingModel::Logical) {
1436     if (!_.features().variable_pointers) {
1437       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1438              << "Generating variable pointers requires capability "
1439              << "VariablePointers or VariablePointersStorageBuffer";
1440     }
1441   }
1442 
1443   // Need to call first, will make sure Base is a valid ID
1444   if (auto error = ValidateAccessChain(_, inst)) return error;
1445 
1446   const auto base_id = inst->GetOperandAs<uint32_t>(2);
1447   const auto base = _.FindDef(base_id);
1448   const auto base_type = _.FindDef(base->type_id());
1449   const auto base_type_storage_class =
1450       base_type->GetOperandAs<spv::StorageClass>(1);
1451 
1452   if (_.HasCapability(spv::Capability::Shader) &&
1453       (base_type_storage_class == spv::StorageClass::Uniform ||
1454        base_type_storage_class == spv::StorageClass::StorageBuffer ||
1455        base_type_storage_class == spv::StorageClass::PhysicalStorageBuffer ||
1456        base_type_storage_class == spv::StorageClass::PushConstant ||
1457        (_.HasCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR) &&
1458         base_type_storage_class == spv::StorageClass::Workgroup)) &&
1459       !_.HasDecoration(base_type->id(), spv::Decoration::ArrayStride)) {
1460     return _.diag(SPV_ERROR_INVALID_DATA, inst)
1461            << "OpPtrAccessChain must have a Base whose type is decorated "
1462               "with ArrayStride";
1463   }
1464 
1465   if (spvIsVulkanEnv(_.context()->target_env)) {
1466     if (base_type_storage_class == spv::StorageClass::Workgroup) {
1467       if (!_.HasCapability(spv::Capability::VariablePointers)) {
1468         return _.diag(SPV_ERROR_INVALID_DATA, inst)
1469                << _.VkErrorID(7651)
1470                << "OpPtrAccessChain Base operand pointing to Workgroup "
1471                   "storage class must use VariablePointers capability";
1472       }
1473     } else if (base_type_storage_class == spv::StorageClass::StorageBuffer) {
1474       if (!_.features().variable_pointers) {
1475         return _.diag(SPV_ERROR_INVALID_DATA, inst)
1476                << _.VkErrorID(7652)
1477                << "OpPtrAccessChain Base operand pointing to StorageBuffer "
1478                   "storage class must use VariablePointers or "
1479                   "VariablePointersStorageBuffer capability";
1480       }
1481     } else if (base_type_storage_class !=
1482                spv::StorageClass::PhysicalStorageBuffer) {
1483       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1484              << _.VkErrorID(7650)
1485              << "OpPtrAccessChain Base operand must point to Workgroup, "
1486                 "StorageBuffer, or PhysicalStorageBuffer storage class";
1487     }
1488   }
1489 
1490   return SPV_SUCCESS;
1491 }
1492 
ValidateArrayLength(ValidationState_t & state,const Instruction * inst)1493 spv_result_t ValidateArrayLength(ValidationState_t& state,
1494                                  const Instruction* inst) {
1495   std::string instr_name =
1496       "Op" + std::string(spvOpcodeString(static_cast<spv::Op>(inst->opcode())));
1497 
1498   // Result type must be a 32-bit unsigned int.
1499   auto result_type = state.FindDef(inst->type_id());
1500   if (result_type->opcode() != spv::Op::OpTypeInt ||
1501       result_type->GetOperandAs<uint32_t>(1) != 32 ||
1502       result_type->GetOperandAs<uint32_t>(2) != 0) {
1503     return state.diag(SPV_ERROR_INVALID_ID, inst)
1504            << "The Result Type of " << instr_name << " <id> "
1505            << state.getIdName(inst->id())
1506            << " must be OpTypeInt with width 32 and signedness 0.";
1507   }
1508 
1509   // The structure that is passed in must be an pointer to a structure, whose
1510   // last element is a runtime array.
1511   auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
1512   auto pointer_type = state.FindDef(pointer->type_id());
1513   if (pointer_type->opcode() != spv::Op::OpTypePointer) {
1514     return state.diag(SPV_ERROR_INVALID_ID, inst)
1515            << "The Structure's type in " << instr_name << " <id> "
1516            << state.getIdName(inst->id())
1517            << " must be a pointer to an OpTypeStruct.";
1518   }
1519 
1520   auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
1521   if (structure_type->opcode() != spv::Op::OpTypeStruct) {
1522     return state.diag(SPV_ERROR_INVALID_ID, inst)
1523            << "The Structure's type in " << instr_name << " <id> "
1524            << state.getIdName(inst->id())
1525            << " must be a pointer to an OpTypeStruct.";
1526   }
1527 
1528   auto num_of_members = structure_type->operands().size() - 1;
1529   auto last_member =
1530       state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
1531   if (last_member->opcode() != spv::Op::OpTypeRuntimeArray) {
1532     return state.diag(SPV_ERROR_INVALID_ID, inst)
1533            << "The Structure's last member in " << instr_name << " <id> "
1534            << state.getIdName(inst->id()) << " must be an OpTypeRuntimeArray.";
1535   }
1536 
1537   // The array member must the index of the last element (the run time
1538   // array).
1539   if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
1540     return state.diag(SPV_ERROR_INVALID_ID, inst)
1541            << "The array member in " << instr_name << " <id> "
1542            << state.getIdName(inst->id())
1543            << " must be an the last member of the struct.";
1544   }
1545   return SPV_SUCCESS;
1546 }
1547 
ValidateCooperativeMatrixLengthNV(ValidationState_t & state,const Instruction * inst)1548 spv_result_t ValidateCooperativeMatrixLengthNV(ValidationState_t& state,
1549                                                const Instruction* inst) {
1550   std::string instr_name =
1551       "Op" + std::string(spvOpcodeString(static_cast<spv::Op>(inst->opcode())));
1552 
1553   // Result type must be a 32-bit unsigned int.
1554   auto result_type = state.FindDef(inst->type_id());
1555   if (result_type->opcode() != spv::Op::OpTypeInt ||
1556       result_type->GetOperandAs<uint32_t>(1) != 32 ||
1557       result_type->GetOperandAs<uint32_t>(2) != 0) {
1558     return state.diag(SPV_ERROR_INVALID_ID, inst)
1559            << "The Result Type of " << instr_name << " <id> "
1560            << state.getIdName(inst->id())
1561            << " must be OpTypeInt with width 32 and signedness 0.";
1562   }
1563 
1564   bool isKhr = inst->opcode() == spv::Op::OpCooperativeMatrixLengthKHR;
1565   auto type_id = inst->GetOperandAs<uint32_t>(2);
1566   auto type = state.FindDef(type_id);
1567   if (isKhr && type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
1568     return state.diag(SPV_ERROR_INVALID_ID, inst)
1569            << "The type in " << instr_name << " <id> "
1570            << state.getIdName(type_id)
1571            << " must be OpTypeCooperativeMatrixKHR.";
1572   } else if (!isKhr && type->opcode() != spv::Op::OpTypeCooperativeMatrixNV) {
1573     return state.diag(SPV_ERROR_INVALID_ID, inst)
1574            << "The type in " << instr_name << " <id> "
1575            << state.getIdName(type_id) << " must be OpTypeCooperativeMatrixNV.";
1576   }
1577   return SPV_SUCCESS;
1578 }
1579 
ValidateCooperativeMatrixLoadStoreNV(ValidationState_t & _,const Instruction * inst)1580 spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
1581                                                   const Instruction* inst) {
1582   uint32_t type_id;
1583   const char* opname;
1584   if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) {
1585     type_id = inst->type_id();
1586     opname = "spv::Op::OpCooperativeMatrixLoadNV";
1587   } else {
1588     // get Object operand's type
1589     type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
1590     opname = "spv::Op::OpCooperativeMatrixStoreNV";
1591   }
1592 
1593   auto matrix_type = _.FindDef(type_id);
1594 
1595   if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixNV) {
1596     if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) {
1597       return _.diag(SPV_ERROR_INVALID_ID, inst)
1598              << "spv::Op::OpCooperativeMatrixLoadNV Result Type <id> "
1599              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1600     } else {
1601       return _.diag(SPV_ERROR_INVALID_ID, inst)
1602              << "spv::Op::OpCooperativeMatrixStoreNV Object type <id> "
1603              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1604     }
1605   }
1606 
1607   const auto pointer_index =
1608       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 2u : 0u;
1609   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
1610   const auto pointer = _.FindDef(pointer_id);
1611   if (!pointer ||
1612       ((_.addressing_model() == spv::AddressingModel::Logical) &&
1613        ((!_.features().variable_pointers &&
1614          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
1615         (_.features().variable_pointers &&
1616          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
1617     return _.diag(SPV_ERROR_INVALID_ID, inst)
1618            << opname << " Pointer <id> " << _.getIdName(pointer_id)
1619            << " is not a logical pointer.";
1620   }
1621 
1622   const auto pointer_type_id = pointer->type_id();
1623   const auto pointer_type = _.FindDef(pointer_type_id);
1624   if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
1625     return _.diag(SPV_ERROR_INVALID_ID, inst)
1626            << opname << " type for pointer <id> " << _.getIdName(pointer_id)
1627            << " is not a pointer type.";
1628   }
1629 
1630   const auto storage_class_index = 1u;
1631   const auto storage_class =
1632       pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
1633 
1634   if (storage_class != spv::StorageClass::Workgroup &&
1635       storage_class != spv::StorageClass::StorageBuffer &&
1636       storage_class != spv::StorageClass::PhysicalStorageBuffer) {
1637     return _.diag(SPV_ERROR_INVALID_ID, inst)
1638            << opname << " storage class for pointer type <id> "
1639            << _.getIdName(pointer_type_id)
1640            << " is not Workgroup or StorageBuffer.";
1641   }
1642 
1643   const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
1644   const auto pointee_type = _.FindDef(pointee_id);
1645   if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
1646                          _.IsFloatScalarOrVectorType(pointee_id))) {
1647     return _.diag(SPV_ERROR_INVALID_ID, inst)
1648            << opname << " Pointer <id> " << _.getIdName(pointer->id())
1649            << "s Type must be a scalar or vector type.";
1650   }
1651 
1652   const auto stride_index =
1653       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 3u : 2u;
1654   const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
1655   const auto stride = _.FindDef(stride_id);
1656   if (!stride || !_.IsIntScalarType(stride->type_id())) {
1657     return _.diag(SPV_ERROR_INVALID_ID, inst)
1658            << "Stride operand <id> " << _.getIdName(stride_id)
1659            << " must be a scalar integer type.";
1660   }
1661 
1662   const auto colmajor_index =
1663       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 4u : 3u;
1664   const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
1665   const auto colmajor = _.FindDef(colmajor_id);
1666   if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
1667       !(spvOpcodeIsConstant(colmajor->opcode()) ||
1668         spvOpcodeIsSpecConstant(colmajor->opcode()))) {
1669     return _.diag(SPV_ERROR_INVALID_ID, inst)
1670            << "Column Major operand <id> " << _.getIdName(colmajor_id)
1671            << " must be a boolean constant instruction.";
1672   }
1673 
1674   const auto memory_access_index =
1675       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadNV) ? 5u : 4u;
1676   if (inst->operands().size() > memory_access_index) {
1677     if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
1678       return error;
1679   }
1680 
1681   return SPV_SUCCESS;
1682 }
1683 
ValidateCooperativeMatrixLoadStoreKHR(ValidationState_t & _,const Instruction * inst)1684 spv_result_t ValidateCooperativeMatrixLoadStoreKHR(ValidationState_t& _,
1685                                                    const Instruction* inst) {
1686   uint32_t type_id;
1687   const char* opname;
1688   if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
1689     type_id = inst->type_id();
1690     opname = "spv::Op::OpCooperativeMatrixLoadKHR";
1691   } else {
1692     // get Object operand's type
1693     type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
1694     opname = "spv::Op::OpCooperativeMatrixStoreKHR";
1695   }
1696 
1697   auto matrix_type = _.FindDef(type_id);
1698 
1699   if (matrix_type->opcode() != spv::Op::OpTypeCooperativeMatrixKHR) {
1700     if (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) {
1701       return _.diag(SPV_ERROR_INVALID_ID, inst)
1702              << "spv::Op::OpCooperativeMatrixLoadKHR Result Type <id> "
1703              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1704     } else {
1705       return _.diag(SPV_ERROR_INVALID_ID, inst)
1706              << "spv::Op::OpCooperativeMatrixStoreKHR Object type <id> "
1707              << _.getIdName(type_id) << " is not a cooperative matrix type.";
1708     }
1709   }
1710 
1711   const auto pointer_index =
1712       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 2u : 0u;
1713   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
1714   const auto pointer = _.FindDef(pointer_id);
1715   if (!pointer ||
1716       ((_.addressing_model() == spv::AddressingModel::Logical) &&
1717        ((!_.features().variable_pointers &&
1718          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
1719         (_.features().variable_pointers &&
1720          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
1721     return _.diag(SPV_ERROR_INVALID_ID, inst)
1722            << opname << " Pointer <id> " << _.getIdName(pointer_id)
1723            << " is not a logical pointer.";
1724   }
1725 
1726   const auto pointer_type_id = pointer->type_id();
1727   const auto pointer_type = _.FindDef(pointer_type_id);
1728   if (!pointer_type || pointer_type->opcode() != spv::Op::OpTypePointer) {
1729     return _.diag(SPV_ERROR_INVALID_ID, inst)
1730            << opname << " type for pointer <id> " << _.getIdName(pointer_id)
1731            << " is not a pointer type.";
1732   }
1733 
1734   const auto storage_class_index = 1u;
1735   const auto storage_class =
1736       pointer_type->GetOperandAs<spv::StorageClass>(storage_class_index);
1737 
1738   if (storage_class != spv::StorageClass::Workgroup &&
1739       storage_class != spv::StorageClass::StorageBuffer &&
1740       storage_class != spv::StorageClass::PhysicalStorageBuffer) {
1741     return _.diag(SPV_ERROR_INVALID_ID, inst)
1742            << _.VkErrorID(8973) << opname
1743            << " storage class for pointer type <id> "
1744            << _.getIdName(pointer_type_id)
1745            << " is not Workgroup, StorageBuffer, or PhysicalStorageBuffer.";
1746   }
1747 
1748   const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
1749   const auto pointee_type = _.FindDef(pointee_id);
1750   if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
1751                          _.IsFloatScalarOrVectorType(pointee_id))) {
1752     return _.diag(SPV_ERROR_INVALID_ID, inst)
1753            << opname << " Pointer <id> " << _.getIdName(pointer->id())
1754            << "s Type must be a scalar or vector type.";
1755   }
1756 
1757   const auto layout_index =
1758       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 3u : 2u;
1759   const auto colmajor_id = inst->GetOperandAs<uint32_t>(layout_index);
1760   const auto colmajor = _.FindDef(colmajor_id);
1761   if (!colmajor || !_.IsIntScalarType(colmajor->type_id()) ||
1762       !(spvOpcodeIsConstant(colmajor->opcode()) ||
1763         spvOpcodeIsSpecConstant(colmajor->opcode()))) {
1764     return _.diag(SPV_ERROR_INVALID_ID, inst)
1765            << "MemoryLayout operand <id> " << _.getIdName(colmajor_id)
1766            << " must be a 32-bit integer constant instruction.";
1767   }
1768 
1769   const auto stride_index =
1770       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 4u : 3u;
1771   if (inst->operands().size() > stride_index) {
1772     const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
1773     const auto stride = _.FindDef(stride_id);
1774     if (!stride || !_.IsIntScalarType(stride->type_id())) {
1775       return _.diag(SPV_ERROR_INVALID_ID, inst)
1776              << "Stride operand <id> " << _.getIdName(stride_id)
1777              << " must be a scalar integer type.";
1778     }
1779   }
1780 
1781   const auto memory_access_index =
1782       (inst->opcode() == spv::Op::OpCooperativeMatrixLoadKHR) ? 5u : 4u;
1783   if (inst->operands().size() > memory_access_index) {
1784     if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
1785       return error;
1786   }
1787 
1788   return SPV_SUCCESS;
1789 }
1790 
ValidatePtrComparison(ValidationState_t & _,const Instruction * inst)1791 spv_result_t ValidatePtrComparison(ValidationState_t& _,
1792                                    const Instruction* inst) {
1793   if (_.addressing_model() == spv::AddressingModel::Logical &&
1794       !_.features().variable_pointers) {
1795     return _.diag(SPV_ERROR_INVALID_ID, inst)
1796            << "Instruction cannot for logical addressing model be used without "
1797               "a variable pointers capability";
1798   }
1799 
1800   const auto result_type = _.FindDef(inst->type_id());
1801   if (inst->opcode() == spv::Op::OpPtrDiff) {
1802     if (!result_type || result_type->opcode() != spv::Op::OpTypeInt) {
1803       return _.diag(SPV_ERROR_INVALID_ID, inst)
1804              << "Result Type must be an integer scalar";
1805     }
1806   } else {
1807     if (!result_type || result_type->opcode() != spv::Op::OpTypeBool) {
1808       return _.diag(SPV_ERROR_INVALID_ID, inst)
1809              << "Result Type must be OpTypeBool";
1810     }
1811   }
1812 
1813   const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
1814   const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
1815   if (!op1 || !op2 || op1->type_id() != op2->type_id()) {
1816     return _.diag(SPV_ERROR_INVALID_ID, inst)
1817            << "The types of Operand 1 and Operand 2 must match";
1818   }
1819   const auto op1_type = _.FindDef(op1->type_id());
1820   if (!op1_type || op1_type->opcode() != spv::Op::OpTypePointer) {
1821     return _.diag(SPV_ERROR_INVALID_ID, inst)
1822            << "Operand type must be a pointer";
1823   }
1824 
1825   spv::StorageClass sc = op1_type->GetOperandAs<spv::StorageClass>(1u);
1826   if (_.addressing_model() == spv::AddressingModel::Logical) {
1827     if (sc != spv::StorageClass::Workgroup &&
1828         sc != spv::StorageClass::StorageBuffer) {
1829       return _.diag(SPV_ERROR_INVALID_ID, inst)
1830              << "Invalid pointer storage class";
1831     }
1832 
1833     if (sc == spv::StorageClass::Workgroup &&
1834         !_.HasCapability(spv::Capability::VariablePointers)) {
1835       return _.diag(SPV_ERROR_INVALID_ID, inst)
1836              << "Workgroup storage class pointer requires VariablePointers "
1837                 "capability to be specified";
1838     }
1839   } else if (sc == spv::StorageClass::PhysicalStorageBuffer) {
1840     return _.diag(SPV_ERROR_INVALID_ID, inst)
1841            << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
1842   }
1843 
1844   return SPV_SUCCESS;
1845 }
1846 
1847 }  // namespace
1848 
MemoryPass(ValidationState_t & _,const Instruction * inst)1849 spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
1850   switch (inst->opcode()) {
1851     case spv::Op::OpVariable:
1852       if (auto error = ValidateVariable(_, inst)) return error;
1853       break;
1854     case spv::Op::OpLoad:
1855       if (auto error = ValidateLoad(_, inst)) return error;
1856       break;
1857     case spv::Op::OpStore:
1858       if (auto error = ValidateStore(_, inst)) return error;
1859       break;
1860     case spv::Op::OpCopyMemory:
1861     case spv::Op::OpCopyMemorySized:
1862       if (auto error = ValidateCopyMemory(_, inst)) return error;
1863       break;
1864     case spv::Op::OpPtrAccessChain:
1865       if (auto error = ValidatePtrAccessChain(_, inst)) return error;
1866       break;
1867     case spv::Op::OpAccessChain:
1868     case spv::Op::OpInBoundsAccessChain:
1869     case spv::Op::OpInBoundsPtrAccessChain:
1870       if (auto error = ValidateAccessChain(_, inst)) return error;
1871       break;
1872     case spv::Op::OpArrayLength:
1873       if (auto error = ValidateArrayLength(_, inst)) return error;
1874       break;
1875     case spv::Op::OpCooperativeMatrixLoadNV:
1876     case spv::Op::OpCooperativeMatrixStoreNV:
1877       if (auto error = ValidateCooperativeMatrixLoadStoreNV(_, inst))
1878         return error;
1879       break;
1880     case spv::Op::OpCooperativeMatrixLengthKHR:
1881     case spv::Op::OpCooperativeMatrixLengthNV:
1882       if (auto error = ValidateCooperativeMatrixLengthNV(_, inst)) return error;
1883       break;
1884     case spv::Op::OpCooperativeMatrixLoadKHR:
1885     case spv::Op::OpCooperativeMatrixStoreKHR:
1886       if (auto error = ValidateCooperativeMatrixLoadStoreKHR(_, inst))
1887         return error;
1888       break;
1889     case spv::Op::OpPtrEqual:
1890     case spv::Op::OpPtrNotEqual:
1891     case spv::Op::OpPtrDiff:
1892       if (auto error = ValidatePtrComparison(_, inst)) return error;
1893       break;
1894     case spv::Op::OpImageTexelPointer:
1895     case spv::Op::OpGenericPtrMemSemantics:
1896     default:
1897       break;
1898   }
1899 
1900   return SPV_SUCCESS;
1901 }
1902 }  // namespace val
1903 }  // namespace spvtools
1904