1 // Copyright (c) 2018 Google LLC.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "source/val/validate.h"
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_scopes.h"
25 #include "source/val/validation_state.h"
26 
27 namespace spvtools {
28 namespace val {
29 namespace {
30 
31 bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
32                                 const Instruction*);
33 bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
34                                  const Instruction*);
35 bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
36                                const Instruction*);
37 bool HasConflictingMemberOffsets(const std::vector<Decoration>&,
38                                  const std::vector<Decoration>&);
39 
IsAllowedTypeOrArrayOfSame(ValidationState_t & _,const Instruction * type,std::initializer_list<uint32_t> allowed)40 bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction* type,
41                                 std::initializer_list<uint32_t> allowed) {
42   if (std::find(allowed.begin(), allowed.end(), type->opcode()) !=
43       allowed.end()) {
44     return true;
45   }
46   if (type->opcode() == SpvOpTypeArray ||
47       type->opcode() == SpvOpTypeRuntimeArray) {
48     auto elem_type = _.FindDef(type->word(2));
49     return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
50            allowed.end();
51   }
52   return false;
53 }
54 
55 // Returns true if the two instructions represent structs that, as far as the
56 // validator can tell, have the exact same data layout.
AreLayoutCompatibleStructs(ValidationState_t & _,const Instruction * type1,const Instruction * type2)57 bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
58                                 const Instruction* type2) {
59   if (type1->opcode() != SpvOpTypeStruct) {
60     return false;
61   }
62   if (type2->opcode() != SpvOpTypeStruct) {
63     return false;
64   }
65 
66   if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;
67 
68   return HaveSameLayoutDecorations(_, type1, type2);
69 }
70 
71 // Returns true if the operands to the OpTypeStruct instruction defining the
72 // types are the same or are layout compatible types. |type1| and |type2| must
73 // be OpTypeStruct instructions.
HaveLayoutCompatibleMembers(ValidationState_t & _,const Instruction * type1,const Instruction * type2)74 bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
75                                  const Instruction* type2) {
76   assert(type1->opcode() == SpvOpTypeStruct &&
77          "type1 must be an OpTypeStruct instruction.");
78   assert(type2->opcode() == SpvOpTypeStruct &&
79          "type2 must be an OpTypeStruct instruction.");
80   const auto& type1_operands = type1->operands();
81   const auto& type2_operands = type2->operands();
82   if (type1_operands.size() != type2_operands.size()) {
83     return false;
84   }
85 
86   for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
87     if (type1->word(operand) != type2->word(operand)) {
88       auto def1 = _.FindDef(type1->word(operand));
89       auto def2 = _.FindDef(type2->word(operand));
90       if (!AreLayoutCompatibleStructs(_, def1, def2)) {
91         return false;
92       }
93     }
94   }
95   return true;
96 }
97 
98 // Returns true if all decorations that affect the data layout of the struct
99 // (like Offset), are the same for the two types. |type1| and |type2| must be
100 // OpTypeStruct instructions.
HaveSameLayoutDecorations(ValidationState_t & _,const Instruction * type1,const Instruction * type2)101 bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
102                                const Instruction* type2) {
103   assert(type1->opcode() == SpvOpTypeStruct &&
104          "type1 must be an OpTypeStruct instruction.");
105   assert(type2->opcode() == SpvOpTypeStruct &&
106          "type2 must be an OpTypeStruct instruction.");
107   const std::vector<Decoration>& type1_decorations =
108       _.id_decorations(type1->id());
109   const std::vector<Decoration>& type2_decorations =
110       _.id_decorations(type2->id());
111 
112   // TODO: Will have to add other check for arrays an matricies if we want to
113   // handle them.
114   if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
115     return false;
116   }
117 
118   return true;
119 }
120 
HasConflictingMemberOffsets(const std::vector<Decoration> & type1_decorations,const std::vector<Decoration> & type2_decorations)121 bool HasConflictingMemberOffsets(
122     const std::vector<Decoration>& type1_decorations,
123     const std::vector<Decoration>& type2_decorations) {
124   {
125     // We are interested in conflicting decoration.  If a decoration is in one
126     // list but not the other, then we will assume the code is correct.  We are
127     // looking for things we know to be wrong.
128     //
129     // We do not have to traverse type2_decoration because, after traversing
130     // type1_decorations, anything new will not be found in
131     // type1_decoration.  Therefore, it cannot lead to a conflict.
132     for (const Decoration& decoration : type1_decorations) {
133       switch (decoration.dec_type()) {
134         case SpvDecorationOffset: {
135           // Since these affect the layout of the struct, they must be present
136           // in both structs.
137           auto compare = [&decoration](const Decoration& rhs) {
138             if (rhs.dec_type() != SpvDecorationOffset) return false;
139             return decoration.struct_member_index() ==
140                    rhs.struct_member_index();
141           };
142           auto i = std::find_if(type2_decorations.begin(),
143                                 type2_decorations.end(), compare);
144           if (i != type2_decorations.end() &&
145               decoration.params().front() != i->params().front()) {
146             return true;
147           }
148         } break;
149         default:
150           // This decoration does not affect the layout of the structure, so
151           // just moving on.
152           break;
153       }
154     }
155   }
156   return false;
157 }
158 
159 // If |skip_builtin| is true, returns true if |storage| contains bool within
160 // it and no storage that contains the bool is builtin.
161 // If |skip_builtin| is false, returns true if |storage| contains bool within
162 // it.
ContainsInvalidBool(ValidationState_t & _,const Instruction * storage,bool skip_builtin)163 bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
164                          bool skip_builtin) {
165   if (skip_builtin) {
166     for (const Decoration& decoration : _.id_decorations(storage->id())) {
167       if (decoration.dec_type() == SpvDecorationBuiltIn) return false;
168     }
169   }
170 
171   const size_t elem_type_index = 1;
172   uint32_t elem_type_id;
173   Instruction* elem_type;
174 
175   switch (storage->opcode()) {
176     case SpvOpTypeBool:
177       return true;
178     case SpvOpTypeVector:
179     case SpvOpTypeMatrix:
180     case SpvOpTypeArray:
181     case SpvOpTypeRuntimeArray:
182       elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
183       elem_type = _.FindDef(elem_type_id);
184       return ContainsInvalidBool(_, elem_type, skip_builtin);
185     case SpvOpTypeStruct:
186       for (size_t member_type_index = 1;
187            member_type_index < storage->operands().size();
188            ++member_type_index) {
189         auto member_type_id =
190             storage->GetOperandAs<uint32_t>(member_type_index);
191         auto member_type = _.FindDef(member_type_id);
192         if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
193       }
194     default:
195       break;
196   }
197   return false;
198 }
199 
GetStorageClass(ValidationState_t & _,const Instruction * inst)200 std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
201     ValidationState_t& _, const Instruction* inst) {
202   SpvStorageClass dst_sc = SpvStorageClassMax;
203   SpvStorageClass src_sc = SpvStorageClassMax;
204   switch (inst->opcode()) {
205     case SpvOpLoad: {
206       auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
207       auto load_pointer_type = _.FindDef(load_pointer->type_id());
208       dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
209       break;
210     }
211     case SpvOpStore: {
212       auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
213       auto store_pointer_type = _.FindDef(store_pointer->type_id());
214       dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
215       break;
216     }
217     case SpvOpCopyMemory:
218     case SpvOpCopyMemorySized: {
219       auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
220       auto dst_type = _.FindDef(dst->type_id());
221       dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
222       auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
223       auto src_type = _.FindDef(src->type_id());
224       src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
225       break;
226     }
227     default:
228       break;
229   }
230 
231   return std::make_pair(dst_sc, src_sc);
232 }
233 
234 // This function is only called for OpLoad, OpStore, OpCopyMemory and
235 // OpCopyMemorySized.
GetMakeAvailableScope(const Instruction * inst,uint32_t mask)236 uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask) {
237   uint32_t offset = 1;
238   if (mask & SpvMemoryAccessAlignedMask) ++offset;
239 
240   uint32_t scope_id = 0;
241   switch (inst->opcode()) {
242     case SpvOpLoad:
243     case SpvOpCopyMemorySized:
244       return inst->GetOperandAs<uint32_t>(3 + offset);
245     case SpvOpStore:
246     case SpvOpCopyMemory:
247       return inst->GetOperandAs<uint32_t>(2 + offset);
248     default:
249       assert(false && "unexpected opcode");
250       break;
251   }
252 
253   return scope_id;
254 }
255 
256 // This function is only called for OpLoad, OpStore, OpCopyMemory and
257 // OpCopyMemorySized.
GetMakeVisibleScope(const Instruction * inst,uint32_t mask)258 uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask) {
259   uint32_t offset = 1;
260   if (mask & SpvMemoryAccessAlignedMask) ++offset;
261   if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++offset;
262 
263   uint32_t scope_id = 0;
264   switch (inst->opcode()) {
265     case SpvOpLoad:
266     case SpvOpCopyMemorySized:
267       return inst->GetOperandAs<uint32_t>(3 + offset);
268     case SpvOpStore:
269     case SpvOpCopyMemory:
270       return inst->GetOperandAs<uint32_t>(2 + offset);
271     default:
272       assert(false && "unexpected opcode");
273       break;
274   }
275 
276   return scope_id;
277 }
278 
DoesStructContainRTA(const ValidationState_t & _,const Instruction * inst)279 bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
280   for (size_t member_index = 1; member_index < inst->operands().size();
281        ++member_index) {
282     const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
283     const auto member_type = _.FindDef(member_id);
284     if (member_type->opcode() == SpvOpTypeRuntimeArray) return true;
285   }
286   return false;
287 }
288 
CheckMemoryAccess(ValidationState_t & _,const Instruction * inst,uint32_t index)289 spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
290                                uint32_t index) {
291   SpvStorageClass dst_sc, src_sc;
292   std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
293   if (inst->operands().size() <= index) {
294     if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
295         dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
296       return _.diag(SPV_ERROR_INVALID_ID, inst)
297              << "Memory accesses with PhysicalStorageBufferEXT must use "
298                 "Aligned.";
299     }
300     return SPV_SUCCESS;
301   }
302 
303   uint32_t mask = inst->GetOperandAs<uint32_t>(index);
304   if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
305     if (inst->opcode() == SpvOpLoad) {
306       return _.diag(SPV_ERROR_INVALID_ID, inst)
307              << "MakePointerAvailableKHR cannot be used with OpLoad.";
308     }
309 
310     if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
311       return _.diag(SPV_ERROR_INVALID_ID, inst)
312              << "NonPrivatePointerKHR must be specified if "
313                 "MakePointerAvailableKHR is specified.";
314     }
315 
316     // Check the associated scope for MakeAvailableKHR.
317     const auto available_scope = GetMakeAvailableScope(inst, mask);
318     if (auto error = ValidateMemoryScope(_, inst, available_scope))
319       return error;
320   }
321 
322   if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
323     if (inst->opcode() == SpvOpStore) {
324       return _.diag(SPV_ERROR_INVALID_ID, inst)
325              << "MakePointerVisibleKHR cannot be used with OpStore.";
326     }
327 
328     if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
329       return _.diag(SPV_ERROR_INVALID_ID, inst)
330              << "NonPrivatePointerKHR must be specified if "
331              << "MakePointerVisibleKHR is specified.";
332     }
333 
334     // Check the associated scope for MakeVisibleKHR.
335     const auto visible_scope = GetMakeVisibleScope(inst, mask);
336     if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
337   }
338 
339   if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
340     if (dst_sc != SpvStorageClassUniform &&
341         dst_sc != SpvStorageClassWorkgroup &&
342         dst_sc != SpvStorageClassCrossWorkgroup &&
343         dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
344         dst_sc != SpvStorageClassStorageBuffer &&
345         dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
346       return _.diag(SPV_ERROR_INVALID_ID, inst)
347              << "NonPrivatePointerKHR requires a pointer in Uniform, "
348              << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
349              << "storage classes.";
350     }
351     if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
352         src_sc != SpvStorageClassWorkgroup &&
353         src_sc != SpvStorageClassCrossWorkgroup &&
354         src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
355         src_sc != SpvStorageClassStorageBuffer &&
356         src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
357       return _.diag(SPV_ERROR_INVALID_ID, inst)
358              << "NonPrivatePointerKHR requires a pointer in Uniform, "
359              << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
360              << "storage classes.";
361     }
362   }
363 
364   if (!(mask & SpvMemoryAccessAlignedMask)) {
365     if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
366         dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
367       return _.diag(SPV_ERROR_INVALID_ID, inst)
368              << "Memory accesses with PhysicalStorageBufferEXT must use "
369                 "Aligned.";
370     }
371   }
372 
373   return SPV_SUCCESS;
374 }
375 
ValidateVariable(ValidationState_t & _,const Instruction * inst)376 spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
377   auto result_type = _.FindDef(inst->type_id());
378   if (!result_type || result_type->opcode() != SpvOpTypePointer) {
379     return _.diag(SPV_ERROR_INVALID_ID, inst)
380            << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
381            << "' is not a pointer type.";
382   }
383 
384   const auto initializer_index = 3;
385   const auto storage_class_index = 2;
386   if (initializer_index < inst->operands().size()) {
387     const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
388     const auto initializer = _.FindDef(initializer_id);
389     const auto is_module_scope_var =
390         initializer && (initializer->opcode() == SpvOpVariable) &&
391         (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
392          SpvStorageClassFunction);
393     const auto is_constant =
394         initializer && spvOpcodeIsConstant(initializer->opcode());
395     if (!initializer || !(is_constant || is_module_scope_var)) {
396       return _.diag(SPV_ERROR_INVALID_ID, inst)
397              << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
398              << "' is not a constant or module-scope variable.";
399     }
400   }
401 
402   const auto storage_class =
403       inst->GetOperandAs<SpvStorageClass>(storage_class_index);
404   if (storage_class != SpvStorageClassWorkgroup &&
405       storage_class != SpvStorageClassCrossWorkgroup &&
406       storage_class != SpvStorageClassPrivate &&
407       storage_class != SpvStorageClassFunction &&
408       storage_class != SpvStorageClassRayPayloadNV &&
409       storage_class != SpvStorageClassIncomingRayPayloadNV &&
410       storage_class != SpvStorageClassHitAttributeNV &&
411       storage_class != SpvStorageClassCallableDataNV &&
412       storage_class != SpvStorageClassIncomingCallableDataNV) {
413     const auto storage_index = 2;
414     const auto storage_id = result_type->GetOperandAs<uint32_t>(storage_index);
415     const auto storage = _.FindDef(storage_id);
416     bool storage_input_or_output = storage_class == SpvStorageClassInput ||
417                                    storage_class == SpvStorageClassOutput;
418     bool builtin = false;
419     if (storage_input_or_output) {
420       for (const Decoration& decoration : _.id_decorations(inst->id())) {
421         if (decoration.dec_type() == SpvDecorationBuiltIn) {
422           builtin = true;
423           break;
424         }
425       }
426     }
427     if (!(storage_input_or_output && builtin) &&
428         ContainsInvalidBool(_, storage, storage_input_or_output)) {
429       return _.diag(SPV_ERROR_INVALID_ID, inst)
430              << "If OpTypeBool is stored in conjunction with OpVariable, it "
431              << "can only be used with non-externally visible shader Storage "
432              << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
433     }
434   }
435 
436   // SPIR-V 3.32.8: Check that pointer type and variable type have the same
437   // storage class.
438   const auto result_storage_class_index = 1;
439   const auto result_storage_class =
440       result_type->GetOperandAs<uint32_t>(result_storage_class_index);
441   if (storage_class != result_storage_class) {
442     return _.diag(SPV_ERROR_INVALID_ID, inst)
443            << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
444            << "Its Storage Class operand must be the same as the Storage Class "
445            << "operand of the result type.";
446   }
447 
448   // Variable pointer related restrictions.
449   const auto pointee = _.FindDef(result_type->word(3));
450   if (_.addressing_model() == SpvAddressingModelLogical &&
451       !_.options()->relax_logical_pointer) {
452     // VariablePointersStorageBuffer is implied by VariablePointers.
453     if (pointee->opcode() == SpvOpTypePointer) {
454       if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
455         return _.diag(SPV_ERROR_INVALID_ID, inst)
456                << "In Logical addressing, variables may not allocate a pointer "
457                << "type";
458       } else if (storage_class != SpvStorageClassFunction &&
459                  storage_class != SpvStorageClassPrivate) {
460         return _.diag(SPV_ERROR_INVALID_ID, inst)
461                << "In Logical addressing with variable pointers, variables "
462                << "that allocate pointers must be in Function or Private "
463                << "storage classes";
464       }
465     }
466   }
467 
468   // Vulkan 14.5.1: Check type of PushConstant variables.
469   // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
470   if (spvIsVulkanEnv(_.context()->target_env)) {
471     if (storage_class == SpvStorageClassPushConstant) {
472       if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
473         return _.diag(SPV_ERROR_INVALID_ID, inst)
474                << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
475                << "' has illegal type.\n"
476                << "From Vulkan spec, section 14.5.1:\n"
477                << "Such variables must be typed as OpTypeStruct, "
478                << "or an array of this type";
479       }
480     }
481 
482     if (storage_class == SpvStorageClassUniformConstant) {
483       if (!IsAllowedTypeOrArrayOfSame(
484               _, pointee,
485               {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
486                SpvOpTypeAccelerationStructureNV})) {
487         return _.diag(SPV_ERROR_INVALID_ID, inst)
488                << "UniformConstant OpVariable <id> '" << _.getIdName(inst->id())
489                << "' has illegal type.\n"
490                << "From Vulkan spec, section 14.5.2:\n"
491                << "Variables identified with the UniformConstant storage class "
492                << "are used only as handles to refer to opaque resources. Such "
493                << "variables must be typed as OpTypeImage, OpTypeSampler, "
494                << "OpTypeSampledImage, OpTypeAccelerationStructureNV, "
495                << "or an array of one of these types.";
496       }
497     }
498 
499     if (storage_class == SpvStorageClassUniform) {
500       if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
501         return _.diag(SPV_ERROR_INVALID_ID, inst)
502                << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
503                << "' has illegal type.\n"
504                << "From Vulkan spec, section 14.5.2:\n"
505                << "Variables identified with the Uniform storage class are "
506                << "used to access transparent buffer backed resources. Such "
507                << "variables must be typed as OpTypeStruct, or an array of "
508                << "this type";
509       }
510     }
511   }
512 
513   // WebGPU & Vulkan Appendix A: Check that if contains initializer, then
514   // storage class is Output, Private, or Function.
515   if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
516       storage_class != SpvStorageClassPrivate &&
517       storage_class != SpvStorageClassFunction) {
518     if (spvIsVulkanEnv(_.context()->target_env)) {
519       return _.diag(SPV_ERROR_INVALID_ID, inst)
520              << "OpVariable, <id> '" << _.getIdName(inst->id())
521              << "', has a disallowed initializer & storage class "
522              << "combination.\n"
523              << "From Vulkan spec, Appendix A:\n"
524              << "Variable declarations that include initializers must have "
525              << "one of the following storage classes: Output, Private, or "
526              << "Function";
527     }
528 
529     if (spvIsWebGPUEnv(_.context()->target_env)) {
530       return _.diag(SPV_ERROR_INVALID_ID, inst)
531              << "OpVariable, <id> '" << _.getIdName(inst->id())
532              << "', has a disallowed initializer & storage class "
533              << "combination.\n"
534              << "From WebGPU execution environment spec:\n"
535              << "Variable declarations that include initializers must have "
536              << "one of the following storage classes: Output, Private, or "
537              << "Function";
538     }
539   }
540 
541   // WebGPU: All variables with storage class Output, Private, or Function MUST
542   // have an initializer.
543   if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 &&
544       (storage_class == SpvStorageClassOutput ||
545        storage_class == SpvStorageClassPrivate ||
546        storage_class == SpvStorageClassFunction)) {
547     return _.diag(SPV_ERROR_INVALID_ID, inst)
548            << "OpVariable, <id> '" << _.getIdName(inst->id())
549            << "', must have an initializer.\n"
550            << "From WebGPU execution environment spec:\n"
551            << "All variables in the following storage classes must have an "
552            << "initializer: Output, Private, or Function";
553   }
554 
555   if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
556     return _.diag(SPV_ERROR_INVALID_ID, inst)
557            << "PhysicalStorageBufferEXT must not be used with OpVariable.";
558   }
559 
560   auto pointee_base = pointee;
561   while (pointee_base->opcode() == SpvOpTypeArray) {
562     pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
563   }
564   if (pointee_base->opcode() == SpvOpTypePointer) {
565     if (pointee_base->GetOperandAs<uint32_t>(1u) ==
566         SpvStorageClassPhysicalStorageBufferEXT) {
567       // check for AliasedPointerEXT/RestrictPointerEXT
568       bool foundAliased =
569           _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
570       bool foundRestrict =
571           _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
572       if (!foundAliased && !foundRestrict) {
573         return _.diag(SPV_ERROR_INVALID_ID, inst)
574                << "OpVariable " << inst->id()
575                << ": expected AliasedPointerEXT or RestrictPointerEXT for "
576                << "PhysicalStorageBufferEXT pointer.";
577       }
578       if (foundAliased && foundRestrict) {
579         return _.diag(SPV_ERROR_INVALID_ID, inst)
580                << "OpVariable " << inst->id()
581                << ": can't specify both AliasedPointerEXT and "
582                << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
583       }
584     }
585   }
586 
587   // Vulkan specific validation rules for OpTypeRuntimeArray
588   if (spvIsVulkanEnv(_.context()->target_env)) {
589     const auto type_index = 2;
590     const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
591     auto value_type = _.FindDef(value_id);
592     // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
593     // so should never appear as a bare variable.
594     // Unless the module has the RuntimeDescriptorArrayEXT capability.
595     if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
596       if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
597         return _.diag(SPV_ERROR_INVALID_ID, inst)
598                << "OpVariable, <id> '" << _.getIdName(inst->id())
599                << "', is attempting to create memory for an illegal type, "
600                << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
601                << "appear as the final member of an OpTypeStruct, thus cannot "
602                << "be instantiated via OpVariable";
603       } else {
604         // A bare variable OpTypeRuntimeArray is allowed in this context, but
605         // still need to check the storage class.
606         if (storage_class != SpvStorageClassStorageBuffer &&
607             storage_class != SpvStorageClassUniform &&
608             storage_class != SpvStorageClassUniformConstant) {
609           return _.diag(SPV_ERROR_INVALID_ID, inst)
610                  << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
611                  << "containing OpTypeRuntimeArray must have storage class of "
612                  << "StorageBuffer, Uniform, or UniformConstant.";
613         }
614       }
615     }
616 
617     // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
618     // must either have the storage class StorageBuffer and be decorated
619     // with Block, or it must be in the Uniform storage class and be decorated
620     // as BufferBlock.
621     if (value_type && value_type->opcode() == SpvOpTypeStruct) {
622       if (DoesStructContainRTA(_, value_type)) {
623         if (storage_class == SpvStorageClassStorageBuffer) {
624           if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
625             return _.diag(SPV_ERROR_INVALID_ID, inst)
626                    << "For Vulkan, an OpTypeStruct variable containing an "
627                    << "OpTypeRuntimeArray must be decorated with Block if it "
628                    << "has storage class StorageBuffer.";
629           }
630         } else if (storage_class == SpvStorageClassUniform) {
631           if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
632             return _.diag(SPV_ERROR_INVALID_ID, inst)
633                    << "For Vulkan, an OpTypeStruct variable containing an "
634                    << "OpTypeRuntimeArray must be decorated with BufferBlock "
635                    << "if it has storage class Uniform.";
636           }
637         } else {
638           return _.diag(SPV_ERROR_INVALID_ID, inst)
639                  << "For Vulkan, OpTypeStruct variables containing "
640                  << "OpTypeRuntimeArray must have storage class of "
641                  << "StorageBuffer or Uniform.";
642         }
643       }
644     }
645   }
646 
647   // WebGPU specific validation rules for OpTypeRuntimeArray
648   if (spvIsWebGPUEnv(_.context()->target_env)) {
649     const auto type_index = 2;
650     const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
651     auto value_type = _.FindDef(value_id);
652     // OpTypeRuntimeArray should only ever be in an OpTypeStruct,
653     // so should never appear as a bare variable.
654     if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
655       return _.diag(SPV_ERROR_INVALID_ID, inst)
656              << "OpVariable, <id> '" << _.getIdName(inst->id())
657              << "', is attempting to create memory for an illegal type, "
658              << "OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray can only "
659              << "appear as the final member of an OpTypeStruct, thus cannot "
660              << "be instantiated via OpVariable";
661     }
662 
663     // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
664     // must have the storage class StorageBuffer and be decorated
665     // with Block.
666     if (value_type && value_type->opcode() == SpvOpTypeStruct) {
667       if (DoesStructContainRTA(_, value_type)) {
668         if (storage_class == SpvStorageClassStorageBuffer) {
669           if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
670             return _.diag(SPV_ERROR_INVALID_ID, inst)
671                    << "For WebGPU, an OpTypeStruct variable containing an "
672                    << "OpTypeRuntimeArray must be decorated with Block if it "
673                    << "has storage class StorageBuffer.";
674           }
675         } else {
676           return _.diag(SPV_ERROR_INVALID_ID, inst)
677                  << "For WebGPU, OpTypeStruct variables containing "
678                  << "OpTypeRuntimeArray must have storage class of "
679                  << "StorageBuffer";
680         }
681       }
682     }
683   }
684 
685   return SPV_SUCCESS;
686 }
687 
ValidateLoad(ValidationState_t & _,const Instruction * inst)688 spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
689   const auto result_type = _.FindDef(inst->type_id());
690   if (!result_type) {
691     return _.diag(SPV_ERROR_INVALID_ID, inst)
692            << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
693            << "' is not defined.";
694   }
695 
696   const bool uses_variable_pointers =
697       _.features().variable_pointers ||
698       _.features().variable_pointers_storage_buffer;
699   const auto pointer_index = 2;
700   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
701   const auto pointer = _.FindDef(pointer_id);
702   if (!pointer ||
703       ((_.addressing_model() == SpvAddressingModelLogical) &&
704        ((!uses_variable_pointers &&
705          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
706         (uses_variable_pointers &&
707          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
708     return _.diag(SPV_ERROR_INVALID_ID, inst)
709            << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
710            << "' is not a logical pointer.";
711   }
712 
713   const auto pointer_type = _.FindDef(pointer->type_id());
714   if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
715     return _.diag(SPV_ERROR_INVALID_ID, inst)
716            << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
717            << "' is not a pointer type.";
718   }
719 
720   const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
721   if (!pointee_type || result_type->id() != pointee_type->id()) {
722     return _.diag(SPV_ERROR_INVALID_ID, inst)
723            << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
724            << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
725            << "'s type.";
726   }
727 
728   if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
729 
730   return SPV_SUCCESS;
731 }
732 
ValidateStore(ValidationState_t & _,const Instruction * inst)733 spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
734   const bool uses_variable_pointer =
735       _.features().variable_pointers ||
736       _.features().variable_pointers_storage_buffer;
737   const auto pointer_index = 0;
738   const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
739   const auto pointer = _.FindDef(pointer_id);
740   if (!pointer ||
741       (_.addressing_model() == SpvAddressingModelLogical &&
742        ((!uses_variable_pointer &&
743          !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
744         (uses_variable_pointer &&
745          !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
746     return _.diag(SPV_ERROR_INVALID_ID, inst)
747            << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
748            << "' is not a logical pointer.";
749   }
750   const auto pointer_type = _.FindDef(pointer->type_id());
751   if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
752     return _.diag(SPV_ERROR_INVALID_ID, inst)
753            << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
754            << "' is not a pointer type.";
755   }
756   const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
757   const auto type = _.FindDef(type_id);
758   if (!type || SpvOpTypeVoid == type->opcode()) {
759     return _.diag(SPV_ERROR_INVALID_ID, inst)
760            << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
761            << "'s type is void.";
762   }
763 
764   // validate storage class
765   {
766     uint32_t data_type;
767     uint32_t storage_class;
768     if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
769       return _.diag(SPV_ERROR_INVALID_ID, inst)
770              << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
771              << "' is not pointer type";
772     }
773 
774     if (storage_class == SpvStorageClassUniformConstant ||
775         storage_class == SpvStorageClassInput ||
776         storage_class == SpvStorageClassPushConstant) {
777       return _.diag(SPV_ERROR_INVALID_ID, inst)
778              << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
779              << "' storage class is read-only";
780     }
781   }
782 
783   const auto object_index = 1;
784   const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
785   const auto object = _.FindDef(object_id);
786   if (!object || !object->type_id()) {
787     return _.diag(SPV_ERROR_INVALID_ID, inst)
788            << "OpStore Object <id> '" << _.getIdName(object_id)
789            << "' is not an object.";
790   }
791   const auto object_type = _.FindDef(object->type_id());
792   if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
793     return _.diag(SPV_ERROR_INVALID_ID, inst)
794            << "OpStore Object <id> '" << _.getIdName(object_id)
795            << "'s type is void.";
796   }
797 
798   if (type->id() != object_type->id()) {
799     if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
800         object_type->opcode() != SpvOpTypeStruct) {
801       return _.diag(SPV_ERROR_INVALID_ID, inst)
802              << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
803              << "'s type does not match Object <id> '"
804              << _.getIdName(object->id()) << "'s type.";
805     }
806 
807     // TODO: Check for layout compatible matricies and arrays as well.
808     if (!AreLayoutCompatibleStructs(_, type, object_type)) {
809       return _.diag(SPV_ERROR_INVALID_ID, inst)
810              << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
811              << "'s layout does not match Object <id> '"
812              << _.getIdName(object->id()) << "'s layout.";
813     }
814   }
815 
816   if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
817 
818   return SPV_SUCCESS;
819 }
820 
ValidateCopyMemory(ValidationState_t & _,const Instruction * inst)821 spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
822   const auto target_index = 0;
823   const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
824   const auto target = _.FindDef(target_id);
825   if (!target) {
826     return _.diag(SPV_ERROR_INVALID_ID, inst)
827            << "Target operand <id> '" << _.getIdName(target_id)
828            << "' is not defined.";
829   }
830 
831   const auto source_index = 1;
832   const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
833   const auto source = _.FindDef(source_id);
834   if (!source) {
835     return _.diag(SPV_ERROR_INVALID_ID, inst)
836            << "Source operand <id> '" << _.getIdName(source_id)
837            << "' is not defined.";
838   }
839 
840   const auto target_pointer_type = _.FindDef(target->type_id());
841   if (!target_pointer_type ||
842       target_pointer_type->opcode() != SpvOpTypePointer) {
843     return _.diag(SPV_ERROR_INVALID_ID, inst)
844            << "Target operand <id> '" << _.getIdName(target_id)
845            << "' is not a pointer.";
846   }
847 
848   const auto source_pointer_type = _.FindDef(source->type_id());
849   if (!source_pointer_type ||
850       source_pointer_type->opcode() != SpvOpTypePointer) {
851     return _.diag(SPV_ERROR_INVALID_ID, inst)
852            << "Source operand <id> '" << _.getIdName(source_id)
853            << "' is not a pointer.";
854   }
855 
856   if (inst->opcode() == SpvOpCopyMemory) {
857     const auto target_type =
858         _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
859     if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
860       return _.diag(SPV_ERROR_INVALID_ID, inst)
861              << "Target operand <id> '" << _.getIdName(target_id)
862              << "' cannot be a void pointer.";
863     }
864 
865     const auto source_type =
866         _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
867     if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
868       return _.diag(SPV_ERROR_INVALID_ID, inst)
869              << "Source operand <id> '" << _.getIdName(source_id)
870              << "' cannot be a void pointer.";
871     }
872 
873     if (target_type->id() != source_type->id()) {
874       return _.diag(SPV_ERROR_INVALID_ID, inst)
875              << "Target <id> '" << _.getIdName(source_id)
876              << "'s type does not match Source <id> '"
877              << _.getIdName(source_type->id()) << "'s type.";
878     }
879 
880     if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
881   } else {
882     const auto size_id = inst->GetOperandAs<uint32_t>(2);
883     const auto size = _.FindDef(size_id);
884     if (!size) {
885       return _.diag(SPV_ERROR_INVALID_ID, inst)
886              << "Size operand <id> '" << _.getIdName(size_id)
887              << "' is not defined.";
888     }
889 
890     const auto size_type = _.FindDef(size->type_id());
891     if (!_.IsIntScalarType(size_type->id())) {
892       return _.diag(SPV_ERROR_INVALID_ID, inst)
893              << "Size operand <id> '" << _.getIdName(size_id)
894              << "' must be a scalar integer type.";
895     }
896 
897     bool is_zero = true;
898     switch (size->opcode()) {
899       case SpvOpConstantNull:
900         return _.diag(SPV_ERROR_INVALID_ID, inst)
901                << "Size operand <id> '" << _.getIdName(size_id)
902                << "' cannot be a constant zero.";
903       case SpvOpConstant:
904         if (size_type->word(3) == 1 &&
905             size->word(size->words().size() - 1) & 0x80000000) {
906           return _.diag(SPV_ERROR_INVALID_ID, inst)
907                  << "Size operand <id> '" << _.getIdName(size_id)
908                  << "' cannot have the sign bit set to 1.";
909         }
910         for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
911           is_zero &= (size->word(i) == 0);
912         }
913         if (is_zero) {
914           return _.diag(SPV_ERROR_INVALID_ID, inst)
915                  << "Size operand <id> '" << _.getIdName(size_id)
916                  << "' cannot be a constant zero.";
917         }
918         break;
919       default:
920         // Cannot infer any other opcodes.
921         break;
922     }
923 
924     if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
925   }
926   return SPV_SUCCESS;
927 }
928 
ValidateAccessChain(ValidationState_t & _,const Instruction * inst)929 spv_result_t ValidateAccessChain(ValidationState_t& _,
930                                  const Instruction* inst) {
931   std::string instr_name =
932       "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
933 
934   // The result type must be OpTypePointer.
935   auto result_type = _.FindDef(inst->type_id());
936   if (SpvOpTypePointer != result_type->opcode()) {
937     return _.diag(SPV_ERROR_INVALID_ID, inst)
938            << "The Result Type of " << instr_name << " <id> '"
939            << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
940            << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
941   }
942 
943   // Result type is a pointer. Find out what it's pointing to.
944   // This will be used to make sure the indexing results in the same type.
945   // OpTypePointer word 3 is the type being pointed to.
946   const auto result_type_pointee = _.FindDef(result_type->word(3));
947 
948   // Base must be a pointer, pointing to the base of a composite object.
949   const auto base_index = 2;
950   const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
951   const auto base = _.FindDef(base_id);
952   const auto base_type = _.FindDef(base->type_id());
953   if (!base_type || SpvOpTypePointer != base_type->opcode()) {
954     return _.diag(SPV_ERROR_INVALID_ID, inst)
955            << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
956            << " instruction must be a pointer.";
957   }
958 
959   // The result pointer storage class and base pointer storage class must match.
960   // Word 2 of OpTypePointer is the Storage Class.
961   auto result_type_storage_class = result_type->word(2);
962   auto base_type_storage_class = base_type->word(2);
963   if (result_type_storage_class != base_type_storage_class) {
964     return _.diag(SPV_ERROR_INVALID_ID, inst)
965            << "The result pointer storage class and base "
966               "pointer storage class in "
967            << instr_name << " do not match.";
968   }
969 
970   // The type pointed to by OpTypePointer (word 3) must be a composite type.
971   auto type_pointee = _.FindDef(base_type->word(3));
972 
973   // Check Universal Limit (SPIR-V Spec. Section 2.17).
974   // The number of indexes passed to OpAccessChain may not exceed 255
975   // The instruction includes 4 words + N words (for N indexes)
976   size_t num_indexes = inst->words().size() - 4;
977   if (inst->opcode() == SpvOpPtrAccessChain ||
978       inst->opcode() == SpvOpInBoundsPtrAccessChain) {
979     // In pointer access chains, the element operand is required, but not
980     // counted as an index.
981     --num_indexes;
982   }
983   const size_t num_indexes_limit =
984       _.options()->universal_limits_.max_access_chain_indexes;
985   if (num_indexes > num_indexes_limit) {
986     return _.diag(SPV_ERROR_INVALID_ID, inst)
987            << "The number of indexes in " << instr_name << " may not exceed "
988            << num_indexes_limit << ". Found " << num_indexes << " indexes.";
989   }
990   // Indexes walk the type hierarchy to the desired depth, potentially down to
991   // scalar granularity. The first index in Indexes will select the top-level
992   // member/element/component/element of the base composite. All composite
993   // constituents use zero-based numbering, as described by their OpType...
994   // instruction. The second index will apply similarly to that result, and so
995   // on. Once any non-composite type is reached, there must be no remaining
996   // (unused) indexes.
997   auto starting_index = 4;
998   if (inst->opcode() == SpvOpPtrAccessChain ||
999       inst->opcode() == SpvOpInBoundsPtrAccessChain) {
1000     ++starting_index;
1001   }
1002   for (size_t i = starting_index; i < inst->words().size(); ++i) {
1003     const uint32_t cur_word = inst->words()[i];
1004     // Earlier ID checks ensure that cur_word definition exists.
1005     auto cur_word_instr = _.FindDef(cur_word);
1006     // The index must be a scalar integer type (See OpAccessChain in the Spec.)
1007     auto index_type = _.FindDef(cur_word_instr->type_id());
1008     if (!index_type || SpvOpTypeInt != index_type->opcode()) {
1009       return _.diag(SPV_ERROR_INVALID_ID, inst)
1010              << "Indexes passed to " << instr_name
1011              << " must be of type integer.";
1012     }
1013     switch (type_pointee->opcode()) {
1014       case SpvOpTypeMatrix:
1015       case SpvOpTypeVector:
1016       case SpvOpTypeArray:
1017       case SpvOpTypeRuntimeArray: {
1018         // In OpTypeMatrix, OpTypeVector, OpTypeArray, and OpTypeRuntimeArray,
1019         // word 2 is the Element Type.
1020         type_pointee = _.FindDef(type_pointee->word(2));
1021         break;
1022       }
1023       case SpvOpTypeStruct: {
1024         // In case of structures, there is an additional constraint on the
1025         // index: the index must be an OpConstant.
1026         if (SpvOpConstant != cur_word_instr->opcode()) {
1027           return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1028                  << "The <id> passed to " << instr_name
1029                  << " to index into a "
1030                     "structure must be an OpConstant.";
1031         }
1032         // Get the index value from the OpConstant (word 3 of OpConstant).
1033         // OpConstant could be a signed integer. But it's okay to treat it as
1034         // unsigned because a negative constant int would never be seen as
1035         // correct as a struct offset, since structs can't have more than 2
1036         // billion members.
1037         const uint32_t cur_index = cur_word_instr->word(3);
1038         // The index points to the struct member we want, therefore, the index
1039         // should be less than the number of struct members.
1040         const uint32_t num_struct_members =
1041             static_cast<uint32_t>(type_pointee->words().size() - 2);
1042         if (cur_index >= num_struct_members) {
1043           return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1044                  << "Index is out of bounds: " << instr_name
1045                  << " can not find index " << cur_index
1046                  << " into the structure <id> '"
1047                  << _.getIdName(type_pointee->id()) << "'. This structure has "
1048                  << num_struct_members << " members. Largest valid index is "
1049                  << num_struct_members - 1 << ".";
1050         }
1051         // Struct members IDs start at word 2 of OpTypeStruct.
1052         auto structMemberId = type_pointee->word(cur_index + 2);
1053         type_pointee = _.FindDef(structMemberId);
1054         break;
1055       }
1056       default: {
1057         // Give an error. reached non-composite type while indexes still remain.
1058         return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
1059                << instr_name
1060                << " reached non-composite type while indexes "
1061                   "still remain to be traversed.";
1062       }
1063     }
1064   }
1065   // At this point, we have fully walked down from the base using the indeces.
1066   // The type being pointed to should be the same as the result type.
1067   if (type_pointee->id() != result_type_pointee->id()) {
1068     return _.diag(SPV_ERROR_INVALID_ID, inst)
1069            << instr_name << " result type (Op"
1070            << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
1071            << ") does not match the type that results from indexing into the "
1072               "base "
1073               "<id> (Op"
1074            << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
1075            << ").";
1076   }
1077 
1078   return SPV_SUCCESS;
1079 }
1080 
ValidatePtrAccessChain(ValidationState_t & _,const Instruction * inst)1081 spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
1082                                     const Instruction* inst) {
1083   if (_.addressing_model() == SpvAddressingModelLogical) {
1084     if (!_.features().variable_pointers &&
1085         !_.features().variable_pointers_storage_buffer) {
1086       return _.diag(SPV_ERROR_INVALID_DATA, inst)
1087              << "Generating variable pointers requires capability "
1088              << "VariablePointers or VariablePointersStorageBuffer";
1089     }
1090   }
1091   return ValidateAccessChain(_, inst);
1092 }
1093 
ValidateArrayLength(ValidationState_t & state,const Instruction * inst)1094 spv_result_t ValidateArrayLength(ValidationState_t& state,
1095                                  const Instruction* inst) {
1096   std::string instr_name =
1097       "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));
1098 
1099   // Result type must be a 32-bit unsigned int.
1100   auto result_type = state.FindDef(inst->type_id());
1101   if (result_type->opcode() != SpvOpTypeInt ||
1102       result_type->GetOperandAs<uint32_t>(1) != 32 ||
1103       result_type->GetOperandAs<uint32_t>(2) != 0) {
1104     return state.diag(SPV_ERROR_INVALID_ID, inst)
1105            << "The Result Type of " << instr_name << " <id> '"
1106            << state.getIdName(inst->id())
1107            << "' must be OpTypeInt with width 32 and signedness 0.";
1108   }
1109 
1110   // The structure that is passed in must be an pointer to a structure, whose
1111   // last element is a runtime array.
1112   auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
1113   auto pointer_type = state.FindDef(pointer->type_id());
1114   if (pointer_type->opcode() != SpvOpTypePointer) {
1115     return state.diag(SPV_ERROR_INVALID_ID, inst)
1116            << "The Struture's type in " << instr_name << " <id> '"
1117            << state.getIdName(inst->id())
1118            << "' must be a pointer to an OpTypeStruct.";
1119   }
1120 
1121   auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
1122   if (structure_type->opcode() != SpvOpTypeStruct) {
1123     return state.diag(SPV_ERROR_INVALID_ID, inst)
1124            << "The Struture's type in " << instr_name << " <id> '"
1125            << state.getIdName(inst->id())
1126            << "' must be a pointer to an OpTypeStruct.";
1127   }
1128 
1129   auto num_of_members = structure_type->operands().size() - 1;
1130   auto last_member =
1131       state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
1132   if (last_member->opcode() != SpvOpTypeRuntimeArray) {
1133     return state.diag(SPV_ERROR_INVALID_ID, inst)
1134            << "The Struture's last member in " << instr_name << " <id> '"
1135            << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
1136   }
1137 
1138   // The array member must the the index of the last element (the run time
1139   // array).
1140   if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
1141     return state.diag(SPV_ERROR_INVALID_ID, inst)
1142            << "The array member in " << instr_name << " <id> '"
1143            << state.getIdName(inst->id())
1144            << "' must be an the last member of the struct.";
1145   }
1146   return SPV_SUCCESS;
1147 }
1148 
1149 }  // namespace
1150 
MemoryPass(ValidationState_t & _,const Instruction * inst)1151 spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
1152   switch (inst->opcode()) {
1153     case SpvOpVariable:
1154       if (auto error = ValidateVariable(_, inst)) return error;
1155       break;
1156     case SpvOpLoad:
1157       if (auto error = ValidateLoad(_, inst)) return error;
1158       break;
1159     case SpvOpStore:
1160       if (auto error = ValidateStore(_, inst)) return error;
1161       break;
1162     case SpvOpCopyMemory:
1163     case SpvOpCopyMemorySized:
1164       if (auto error = ValidateCopyMemory(_, inst)) return error;
1165       break;
1166     case SpvOpPtrAccessChain:
1167       if (auto error = ValidatePtrAccessChain(_, inst)) return error;
1168       break;
1169     case SpvOpAccessChain:
1170     case SpvOpInBoundsAccessChain:
1171     case SpvOpInBoundsPtrAccessChain:
1172       if (auto error = ValidateAccessChain(_, inst)) return error;
1173       break;
1174     case SpvOpArrayLength:
1175       if (auto error = ValidateArrayLength(_, inst)) return error;
1176       break;
1177     case SpvOpImageTexelPointer:
1178     case SpvOpGenericPtrMemSemantics:
1179     default:
1180       break;
1181   }
1182 
1183   return SPV_SUCCESS;
1184 }
1185 }  // namespace val
1186 }  // namespace spvtools
1187