• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <algorithm>
16 #include <vector>
17 
18 #include "source/spirv_constant.h"
19 #include "source/spirv_target_env.h"
20 #include "source/val/function.h"
21 #include "source/val/instruction.h"
22 #include "source/val/validate.h"
23 #include "source/val/validation_state.h"
24 
25 namespace spvtools {
26 namespace val {
27 namespace {
28 
29 // Limit the number of checked locations to 4096. Multiplied by 4 to represent
30 // all the components. This limit is set to be well beyond practical use cases.
31 const uint32_t kMaxLocations = 4096 * 4;
32 
33 // Returns true if \c inst is an input or output variable.
is_interface_variable(const Instruction * inst,bool is_spv_1_4)34 bool is_interface_variable(const Instruction* inst, bool is_spv_1_4) {
35   if (is_spv_1_4) {
36     // Starting in SPIR-V 1.4, all global variables are interface variables.
37     return inst->opcode() == spv::Op::OpVariable &&
38            inst->GetOperandAs<spv::StorageClass>(2u) !=
39                spv::StorageClass::Function;
40   } else {
41     return inst->opcode() == spv::Op::OpVariable &&
42            (inst->GetOperandAs<spv::StorageClass>(2u) ==
43                 spv::StorageClass::Input ||
44             inst->GetOperandAs<spv::StorageClass>(2u) ==
45                 spv::StorageClass::Output);
46   }
47 }
48 
49 // Checks that \c var is listed as an interface in all the entry points that use
50 // it.
check_interface_variable(ValidationState_t & _,const Instruction * var)51 spv_result_t check_interface_variable(ValidationState_t& _,
52                                       const Instruction* var) {
53   std::vector<const Function*> functions;
54   std::vector<const Instruction*> uses;
55   for (auto use : var->uses()) {
56     uses.push_back(use.first);
57   }
58   for (uint32_t i = 0; i < uses.size(); ++i) {
59     const auto user = uses[i];
60     if (const Function* func = user->function()) {
61       functions.push_back(func);
62     } else {
63       // In the rare case that the variable is used by another instruction in
64       // the global scope, continue searching for an instruction used in a
65       // function.
66       for (auto use : user->uses()) {
67         uses.push_back(use.first);
68       }
69     }
70   }
71 
72   std::sort(functions.begin(), functions.end(),
73             [](const Function* lhs, const Function* rhs) {
74               return lhs->id() < rhs->id();
75             });
76   functions.erase(std::unique(functions.begin(), functions.end()),
77                   functions.end());
78 
79   std::vector<uint32_t> entry_points;
80   for (const auto func : functions) {
81     for (auto id : _.FunctionEntryPoints(func->id())) {
82       entry_points.push_back(id);
83     }
84   }
85 
86   std::sort(entry_points.begin(), entry_points.end());
87   entry_points.erase(std::unique(entry_points.begin(), entry_points.end()),
88                      entry_points.end());
89 
90   for (auto id : entry_points) {
91     for (const auto& desc : _.entry_point_descriptions(id)) {
92       bool found = false;
93       for (auto interface : desc.interfaces) {
94         if (var->id() == interface) {
95           found = true;
96           break;
97         }
98       }
99       if (!found) {
100         return _.diag(SPV_ERROR_INVALID_ID, var)
101                << "Interface variable id <" << var->id()
102                << "> is used by entry point '" << desc.name << "' id <" << id
103                << ">, but is not listed as an interface";
104       }
105     }
106   }
107 
108   return SPV_SUCCESS;
109 }
110 
111 // This function assumes a base location has been determined already. As such
112 // any further location decorations are invalid.
113 // TODO: if this code turns out to be slow, there is an opportunity to cache
114 // the result for a given type id.
NumConsumedLocations(ValidationState_t & _,const Instruction * type,uint32_t * num_locations)115 spv_result_t NumConsumedLocations(ValidationState_t& _, const Instruction* type,
116                                   uint32_t* num_locations) {
117   *num_locations = 0;
118   switch (type->opcode()) {
119     case spv::Op::OpTypeInt:
120     case spv::Op::OpTypeFloat:
121       // Scalars always consume a single location.
122       *num_locations = 1;
123       break;
124     case spv::Op::OpTypeVector:
125       // 3- and 4-component 64-bit vectors consume two locations.
126       if ((_.ContainsSizedIntOrFloatType(type->id(), spv::Op::OpTypeInt, 64) ||
127            _.ContainsSizedIntOrFloatType(type->id(), spv::Op::OpTypeFloat,
128                                          64)) &&
129           (type->GetOperandAs<uint32_t>(2) > 2)) {
130         *num_locations = 2;
131       } else {
132         *num_locations = 1;
133       }
134       break;
135     case spv::Op::OpTypeMatrix:
136       // Matrices consume locations equal to the underlying vector type for
137       // each column.
138       NumConsumedLocations(_, _.FindDef(type->GetOperandAs<uint32_t>(1)),
139                            num_locations);
140       *num_locations *= type->GetOperandAs<uint32_t>(2);
141       break;
142     case spv::Op::OpTypeArray: {
143       // Arrays consume locations equal to the underlying type times the number
144       // of elements in the vector.
145       NumConsumedLocations(_, _.FindDef(type->GetOperandAs<uint32_t>(1)),
146                            num_locations);
147       bool is_int = false;
148       bool is_const = false;
149       uint32_t value = 0;
150       // Attempt to evaluate the number of array elements.
151       std::tie(is_int, is_const, value) =
152           _.EvalInt32IfConst(type->GetOperandAs<uint32_t>(2));
153       if (is_int && is_const) *num_locations *= value;
154       break;
155     }
156     case spv::Op::OpTypeStruct: {
157       // Members cannot have location decorations at this point.
158       if (_.HasDecoration(type->id(), spv::Decoration::Location)) {
159         return _.diag(SPV_ERROR_INVALID_DATA, type)
160                << _.VkErrorID(4918) << "Members cannot be assigned a location";
161       }
162 
163       // Structs consume locations equal to the sum of the locations consumed
164       // by the members.
165       for (uint32_t i = 1; i < type->operands().size(); ++i) {
166         uint32_t member_locations = 0;
167         if (auto error = NumConsumedLocations(
168                 _, _.FindDef(type->GetOperandAs<uint32_t>(i)),
169                 &member_locations)) {
170           return error;
171         }
172         *num_locations += member_locations;
173       }
174       break;
175     }
176     case spv::Op::OpTypePointer: {
177       if (_.addressing_model() ==
178               spv::AddressingModel::PhysicalStorageBuffer64 &&
179           type->GetOperandAs<spv::StorageClass>(1) ==
180               spv::StorageClass::PhysicalStorageBuffer) {
181         *num_locations = 1;
182         break;
183       }
184       [[fallthrough]];
185     }
186     default:
187       return _.diag(SPV_ERROR_INVALID_DATA, type)
188              << "Invalid type to assign a location";
189   }
190 
191   return SPV_SUCCESS;
192 }
193 
194 // Returns the number of components consumed by types that support a component
195 // decoration.
NumConsumedComponents(ValidationState_t & _,const Instruction * type)196 uint32_t NumConsumedComponents(ValidationState_t& _, const Instruction* type) {
197   uint32_t num_components = 0;
198   switch (type->opcode()) {
199     case spv::Op::OpTypeInt:
200     case spv::Op::OpTypeFloat:
201       // 64-bit types consume two components.
202       if (type->GetOperandAs<uint32_t>(1) == 64) {
203         num_components = 2;
204       } else {
205         num_components = 1;
206       }
207       break;
208     case spv::Op::OpTypeVector:
209       // Vectors consume components equal to the underlying type's consumption
210       // times the number of elements in the vector. Note that 3- and 4-element
211       // vectors cannot have a component decoration (i.e. assumed to be zero).
212       num_components =
213           NumConsumedComponents(_, _.FindDef(type->GetOperandAs<uint32_t>(1)));
214       num_components *= type->GetOperandAs<uint32_t>(2);
215       break;
216     case spv::Op::OpTypeArray:
217       // Skip the array.
218       return NumConsumedComponents(_,
219                                    _.FindDef(type->GetOperandAs<uint32_t>(1)));
220     case spv::Op::OpTypePointer:
221       if (_.addressing_model() ==
222               spv::AddressingModel::PhysicalStorageBuffer64 &&
223           type->GetOperandAs<spv::StorageClass>(1) ==
224               spv::StorageClass::PhysicalStorageBuffer) {
225         return 2;
226       }
227       break;
228     default:
229       // This is an error that is validated elsewhere.
230       break;
231   }
232 
233   return num_components;
234 }
235 
236 // Populates |locations| (and/or |output_index1_locations|) with the use
237 // location and component coordinates for |variable|. Indices are calculated as
238 // 4 * location + component.
GetLocationsForVariable(ValidationState_t & _,const Instruction * entry_point,const Instruction * variable,std::unordered_set<uint32_t> * locations,std::unordered_set<uint32_t> * output_index1_locations)239 spv_result_t GetLocationsForVariable(
240     ValidationState_t& _, const Instruction* entry_point,
241     const Instruction* variable, std::unordered_set<uint32_t>* locations,
242     std::unordered_set<uint32_t>* output_index1_locations) {
243   const bool is_fragment = entry_point->GetOperandAs<spv::ExecutionModel>(0) ==
244                            spv::ExecutionModel::Fragment;
245   const bool is_output =
246       variable->GetOperandAs<spv::StorageClass>(2) == spv::StorageClass::Output;
247   auto ptr_type_id = variable->GetOperandAs<uint32_t>(0);
248   auto ptr_type = _.FindDef(ptr_type_id);
249   auto type_id = ptr_type->GetOperandAs<uint32_t>(2);
250   auto type = _.FindDef(type_id);
251 
252   // Check for Location, Component and Index decorations on the variable. The
253   // validator allows duplicate decorations if the location/component/index are
254   // equal. Also track Patch and PerTaskNV decorations.
255   bool has_location = false;
256   uint32_t location = 0;
257   bool has_component = false;
258   uint32_t component = 0;
259   bool has_index = false;
260   uint32_t index = 0;
261   bool has_patch = false;
262   bool has_per_task_nv = false;
263   bool has_per_vertex_khr = false;
264   for (auto& dec : _.id_decorations(variable->id())) {
265     if (dec.dec_type() == spv::Decoration::Location) {
266       if (has_location && dec.params()[0] != location) {
267         return _.diag(SPV_ERROR_INVALID_DATA, variable)
268                << "Variable has conflicting location decorations";
269       }
270       has_location = true;
271       location = dec.params()[0];
272     } else if (dec.dec_type() == spv::Decoration::Component) {
273       if (has_component && dec.params()[0] != component) {
274         return _.diag(SPV_ERROR_INVALID_DATA, variable)
275                << "Variable has conflicting component decorations";
276       }
277       has_component = true;
278       component = dec.params()[0];
279     } else if (dec.dec_type() == spv::Decoration::Index) {
280       if (!is_output || !is_fragment) {
281         return _.diag(SPV_ERROR_INVALID_DATA, variable)
282                << "Index can only be applied to Fragment output variables";
283       }
284       if (has_index && dec.params()[0] != index) {
285         return _.diag(SPV_ERROR_INVALID_DATA, variable)
286                << "Variable has conflicting index decorations";
287       }
288       has_index = true;
289       index = dec.params()[0];
290     } else if (dec.dec_type() == spv::Decoration::BuiltIn) {
291       // Don't check built-ins.
292       return SPV_SUCCESS;
293     } else if (dec.dec_type() == spv::Decoration::Patch) {
294       has_patch = true;
295     } else if (dec.dec_type() == spv::Decoration::PerTaskNV) {
296       has_per_task_nv = true;
297     } else if (dec.dec_type() == spv::Decoration::PerVertexKHR) {
298       if (!is_fragment) {
299         return _.diag(SPV_ERROR_INVALID_DATA, variable)
300                << _.VkErrorID(6777)
301                << "PerVertexKHR can only be applied to Fragment Execution "
302                   "Models";
303       }
304       if (type->opcode() != spv::Op::OpTypeArray &&
305           type->opcode() != spv::Op::OpTypeRuntimeArray) {
306         return _.diag(SPV_ERROR_INVALID_DATA, variable)
307                << _.VkErrorID(6778)
308                << "PerVertexKHR must be declared as arrays";
309       }
310       has_per_vertex_khr = true;
311     }
312   }
313 
314   // Vulkan 14.1.3: Tessellation control and mesh per-vertex outputs and
315   // tessellation control, evaluation and geometry per-vertex inputs have a
316   // layer of arraying that is not included in interface matching.
317   bool is_arrayed = false;
318   switch (entry_point->GetOperandAs<spv::ExecutionModel>(0)) {
319     case spv::ExecutionModel::TessellationControl:
320       if (!has_patch) {
321         is_arrayed = true;
322       }
323       break;
324     case spv::ExecutionModel::TessellationEvaluation:
325       if (!is_output && !has_patch) {
326         is_arrayed = true;
327       }
328       break;
329     case spv::ExecutionModel::Geometry:
330       if (!is_output) {
331         is_arrayed = true;
332       }
333       break;
334     case spv::ExecutionModel::Fragment:
335       if (!is_output && has_per_vertex_khr) {
336         is_arrayed = true;
337       }
338       break;
339     case spv::ExecutionModel::MeshNV:
340       if (is_output && !has_per_task_nv) {
341         is_arrayed = true;
342       }
343       break;
344     default:
345       break;
346   }
347 
348   // Unpack arrayness.
349   if (is_arrayed && (type->opcode() == spv::Op::OpTypeArray ||
350                      type->opcode() == spv::Op::OpTypeRuntimeArray)) {
351     type_id = type->GetOperandAs<uint32_t>(1);
352     type = _.FindDef(type_id);
353   }
354 
355   if (type->opcode() == spv::Op::OpTypeStruct) {
356     // Don't check built-ins.
357     if (_.HasDecoration(type_id, spv::Decoration::BuiltIn)) return SPV_SUCCESS;
358   }
359 
360   // Only block-decorated structs don't need a location on the variable.
361   const bool is_block = _.HasDecoration(type_id, spv::Decoration::Block);
362   if (!has_location && !is_block) {
363     const auto vuid = (type->opcode() == spv::Op::OpTypeStruct) ? 4917 : 4916;
364     return _.diag(SPV_ERROR_INVALID_DATA, variable)
365            << _.VkErrorID(vuid) << "Variable must be decorated with a location";
366   }
367 
368   const std::string storage_class = is_output ? "output" : "input";
369   if (has_location) {
370     auto sub_type = type;
371     bool is_int = false;
372     bool is_const = false;
373     uint32_t array_size = 1;
374     // If the variable is still arrayed, mark the locations/components per
375     // index.
376     if (type->opcode() == spv::Op::OpTypeArray) {
377       // Determine the array size if possible and get the element type.
378       std::tie(is_int, is_const, array_size) =
379           _.EvalInt32IfConst(type->GetOperandAs<uint32_t>(2));
380       if (!is_int || !is_const) array_size = 1;
381       auto sub_type_id = type->GetOperandAs<uint32_t>(1);
382       sub_type = _.FindDef(sub_type_id);
383     }
384 
385     uint32_t num_locations = 0;
386     if (auto error = NumConsumedLocations(_, sub_type, &num_locations))
387       return error;
388     uint32_t num_components = NumConsumedComponents(_, sub_type);
389 
390     for (uint32_t array_idx = 0; array_idx < array_size; ++array_idx) {
391       uint32_t array_location = location + (num_locations * array_idx);
392       uint32_t start = array_location * 4;
393       if (kMaxLocations <= start) {
394         // Too many locations, give up.
395         break;
396       }
397 
398       uint32_t end = (array_location + num_locations) * 4;
399       if (num_components != 0) {
400         start += component;
401         end = array_location * 4 + component + num_components;
402       }
403 
404       auto locs = locations;
405       if (has_index && index == 1) locs = output_index1_locations;
406 
407       for (uint32_t i = start; i < end; ++i) {
408         if (!locs->insert(i).second) {
409           return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
410                  << (is_output ? _.VkErrorID(8722) : _.VkErrorID(8721))
411                  << "Entry-point has conflicting " << storage_class
412                  << " location assignment at location " << i / 4
413                  << ", component " << i % 4;
414         }
415       }
416     }
417   } else {
418     // For Block-decorated structs with no location assigned to the variable,
419     // each member of the block must be assigned a location. Also record any
420     // member component assignments. The validator allows duplicate decorations
421     // if they agree on the location/component.
422     std::unordered_map<uint32_t, uint32_t> member_locations;
423     std::unordered_map<uint32_t, uint32_t> member_components;
424     for (auto& dec : _.id_decorations(type_id)) {
425       if (dec.dec_type() == spv::Decoration::Location) {
426         auto where = member_locations.find(dec.struct_member_index());
427         if (where == member_locations.end()) {
428           member_locations[dec.struct_member_index()] = dec.params()[0];
429         } else if (where->second != dec.params()[0]) {
430           return _.diag(SPV_ERROR_INVALID_DATA, type)
431                  << "Member index " << dec.struct_member_index()
432                  << " has conflicting location assignments";
433         }
434       } else if (dec.dec_type() == spv::Decoration::Component) {
435         auto where = member_components.find(dec.struct_member_index());
436         if (where == member_components.end()) {
437           member_components[dec.struct_member_index()] = dec.params()[0];
438         } else if (where->second != dec.params()[0]) {
439           return _.diag(SPV_ERROR_INVALID_DATA, type)
440                  << "Member index " << dec.struct_member_index()
441                  << " has conflicting component assignments";
442         }
443       }
444     }
445 
446     for (uint32_t i = 1; i < type->operands().size(); ++i) {
447       auto where = member_locations.find(i - 1);
448       if (where == member_locations.end()) {
449         return _.diag(SPV_ERROR_INVALID_DATA, type)
450                << _.VkErrorID(4919) << "Member index " << i - 1
451                << " is missing a location assignment";
452       }
453 
454       location = where->second;
455       auto member = _.FindDef(type->GetOperandAs<uint32_t>(i));
456       uint32_t num_locations = 0;
457       if (auto error = NumConsumedLocations(_, member, &num_locations))
458         return error;
459 
460       // If the component is not specified, it is assumed to be zero.
461       uint32_t num_components = NumConsumedComponents(_, member);
462       component = 0;
463       if (member_components.count(i - 1)) {
464         component = member_components[i - 1];
465       }
466 
467       uint32_t start = location * 4;
468       if (kMaxLocations <= start) {
469         // Too many locations, give up.
470         continue;
471       }
472 
473       if (member->opcode() == spv::Op::OpTypeArray && num_components >= 1 &&
474           num_components < 4) {
475         // When an array has an element that takes less than a location in
476         // size, calculate the used locations in a strided manner.
477         for (uint32_t l = location; l < num_locations + location; ++l) {
478           for (uint32_t c = component; c < component + num_components; ++c) {
479             uint32_t check = 4 * l + c;
480             if (!locations->insert(check).second) {
481               return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
482                      << (is_output ? _.VkErrorID(8722) : _.VkErrorID(8721))
483                      << "Entry-point has conflicting " << storage_class
484                      << " location assignment at location " << l
485                      << ", component " << c;
486             }
487           }
488         }
489       } else {
490         // TODO: There is a hole here is the member is an array of 3- or
491         // 4-element vectors of 64-bit types.
492         uint32_t end = (location + num_locations) * 4;
493         if (num_components != 0) {
494           start += component;
495           end = location * 4 + component + num_components;
496         }
497         for (uint32_t l = start; l < end; ++l) {
498           if (!locations->insert(l).second) {
499             return _.diag(SPV_ERROR_INVALID_DATA, entry_point)
500                    << (is_output ? _.VkErrorID(8722) : _.VkErrorID(8721))
501                    << "Entry-point has conflicting " << storage_class
502                    << " location assignment at location " << l / 4
503                    << ", component " << l % 4;
504           }
505         }
506       }
507     }
508   }
509 
510   return SPV_SUCCESS;
511 }
512 
ValidateLocations(ValidationState_t & _,const Instruction * entry_point)513 spv_result_t ValidateLocations(ValidationState_t& _,
514                                const Instruction* entry_point) {
515   // According to Vulkan 14.1 only the following execution models have
516   // locations assigned.
517   // TODO(dneto): SPV_NV_ray_tracing also uses locations on interface variables,
518   // in other shader stages. Similarly, the *provisional* version of
519   // SPV_KHR_ray_tracing did as well, but not the final version.
520   switch (entry_point->GetOperandAs<spv::ExecutionModel>(0)) {
521     case spv::ExecutionModel::Vertex:
522     case spv::ExecutionModel::TessellationControl:
523     case spv::ExecutionModel::TessellationEvaluation:
524     case spv::ExecutionModel::Geometry:
525     case spv::ExecutionModel::Fragment:
526       break;
527     default:
528       return SPV_SUCCESS;
529   }
530 
531   // Locations are stored as a combined location and component values.
532   std::unordered_set<uint32_t> input_locations;
533   std::unordered_set<uint32_t> output_locations_index0;
534   std::unordered_set<uint32_t> output_locations_index1;
535   std::unordered_set<uint32_t> seen;
536   for (uint32_t i = 3; i < entry_point->operands().size(); ++i) {
537     auto interface_id = entry_point->GetOperandAs<uint32_t>(i);
538     auto interface_var = _.FindDef(interface_id);
539     auto storage_class = interface_var->GetOperandAs<spv::StorageClass>(2);
540     if (storage_class != spv::StorageClass::Input &&
541         storage_class != spv::StorageClass::Output) {
542       continue;
543     }
544     if (!seen.insert(interface_id).second) {
545       // Pre-1.4 an interface variable could be listed multiple times in an
546       // entry point. Validation for 1.4 or later is done elsewhere.
547       continue;
548     }
549 
550     auto locations = (storage_class == spv::StorageClass::Input)
551                          ? &input_locations
552                          : &output_locations_index0;
553     if (auto error = GetLocationsForVariable(
554             _, entry_point, interface_var, locations, &output_locations_index1))
555       return error;
556   }
557 
558   return SPV_SUCCESS;
559 }
560 
561 }  // namespace
562 
ValidateInterfaces(ValidationState_t & _)563 spv_result_t ValidateInterfaces(ValidationState_t& _) {
564   bool is_spv_1_4 = _.version() >= SPV_SPIRV_VERSION_WORD(1, 4);
565   for (auto& inst : _.ordered_instructions()) {
566     if (is_interface_variable(&inst, is_spv_1_4)) {
567       if (auto error = check_interface_variable(_, &inst)) {
568         return error;
569       }
570     }
571   }
572 
573   if (spvIsVulkanEnv(_.context()->target_env)) {
574     for (auto& inst : _.ordered_instructions()) {
575       if (inst.opcode() == spv::Op::OpEntryPoint) {
576         if (auto error = ValidateLocations(_, &inst)) {
577           return error;
578         }
579       }
580       if (inst.opcode() == spv::Op::OpTypeVoid) break;
581     }
582   }
583 
584   return SPV_SUCCESS;
585 }
586 
587 }  // namespace val
588 }  // namespace spvtools
589