validate_decorations.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. // Copyright (c) 2017 Google Inc.
  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. #include <algorithm>
  15. #include <cassert>
  16. #include <string>
  17. #include <tuple>
  18. #include <unordered_map>
  19. #include <unordered_set>
  20. #include <utility>
  21. #include <vector>
  22. #include "source/diagnostic.h"
  23. #include "source/opcode.h"
  24. #include "source/spirv_constant.h"
  25. #include "source/spirv_target_env.h"
  26. #include "source/spirv_validator_options.h"
  27. #include "source/val/validate_scopes.h"
  28. #include "source/val/validation_state.h"
  29. namespace spvtools {
  30. namespace val {
  31. namespace {
  32. // Distinguish between row and column major matrix layouts.
  33. enum MatrixLayout { kRowMajor, kColumnMajor };
  34. // A functor for hashing a pair of integers.
  35. struct PairHash {
  36. std::size_t operator()(const std::pair<uint32_t, uint32_t> pair) const {
  37. const uint32_t a = pair.first;
  38. const uint32_t b = pair.second;
  39. const uint32_t rotated_b = (b >> 2) | ((b & 3) << 30);
  40. return a ^ rotated_b;
  41. }
  42. };
  43. // A functor for hashing decoration types.
  44. struct SpvDecorationHash {
  45. std::size_t operator()(SpvDecoration dec) const {
  46. return static_cast<std::size_t>(dec);
  47. }
  48. };
  49. // Struct member layout attributes that are inherited through arrays.
  50. struct LayoutConstraints {
  51. explicit LayoutConstraints(
  52. MatrixLayout the_majorness = MatrixLayout::kColumnMajor,
  53. uint32_t stride = 0)
  54. : majorness(the_majorness), matrix_stride(stride) {}
  55. MatrixLayout majorness;
  56. uint32_t matrix_stride;
  57. };
  58. // A type for mapping (struct id, member id) to layout constraints.
  59. using MemberConstraints = std::unordered_map<std::pair<uint32_t, uint32_t>,
  60. LayoutConstraints, PairHash>;
  61. // Returns the array stride of the given array type.
  62. uint32_t GetArrayStride(uint32_t array_id, ValidationState_t& vstate) {
  63. for (auto& decoration : vstate.id_decorations(array_id)) {
  64. if (SpvDecorationArrayStride == decoration.dec_type()) {
  65. return decoration.params()[0];
  66. }
  67. }
  68. return 0;
  69. }
  70. // Returns true if the given variable has a BuiltIn decoration.
  71. bool isBuiltInVar(uint32_t var_id, ValidationState_t& vstate) {
  72. const auto& decorations = vstate.id_decorations(var_id);
  73. return std::any_of(
  74. decorations.begin(), decorations.end(),
  75. [](const Decoration& d) { return SpvDecorationBuiltIn == d.dec_type(); });
  76. }
  77. // Returns true if the given structure type has any members with BuiltIn
  78. // decoration.
  79. bool isBuiltInStruct(uint32_t struct_id, ValidationState_t& vstate) {
  80. const auto& decorations = vstate.id_decorations(struct_id);
  81. return std::any_of(
  82. decorations.begin(), decorations.end(), [](const Decoration& d) {
  83. return SpvDecorationBuiltIn == d.dec_type() &&
  84. Decoration::kInvalidMember != d.struct_member_index();
  85. });
  86. }
  87. // Returns true if the given ID has the Import LinkageAttributes decoration.
  88. bool hasImportLinkageAttribute(uint32_t id, ValidationState_t& vstate) {
  89. const auto& decorations = vstate.id_decorations(id);
  90. return std::any_of(decorations.begin(), decorations.end(),
  91. [](const Decoration& d) {
  92. return SpvDecorationLinkageAttributes == d.dec_type() &&
  93. d.params().size() >= 2u &&
  94. d.params().back() == SpvLinkageTypeImport;
  95. });
  96. }
  97. // Returns a vector of all members of a structure.
  98. std::vector<uint32_t> getStructMembers(uint32_t struct_id,
  99. ValidationState_t& vstate) {
  100. const auto inst = vstate.FindDef(struct_id);
  101. return std::vector<uint32_t>(inst->words().begin() + 2, inst->words().end());
  102. }
  103. // Returns a vector of all members of a structure that have specific type.
  104. std::vector<uint32_t> getStructMembers(uint32_t struct_id, SpvOp type,
  105. ValidationState_t& vstate) {
  106. std::vector<uint32_t> members;
  107. for (auto id : getStructMembers(struct_id, vstate)) {
  108. if (type == vstate.FindDef(id)->opcode()) {
  109. members.push_back(id);
  110. }
  111. }
  112. return members;
  113. }
  114. // Returns whether the given structure is missing Offset decoration for any
  115. // member. Handles also nested structures.
  116. bool isMissingOffsetInStruct(uint32_t struct_id, ValidationState_t& vstate) {
  117. std::vector<bool> hasOffset(getStructMembers(struct_id, vstate).size(),
  118. false);
  119. // Check offsets of member decorations
  120. for (auto& decoration : vstate.id_decorations(struct_id)) {
  121. if (SpvDecorationOffset == decoration.dec_type() &&
  122. Decoration::kInvalidMember != decoration.struct_member_index()) {
  123. hasOffset[decoration.struct_member_index()] = true;
  124. }
  125. }
  126. // Check also nested structures
  127. bool nestedStructsMissingOffset = false;
  128. for (auto id : getStructMembers(struct_id, SpvOpTypeStruct, vstate)) {
  129. if (isMissingOffsetInStruct(id, vstate)) {
  130. nestedStructsMissingOffset = true;
  131. break;
  132. }
  133. }
  134. return nestedStructsMissingOffset ||
  135. !std::all_of(hasOffset.begin(), hasOffset.end(),
  136. [](const bool b) { return b; });
  137. }
  138. // Rounds x up to the next alignment. Assumes alignment is a power of two.
  139. uint32_t align(uint32_t x, uint32_t alignment) {
  140. return (x + alignment - 1) & ~(alignment - 1);
  141. }
  142. // Returns base alignment of struct member. If |roundUp| is true, also
  143. // ensure that structs and arrays are aligned at least to a multiple of 16
  144. // bytes.
  145. uint32_t getBaseAlignment(uint32_t member_id, bool roundUp,
  146. const LayoutConstraints& inherited,
  147. MemberConstraints& constraints,
  148. ValidationState_t& vstate) {
  149. const auto inst = vstate.FindDef(member_id);
  150. const auto& words = inst->words();
  151. // Minimal alignment is byte-aligned.
  152. uint32_t baseAlignment = 1;
  153. switch (inst->opcode()) {
  154. case SpvOpTypeInt:
  155. case SpvOpTypeFloat:
  156. baseAlignment = words[2] / 8;
  157. break;
  158. case SpvOpTypeVector: {
  159. const auto componentId = words[2];
  160. const auto numComponents = words[3];
  161. const auto componentAlignment = getBaseAlignment(
  162. componentId, roundUp, inherited, constraints, vstate);
  163. baseAlignment =
  164. componentAlignment * (numComponents == 3 ? 4 : numComponents);
  165. break;
  166. }
  167. case SpvOpTypeMatrix: {
  168. const auto column_type = words[2];
  169. if (inherited.majorness == kColumnMajor) {
  170. baseAlignment = getBaseAlignment(column_type, roundUp, inherited,
  171. constraints, vstate);
  172. } else {
  173. // A row-major matrix of C columns has a base alignment equal to the
  174. // base alignment of a vector of C matrix components.
  175. const auto num_columns = words[3];
  176. const auto component_inst = vstate.FindDef(column_type);
  177. const auto component_id = component_inst->words()[2];
  178. const auto componentAlignment = getBaseAlignment(
  179. component_id, roundUp, inherited, constraints, vstate);
  180. baseAlignment =
  181. componentAlignment * (num_columns == 3 ? 4 : num_columns);
  182. }
  183. } break;
  184. case SpvOpTypeArray:
  185. case SpvOpTypeRuntimeArray:
  186. baseAlignment =
  187. getBaseAlignment(words[2], roundUp, inherited, constraints, vstate);
  188. if (roundUp) baseAlignment = align(baseAlignment, 16u);
  189. break;
  190. case SpvOpTypeStruct: {
  191. const auto members = getStructMembers(member_id, vstate);
  192. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  193. memberIdx < numMembers; ++memberIdx) {
  194. const auto id = members[memberIdx];
  195. const auto& constraint =
  196. constraints[std::make_pair(member_id, memberIdx)];
  197. baseAlignment = std::max(
  198. baseAlignment,
  199. getBaseAlignment(id, roundUp, constraint, constraints, vstate));
  200. }
  201. if (roundUp) baseAlignment = align(baseAlignment, 16u);
  202. break;
  203. }
  204. case SpvOpTypePointer:
  205. baseAlignment = vstate.pointer_size_and_alignment();
  206. break;
  207. default:
  208. assert(0);
  209. break;
  210. }
  211. return baseAlignment;
  212. }
  213. // Returns scalar alignment of a type.
  214. uint32_t getScalarAlignment(uint32_t type_id, ValidationState_t& vstate) {
  215. const auto inst = vstate.FindDef(type_id);
  216. const auto& words = inst->words();
  217. switch (inst->opcode()) {
  218. case SpvOpTypeInt:
  219. case SpvOpTypeFloat:
  220. return words[2] / 8;
  221. case SpvOpTypeVector:
  222. case SpvOpTypeMatrix:
  223. case SpvOpTypeArray:
  224. case SpvOpTypeRuntimeArray: {
  225. const auto compositeMemberTypeId = words[2];
  226. return getScalarAlignment(compositeMemberTypeId, vstate);
  227. }
  228. case SpvOpTypeStruct: {
  229. const auto members = getStructMembers(type_id, vstate);
  230. uint32_t max_member_alignment = 1;
  231. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  232. memberIdx < numMembers; ++memberIdx) {
  233. const auto id = members[memberIdx];
  234. uint32_t member_alignment = getScalarAlignment(id, vstate);
  235. if (member_alignment > max_member_alignment) {
  236. max_member_alignment = member_alignment;
  237. }
  238. }
  239. return max_member_alignment;
  240. } break;
  241. case SpvOpTypePointer:
  242. return vstate.pointer_size_and_alignment();
  243. default:
  244. assert(0);
  245. break;
  246. }
  247. return 1;
  248. }
  249. // Returns size of a struct member. Doesn't include padding at the end of struct
  250. // or array. Assumes that in the struct case, all members have offsets.
  251. uint32_t getSize(uint32_t member_id, const LayoutConstraints& inherited,
  252. MemberConstraints& constraints, ValidationState_t& vstate) {
  253. const auto inst = vstate.FindDef(member_id);
  254. const auto& words = inst->words();
  255. switch (inst->opcode()) {
  256. case SpvOpTypeInt:
  257. case SpvOpTypeFloat:
  258. return words[2] / 8;
  259. case SpvOpTypeVector: {
  260. const auto componentId = words[2];
  261. const auto numComponents = words[3];
  262. const auto componentSize =
  263. getSize(componentId, inherited, constraints, vstate);
  264. const auto size = componentSize * numComponents;
  265. return size;
  266. }
  267. case SpvOpTypeArray: {
  268. const auto sizeInst = vstate.FindDef(words[3]);
  269. if (spvOpcodeIsSpecConstant(sizeInst->opcode())) return 0;
  270. assert(SpvOpConstant == sizeInst->opcode());
  271. const uint32_t num_elem = sizeInst->words()[3];
  272. const uint32_t elem_type = words[2];
  273. const uint32_t elem_size =
  274. getSize(elem_type, inherited, constraints, vstate);
  275. // Account for gaps due to alignments in the first N-1 elements,
  276. // then add the size of the last element.
  277. const auto size =
  278. (num_elem - 1) * GetArrayStride(member_id, vstate) + elem_size;
  279. return size;
  280. }
  281. case SpvOpTypeRuntimeArray:
  282. return 0;
  283. case SpvOpTypeMatrix: {
  284. const auto num_columns = words[3];
  285. if (inherited.majorness == kColumnMajor) {
  286. return num_columns * inherited.matrix_stride;
  287. } else {
  288. // Row major case.
  289. const auto column_type = words[2];
  290. const auto component_inst = vstate.FindDef(column_type);
  291. const auto num_rows = component_inst->words()[3];
  292. const auto scalar_elem_type = component_inst->words()[2];
  293. const uint32_t scalar_elem_size =
  294. getSize(scalar_elem_type, inherited, constraints, vstate);
  295. return (num_rows - 1) * inherited.matrix_stride +
  296. num_columns * scalar_elem_size;
  297. }
  298. }
  299. case SpvOpTypeStruct: {
  300. const auto& members = getStructMembers(member_id, vstate);
  301. if (members.empty()) return 0;
  302. const auto lastIdx = uint32_t(members.size() - 1);
  303. const auto& lastMember = members.back();
  304. uint32_t offset = 0xffffffff;
  305. // Find the offset of the last element and add the size.
  306. for (auto& decoration : vstate.id_decorations(member_id)) {
  307. if (SpvDecorationOffset == decoration.dec_type() &&
  308. decoration.struct_member_index() == (int)lastIdx) {
  309. offset = decoration.params()[0];
  310. }
  311. }
  312. // This check depends on the fact that all members have offsets. This
  313. // has been checked earlier in the flow.
  314. assert(offset != 0xffffffff);
  315. const auto& constraint = constraints[std::make_pair(lastMember, lastIdx)];
  316. return offset + getSize(lastMember, constraint, constraints, vstate);
  317. }
  318. case SpvOpTypePointer:
  319. return vstate.pointer_size_and_alignment();
  320. default:
  321. assert(0);
  322. return 0;
  323. }
  324. }
  325. // A member is defined to improperly straddle if either of the following are
  326. // true:
  327. // - It is a vector with total size less than or equal to 16 bytes, and has
  328. // Offset decorations placing its first byte at F and its last byte at L, where
  329. // floor(F / 16) != floor(L / 16).
  330. // - It is a vector with total size greater than 16 bytes and has its Offset
  331. // decorations placing its first byte at a non-integer multiple of 16.
  332. bool hasImproperStraddle(uint32_t id, uint32_t offset,
  333. const LayoutConstraints& inherited,
  334. MemberConstraints& constraints,
  335. ValidationState_t& vstate) {
  336. const auto size = getSize(id, inherited, constraints, vstate);
  337. const auto F = offset;
  338. const auto L = offset + size - 1;
  339. if (size <= 16) {
  340. if ((F >> 4) != (L >> 4)) return true;
  341. } else {
  342. if (F % 16 != 0) return true;
  343. }
  344. return false;
  345. }
  346. // Returns true if |offset| satsifies an alignment to |alignment|. In the case
  347. // of |alignment| of zero, the |offset| must also be zero.
  348. bool IsAlignedTo(uint32_t offset, uint32_t alignment) {
  349. if (alignment == 0) return offset == 0;
  350. return 0 == (offset % alignment);
  351. }
  352. // Returns SPV_SUCCESS if the given struct satisfies standard layout rules for
  353. // Block or BufferBlocks in Vulkan. Otherwise emits a diagnostic and returns
  354. // something other than SPV_SUCCESS. Matrices inherit the specified column
  355. // or row major-ness.
  356. spv_result_t checkLayout(uint32_t struct_id, const char* storage_class_str,
  357. const char* decoration_str, bool blockRules,
  358. uint32_t incoming_offset,
  359. MemberConstraints& constraints,
  360. ValidationState_t& vstate) {
  361. if (vstate.options()->skip_block_layout) return SPV_SUCCESS;
  362. // blockRules are the same as bufferBlock rules if the uniform buffer
  363. // standard layout extension is being used.
  364. if (vstate.options()->uniform_buffer_standard_layout) blockRules = false;
  365. // Relaxed layout and scalar layout can both be in effect at the same time.
  366. // For example, relaxed layout is implied by Vulkan 1.1. But scalar layout
  367. // is more permissive than relaxed layout.
  368. const bool relaxed_block_layout = vstate.IsRelaxedBlockLayout();
  369. const bool scalar_block_layout = vstate.options()->scalar_block_layout;
  370. auto fail = [&vstate, struct_id, storage_class_str, decoration_str,
  371. blockRules, relaxed_block_layout,
  372. scalar_block_layout](uint32_t member_idx) -> DiagnosticStream {
  373. DiagnosticStream ds =
  374. std::move(vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(struct_id))
  375. << "Structure id " << struct_id << " decorated as "
  376. << decoration_str << " for variable in " << storage_class_str
  377. << " storage class must follow "
  378. << (scalar_block_layout
  379. ? "scalar "
  380. : (relaxed_block_layout ? "relaxed " : "standard "))
  381. << (blockRules ? "uniform buffer" : "storage buffer")
  382. << " layout rules: member " << member_idx << " ");
  383. return ds;
  384. };
  385. const auto& members = getStructMembers(struct_id, vstate);
  386. // To check for member overlaps, we want to traverse the members in
  387. // offset order.
  388. struct MemberOffsetPair {
  389. uint32_t member;
  390. uint32_t offset;
  391. };
  392. std::vector<MemberOffsetPair> member_offsets;
  393. member_offsets.reserve(members.size());
  394. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  395. memberIdx < numMembers; memberIdx++) {
  396. uint32_t offset = 0xffffffff;
  397. for (auto& decoration : vstate.id_decorations(struct_id)) {
  398. if (decoration.struct_member_index() == (int)memberIdx) {
  399. switch (decoration.dec_type()) {
  400. case SpvDecorationOffset:
  401. offset = decoration.params()[0];
  402. break;
  403. default:
  404. break;
  405. }
  406. }
  407. }
  408. member_offsets.push_back(
  409. MemberOffsetPair{memberIdx, incoming_offset + offset});
  410. }
  411. std::stable_sort(
  412. member_offsets.begin(), member_offsets.end(),
  413. [](const MemberOffsetPair& lhs, const MemberOffsetPair& rhs) {
  414. return lhs.offset < rhs.offset;
  415. });
  416. // Now scan from lowest offest to highest offset.
  417. uint32_t nextValidOffset = 0;
  418. for (size_t ordered_member_idx = 0;
  419. ordered_member_idx < member_offsets.size(); ordered_member_idx++) {
  420. const auto& member_offset = member_offsets[ordered_member_idx];
  421. const auto memberIdx = member_offset.member;
  422. const auto offset = member_offset.offset;
  423. auto id = members[member_offset.member];
  424. const LayoutConstraints& constraint =
  425. constraints[std::make_pair(struct_id, uint32_t(memberIdx))];
  426. // Scalar layout takes precedence because it's more permissive, and implying
  427. // an alignment that divides evenly into the alignment that would otherwise
  428. // be used.
  429. const auto alignment =
  430. scalar_block_layout
  431. ? getScalarAlignment(id, vstate)
  432. : getBaseAlignment(id, blockRules, constraint, constraints, vstate);
  433. const auto inst = vstate.FindDef(id);
  434. const auto opcode = inst->opcode();
  435. const auto size = getSize(id, constraint, constraints, vstate);
  436. // Check offset.
  437. if (offset == 0xffffffff)
  438. return fail(memberIdx) << "is missing an Offset decoration";
  439. if (!scalar_block_layout && relaxed_block_layout &&
  440. opcode == SpvOpTypeVector) {
  441. // In relaxed block layout, the vector offset must be aligned to the
  442. // vector's scalar element type.
  443. const auto componentId = inst->words()[2];
  444. const auto scalar_alignment = getScalarAlignment(componentId, vstate);
  445. if (!IsAlignedTo(offset, scalar_alignment)) {
  446. return fail(memberIdx)
  447. << "at offset " << offset
  448. << " is not aligned to scalar element size " << scalar_alignment;
  449. }
  450. } else {
  451. // Without relaxed block layout, the offset must be divisible by the
  452. // alignment requirement.
  453. if (!IsAlignedTo(offset, alignment)) {
  454. return fail(memberIdx)
  455. << "at offset " << offset << " is not aligned to " << alignment;
  456. }
  457. }
  458. if (offset < nextValidOffset)
  459. return fail(memberIdx) << "at offset " << offset
  460. << " overlaps previous member ending at offset "
  461. << nextValidOffset - 1;
  462. if (!scalar_block_layout && relaxed_block_layout) {
  463. // Check improper straddle of vectors.
  464. if (SpvOpTypeVector == opcode &&
  465. hasImproperStraddle(id, offset, constraint, constraints, vstate))
  466. return fail(memberIdx)
  467. << "is an improperly straddling vector at offset " << offset;
  468. }
  469. // Check struct members recursively.
  470. spv_result_t recursive_status = SPV_SUCCESS;
  471. if (SpvOpTypeStruct == opcode &&
  472. SPV_SUCCESS != (recursive_status = checkLayout(
  473. id, storage_class_str, decoration_str, blockRules,
  474. offset, constraints, vstate)))
  475. return recursive_status;
  476. // Check matrix stride.
  477. if (SpvOpTypeMatrix == opcode) {
  478. for (auto& decoration : vstate.id_decorations(id)) {
  479. if (SpvDecorationMatrixStride == decoration.dec_type() &&
  480. !IsAlignedTo(decoration.params()[0], alignment))
  481. return fail(memberIdx)
  482. << "is a matrix with stride " << decoration.params()[0]
  483. << " not satisfying alignment to " << alignment;
  484. }
  485. }
  486. // Check arrays and runtime arrays recursively.
  487. auto array_inst = inst;
  488. auto array_alignment = alignment;
  489. while (array_inst->opcode() == SpvOpTypeArray ||
  490. array_inst->opcode() == SpvOpTypeRuntimeArray) {
  491. const auto typeId = array_inst->word(2);
  492. const auto element_inst = vstate.FindDef(typeId);
  493. // Check array stride.
  494. auto array_stride = 0;
  495. for (auto& decoration : vstate.id_decorations(array_inst->id())) {
  496. if (SpvDecorationArrayStride == decoration.dec_type()) {
  497. array_stride = decoration.params()[0];
  498. if (!IsAlignedTo(array_stride, array_alignment))
  499. return fail(memberIdx)
  500. << "contains an array with stride " << decoration.params()[0]
  501. << " not satisfying alignment to " << alignment;
  502. }
  503. }
  504. bool is_int32 = false;
  505. bool is_const = false;
  506. uint32_t num_elements = 0;
  507. if (array_inst->opcode() == SpvOpTypeArray) {
  508. std::tie(is_int32, is_const, num_elements) =
  509. vstate.EvalInt32IfConst(array_inst->word(3));
  510. }
  511. num_elements = std::max(1u, num_elements);
  512. // Check each element recursively if it is a struct. There is a
  513. // limitation to this check if the array size is a spec constant or is a
  514. // runtime array then we will only check a single element. This means
  515. // some improper straddles might be missed.
  516. for (uint32_t i = 0; i < num_elements; ++i) {
  517. uint32_t next_offset = i * array_stride + offset;
  518. if (SpvOpTypeStruct == element_inst->opcode() &&
  519. SPV_SUCCESS != (recursive_status = checkLayout(
  520. typeId, storage_class_str, decoration_str,
  521. blockRules, next_offset, constraints, vstate)))
  522. return recursive_status;
  523. // If offsets accumulate up to a 16-byte multiple stop checking since
  524. // it will just repeat.
  525. if (i > 0 && (next_offset % 16 == 0)) break;
  526. }
  527. // Proceed to the element in case it is an array.
  528. array_inst = element_inst;
  529. array_alignment = scalar_block_layout
  530. ? getScalarAlignment(array_inst->id(), vstate)
  531. : getBaseAlignment(array_inst->id(), blockRules,
  532. constraint, constraints, vstate);
  533. }
  534. nextValidOffset = offset + size;
  535. if (!scalar_block_layout && blockRules &&
  536. (SpvOpTypeArray == opcode || SpvOpTypeStruct == opcode)) {
  537. // Uniform block rules don't permit anything in the padding of a struct
  538. // or array.
  539. nextValidOffset = align(nextValidOffset, alignment);
  540. }
  541. }
  542. return SPV_SUCCESS;
  543. }
  544. // Returns true if variable or structure id has given decoration. Handles also
  545. // nested structures.
  546. bool hasDecoration(uint32_t id, SpvDecoration decoration,
  547. ValidationState_t& vstate) {
  548. for (auto& dec : vstate.id_decorations(id)) {
  549. if (decoration == dec.dec_type()) return true;
  550. }
  551. if (SpvOpTypeStruct != vstate.FindDef(id)->opcode()) {
  552. return false;
  553. }
  554. for (auto member_id : getStructMembers(id, SpvOpTypeStruct, vstate)) {
  555. if (hasDecoration(member_id, decoration, vstate)) {
  556. return true;
  557. }
  558. }
  559. return false;
  560. }
  561. // Returns true if all ids of given type have a specified decoration.
  562. bool checkForRequiredDecoration(uint32_t struct_id, SpvDecoration decoration,
  563. SpvOp type, ValidationState_t& vstate) {
  564. const auto& members = getStructMembers(struct_id, vstate);
  565. for (size_t memberIdx = 0; memberIdx < members.size(); memberIdx++) {
  566. const auto id = members[memberIdx];
  567. if (type != vstate.FindDef(id)->opcode()) continue;
  568. bool found = false;
  569. for (auto& dec : vstate.id_decorations(id)) {
  570. if (decoration == dec.dec_type()) found = true;
  571. }
  572. for (auto& dec : vstate.id_decorations(struct_id)) {
  573. if (decoration == dec.dec_type() &&
  574. (int)memberIdx == dec.struct_member_index()) {
  575. found = true;
  576. }
  577. }
  578. if (!found) {
  579. return false;
  580. }
  581. }
  582. for (auto id : getStructMembers(struct_id, SpvOpTypeStruct, vstate)) {
  583. if (!checkForRequiredDecoration(id, decoration, type, vstate)) {
  584. return false;
  585. }
  586. }
  587. return true;
  588. }
  589. spv_result_t CheckLinkageAttrOfFunctions(ValidationState_t& vstate) {
  590. for (const auto& function : vstate.functions()) {
  591. if (function.block_count() == 0u) {
  592. // A function declaration (an OpFunction with no basic blocks), must have
  593. // a Linkage Attributes Decoration with the Import Linkage Type.
  594. if (!hasImportLinkageAttribute(function.id(), vstate)) {
  595. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  596. vstate.FindDef(function.id()))
  597. << "Function declaration (id " << function.id()
  598. << ") must have a LinkageAttributes decoration with the Import "
  599. "Linkage type.";
  600. }
  601. } else {
  602. if (hasImportLinkageAttribute(function.id(), vstate)) {
  603. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  604. vstate.FindDef(function.id()))
  605. << "Function definition (id " << function.id()
  606. << ") may not be decorated with Import Linkage type.";
  607. }
  608. }
  609. }
  610. return SPV_SUCCESS;
  611. }
  612. // Checks whether an imported variable is initialized by this module.
  613. spv_result_t CheckImportedVariableInitialization(ValidationState_t& vstate) {
  614. // According the SPIR-V Spec 2.16.1, it is illegal to initialize an imported
  615. // variable. This means that a module-scope OpVariable with initialization
  616. // value cannot be marked with the Import Linkage Type (import type id = 1).
  617. for (auto global_var_id : vstate.global_vars()) {
  618. // Initializer <id> is an optional argument for OpVariable. If initializer
  619. // <id> is present, the instruction will have 5 words.
  620. auto variable_instr = vstate.FindDef(global_var_id);
  621. if (variable_instr->words().size() == 5u &&
  622. hasImportLinkageAttribute(global_var_id, vstate)) {
  623. return vstate.diag(SPV_ERROR_INVALID_ID, variable_instr)
  624. << "A module-scope OpVariable with initialization value "
  625. "cannot be marked with the Import Linkage Type.";
  626. }
  627. }
  628. return SPV_SUCCESS;
  629. }
  630. // Checks whether a builtin variable is valid.
  631. spv_result_t CheckBuiltInVariable(uint32_t var_id, ValidationState_t& vstate) {
  632. const auto& decorations = vstate.id_decorations(var_id);
  633. for (const auto& d : decorations) {
  634. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  635. if (d.dec_type() == SpvDecorationLocation ||
  636. d.dec_type() == SpvDecorationComponent) {
  637. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  638. << "A BuiltIn variable (id " << var_id
  639. << ") cannot have any Location or Component decorations";
  640. }
  641. }
  642. }
  643. return SPV_SUCCESS;
  644. }
  645. // Checks whether proper decorations have been appied to the entry points.
  646. spv_result_t CheckDecorationsOfEntryPoints(ValidationState_t& vstate) {
  647. for (uint32_t entry_point : vstate.entry_points()) {
  648. const auto& descs = vstate.entry_point_descriptions(entry_point);
  649. int num_builtin_inputs = 0;
  650. int num_builtin_outputs = 0;
  651. for (const auto& desc : descs) {
  652. std::unordered_set<Instruction*> seen_vars;
  653. for (auto interface : desc.interfaces) {
  654. Instruction* var_instr = vstate.FindDef(interface);
  655. if (!var_instr || SpvOpVariable != var_instr->opcode()) {
  656. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  657. << "Interfaces passed to OpEntryPoint must be of type "
  658. "OpTypeVariable. Found Op"
  659. << spvOpcodeString(var_instr->opcode()) << ".";
  660. }
  661. const SpvStorageClass storage_class =
  662. var_instr->GetOperandAs<SpvStorageClass>(2);
  663. if (vstate.version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
  664. // Starting in 1.4, OpEntryPoint must list all global variables
  665. // it statically uses and those interfaces must be unique.
  666. if (storage_class == SpvStorageClassFunction) {
  667. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  668. << "OpEntryPoint interfaces should only list global "
  669. "variables";
  670. }
  671. if (!seen_vars.insert(var_instr).second) {
  672. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  673. << "Non-unique OpEntryPoint interface "
  674. << vstate.getIdName(interface) << " is disallowed";
  675. }
  676. } else {
  677. if (storage_class != SpvStorageClassInput &&
  678. storage_class != SpvStorageClassOutput) {
  679. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  680. << "OpEntryPoint interfaces must be OpVariables with "
  681. "Storage Class of Input(1) or Output(3). Found Storage "
  682. "Class "
  683. << storage_class << " for Entry Point id " << entry_point
  684. << ".";
  685. }
  686. }
  687. const uint32_t ptr_id = var_instr->word(1);
  688. Instruction* ptr_instr = vstate.FindDef(ptr_id);
  689. // It is guaranteed (by validator ID checks) that ptr_instr is
  690. // OpTypePointer. Word 3 of this instruction is the type being pointed
  691. // to.
  692. const uint32_t type_id = ptr_instr->word(3);
  693. Instruction* type_instr = vstate.FindDef(type_id);
  694. if (type_instr && SpvOpTypeStruct == type_instr->opcode() &&
  695. isBuiltInStruct(type_id, vstate)) {
  696. if (storage_class == SpvStorageClassInput) ++num_builtin_inputs;
  697. if (storage_class == SpvStorageClassOutput) ++num_builtin_outputs;
  698. if (num_builtin_inputs > 1 || num_builtin_outputs > 1) break;
  699. if (auto error = CheckBuiltInVariable(interface, vstate))
  700. return error;
  701. } else if (isBuiltInVar(interface, vstate)) {
  702. if (auto error = CheckBuiltInVariable(interface, vstate))
  703. return error;
  704. }
  705. }
  706. if (num_builtin_inputs > 1 || num_builtin_outputs > 1) {
  707. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  708. vstate.FindDef(entry_point))
  709. << "There must be at most one object per Storage Class that can "
  710. "contain a structure type containing members decorated with "
  711. "BuiltIn, consumed per entry-point. Entry Point id "
  712. << entry_point << " does not meet this requirement.";
  713. }
  714. // The LinkageAttributes Decoration cannot be applied to functions
  715. // targeted by an OpEntryPoint instruction
  716. for (auto& decoration : vstate.id_decorations(entry_point)) {
  717. if (SpvDecorationLinkageAttributes == decoration.dec_type()) {
  718. const char* linkage_name =
  719. reinterpret_cast<const char*>(&decoration.params()[0]);
  720. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  721. vstate.FindDef(entry_point))
  722. << "The LinkageAttributes Decoration (Linkage name: "
  723. << linkage_name << ") cannot be applied to function id "
  724. << entry_point
  725. << " because it is targeted by an OpEntryPoint instruction.";
  726. }
  727. }
  728. }
  729. }
  730. return SPV_SUCCESS;
  731. }
  732. // Load |constraints| with all the member constraints for structs contained
  733. // within the given array type.
  734. void ComputeMemberConstraintsForArray(MemberConstraints* constraints,
  735. uint32_t array_id,
  736. const LayoutConstraints& inherited,
  737. ValidationState_t& vstate);
  738. // Load |constraints| with all the member constraints for the given struct,
  739. // and all its contained structs.
  740. void ComputeMemberConstraintsForStruct(MemberConstraints* constraints,
  741. uint32_t struct_id,
  742. const LayoutConstraints& inherited,
  743. ValidationState_t& vstate) {
  744. assert(constraints);
  745. const auto& members = getStructMembers(struct_id, vstate);
  746. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  747. memberIdx < numMembers; memberIdx++) {
  748. LayoutConstraints& constraint =
  749. (*constraints)[std::make_pair(struct_id, memberIdx)];
  750. constraint = inherited;
  751. for (auto& decoration : vstate.id_decorations(struct_id)) {
  752. if (decoration.struct_member_index() == (int)memberIdx) {
  753. switch (decoration.dec_type()) {
  754. case SpvDecorationRowMajor:
  755. constraint.majorness = kRowMajor;
  756. break;
  757. case SpvDecorationColMajor:
  758. constraint.majorness = kColumnMajor;
  759. break;
  760. case SpvDecorationMatrixStride:
  761. constraint.matrix_stride = decoration.params()[0];
  762. break;
  763. default:
  764. break;
  765. }
  766. }
  767. }
  768. // Now recurse
  769. auto member_type_id = members[memberIdx];
  770. const auto member_type_inst = vstate.FindDef(member_type_id);
  771. const auto opcode = member_type_inst->opcode();
  772. switch (opcode) {
  773. case SpvOpTypeArray:
  774. case SpvOpTypeRuntimeArray:
  775. ComputeMemberConstraintsForArray(constraints, member_type_id, inherited,
  776. vstate);
  777. break;
  778. case SpvOpTypeStruct:
  779. ComputeMemberConstraintsForStruct(constraints, member_type_id,
  780. inherited, vstate);
  781. break;
  782. default:
  783. break;
  784. }
  785. }
  786. }
  787. void ComputeMemberConstraintsForArray(MemberConstraints* constraints,
  788. uint32_t array_id,
  789. const LayoutConstraints& inherited,
  790. ValidationState_t& vstate) {
  791. assert(constraints);
  792. auto elem_type_id = vstate.FindDef(array_id)->words()[2];
  793. const auto elem_type_inst = vstate.FindDef(elem_type_id);
  794. const auto opcode = elem_type_inst->opcode();
  795. switch (opcode) {
  796. case SpvOpTypeArray:
  797. case SpvOpTypeRuntimeArray:
  798. ComputeMemberConstraintsForArray(constraints, elem_type_id, inherited,
  799. vstate);
  800. break;
  801. case SpvOpTypeStruct:
  802. ComputeMemberConstraintsForStruct(constraints, elem_type_id, inherited,
  803. vstate);
  804. break;
  805. default:
  806. break;
  807. }
  808. }
  809. spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) {
  810. // Set of entry points that are known to use a push constant.
  811. std::unordered_set<uint32_t> uses_push_constant;
  812. for (const auto& inst : vstate.ordered_instructions()) {
  813. const auto& words = inst.words();
  814. if (SpvOpVariable == inst.opcode()) {
  815. const auto var_id = inst.id();
  816. // For storage class / decoration combinations, see Vulkan 14.5.4 "Offset
  817. // and Stride Assignment".
  818. const auto storageClass = words[3];
  819. const bool uniform = storageClass == SpvStorageClassUniform;
  820. const bool uniform_constant =
  821. storageClass == SpvStorageClassUniformConstant;
  822. const bool push_constant = storageClass == SpvStorageClassPushConstant;
  823. const bool storage_buffer = storageClass == SpvStorageClassStorageBuffer;
  824. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  825. // Vulkan 14.5.1: There must be no more than one PushConstant block
  826. // per entry point.
  827. if (push_constant) {
  828. auto entry_points = vstate.EntryPointReferences(var_id);
  829. for (auto ep_id : entry_points) {
  830. const bool already_used = !uses_push_constant.insert(ep_id).second;
  831. if (already_used) {
  832. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  833. << "Entry point id '" << ep_id
  834. << "' uses more than one PushConstant interface.\n"
  835. << "From Vulkan spec, section 14.5.1:\n"
  836. << "There must be no more than one push constant block "
  837. << "statically used per shader entry point.";
  838. }
  839. }
  840. }
  841. // Vulkan 14.5.2: Check DescriptorSet and Binding decoration for
  842. // UniformConstant which cannot be a struct.
  843. if (uniform_constant) {
  844. auto entry_points = vstate.EntryPointReferences(var_id);
  845. if (!entry_points.empty() &&
  846. !hasDecoration(var_id, SpvDecorationDescriptorSet, vstate)) {
  847. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  848. << "UniformConstant id '" << var_id
  849. << "' is missing DescriptorSet decoration.\n"
  850. << "From Vulkan spec, section 14.5.2:\n"
  851. << "These variables must have DescriptorSet and Binding "
  852. "decorations specified";
  853. }
  854. if (!entry_points.empty() &&
  855. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  856. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  857. << "UniformConstant id '" << var_id
  858. << "' is missing Binding decoration.\n"
  859. << "From Vulkan spec, section 14.5.2:\n"
  860. << "These variables must have DescriptorSet and Binding "
  861. "decorations specified";
  862. }
  863. }
  864. }
  865. if (spvIsOpenGLEnv(vstate.context()->target_env)) {
  866. bool has_block = hasDecoration(var_id, SpvDecorationBlock, vstate);
  867. bool has_buffer_block =
  868. hasDecoration(var_id, SpvDecorationBufferBlock, vstate);
  869. if ((uniform && (has_block || has_buffer_block)) ||
  870. (storage_buffer && has_block)) {
  871. auto entry_points = vstate.EntryPointReferences(var_id);
  872. if (!entry_points.empty() &&
  873. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  874. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  875. << (uniform ? "Uniform" : "Storage Buffer") << " id '"
  876. << var_id << "' is missing Binding decoration.\n"
  877. << "From ARB_gl_spirv extension:\n"
  878. << "Uniform and shader storage block variables must "
  879. << "also be decorated with a *Binding*.";
  880. }
  881. }
  882. }
  883. const bool phys_storage_buffer =
  884. storageClass == SpvStorageClassPhysicalStorageBufferEXT;
  885. if (uniform || push_constant || storage_buffer || phys_storage_buffer) {
  886. const auto ptrInst = vstate.FindDef(words[1]);
  887. assert(SpvOpTypePointer == ptrInst->opcode());
  888. auto id = ptrInst->words()[3];
  889. auto id_inst = vstate.FindDef(id);
  890. // Jump through one level of arraying.
  891. if (id_inst->opcode() == SpvOpTypeArray ||
  892. id_inst->opcode() == SpvOpTypeRuntimeArray) {
  893. id = id_inst->GetOperandAs<uint32_t>(1u);
  894. id_inst = vstate.FindDef(id);
  895. }
  896. // Struct requirement is checked on variables so just move on here.
  897. if (SpvOpTypeStruct != id_inst->opcode()) continue;
  898. MemberConstraints constraints;
  899. ComputeMemberConstraintsForStruct(&constraints, id, LayoutConstraints(),
  900. vstate);
  901. // Prepare for messages
  902. const char* sc_str =
  903. uniform ? "Uniform"
  904. : (push_constant ? "PushConstant" : "StorageBuffer");
  905. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  906. const bool block = hasDecoration(id, SpvDecorationBlock, vstate);
  907. const bool buffer_block =
  908. hasDecoration(id, SpvDecorationBufferBlock, vstate);
  909. if (storage_buffer && buffer_block) {
  910. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  911. << "Storage buffer id '" << var_id
  912. << " In Vulkan, BufferBlock is disallowed on variables in "
  913. "the StorageBuffer storage class";
  914. }
  915. // Vulkan 14.5.1/2: Check Block decoration for PushConstant, Uniform
  916. // and StorageBuffer variables. Uniform can also use BufferBlock.
  917. if (push_constant && !block) {
  918. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  919. << "PushConstant id '" << id
  920. << "' is missing Block decoration.\n"
  921. << "From Vulkan spec, section 14.5.1:\n"
  922. << "Such variables must be identified with a Block "
  923. "decoration";
  924. }
  925. if (storage_buffer && !block) {
  926. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  927. << "StorageBuffer id '" << id
  928. << "' is missing Block decoration.\n"
  929. << "From Vulkan spec, section 14.5.2:\n"
  930. << "Such variables must be identified with a Block "
  931. "decoration";
  932. }
  933. if (uniform && !block && !buffer_block) {
  934. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  935. << "Uniform id '" << id
  936. << "' is missing Block or BufferBlock decoration.\n"
  937. << "From Vulkan spec, section 14.5.2:\n"
  938. << "Such variables must be identified with a Block or "
  939. "BufferBlock decoration";
  940. }
  941. // Vulkan 14.5.2: Check DescriptorSet and Binding decoration for
  942. // Uniform and StorageBuffer variables.
  943. if (uniform || storage_buffer) {
  944. auto entry_points = vstate.EntryPointReferences(var_id);
  945. if (!entry_points.empty() &&
  946. !hasDecoration(var_id, SpvDecorationDescriptorSet, vstate)) {
  947. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  948. << sc_str << " id '" << var_id
  949. << "' is missing DescriptorSet decoration.\n"
  950. << "From Vulkan spec, section 14.5.2:\n"
  951. << "These variables must have DescriptorSet and Binding "
  952. "decorations specified";
  953. }
  954. if (!entry_points.empty() &&
  955. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  956. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  957. << sc_str << " id '" << var_id
  958. << "' is missing Binding decoration.\n"
  959. << "From Vulkan spec, section 14.5.2:\n"
  960. << "These variables must have DescriptorSet and Binding "
  961. "decorations specified";
  962. }
  963. }
  964. }
  965. for (const auto& dec : vstate.id_decorations(id)) {
  966. const bool blockDeco = SpvDecorationBlock == dec.dec_type();
  967. const bool bufferDeco = SpvDecorationBufferBlock == dec.dec_type();
  968. const bool blockRules = uniform && blockDeco;
  969. const bool bufferRules =
  970. (uniform && bufferDeco) || (push_constant && blockDeco) ||
  971. ((storage_buffer || phys_storage_buffer) && blockDeco);
  972. if (uniform && blockDeco) {
  973. vstate.RegisterPointerToUniformBlock(ptrInst->id());
  974. vstate.RegisterStructForUniformBlock(id);
  975. }
  976. if ((uniform && bufferDeco) ||
  977. ((storage_buffer || phys_storage_buffer) && blockDeco)) {
  978. vstate.RegisterPointerToStorageBuffer(ptrInst->id());
  979. vstate.RegisterStructForStorageBuffer(id);
  980. }
  981. if (blockRules || bufferRules) {
  982. const char* deco_str = blockDeco ? "Block" : "BufferBlock";
  983. spv_result_t recursive_status = SPV_SUCCESS;
  984. if (isMissingOffsetInStruct(id, vstate)) {
  985. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  986. << "Structure id " << id << " decorated as " << deco_str
  987. << " must be explicitly laid out with Offset "
  988. "decorations.";
  989. } else if (hasDecoration(id, SpvDecorationGLSLShared, vstate)) {
  990. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  991. << "Structure id " << id << " decorated as " << deco_str
  992. << " must not use GLSLShared decoration.";
  993. } else if (hasDecoration(id, SpvDecorationGLSLPacked, vstate)) {
  994. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  995. << "Structure id " << id << " decorated as " << deco_str
  996. << " must not use GLSLPacked decoration.";
  997. } else if (!checkForRequiredDecoration(id, SpvDecorationArrayStride,
  998. SpvOpTypeArray, vstate)) {
  999. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1000. << "Structure id " << id << " decorated as " << deco_str
  1001. << " must be explicitly laid out with ArrayStride "
  1002. "decorations.";
  1003. } else if (!checkForRequiredDecoration(id,
  1004. SpvDecorationMatrixStride,
  1005. SpvOpTypeMatrix, vstate)) {
  1006. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1007. << "Structure id " << id << " decorated as " << deco_str
  1008. << " must be explicitly laid out with MatrixStride "
  1009. "decorations.";
  1010. } else if (blockRules &&
  1011. (SPV_SUCCESS != (recursive_status = checkLayout(
  1012. id, sc_str, deco_str, true, 0,
  1013. constraints, vstate)))) {
  1014. return recursive_status;
  1015. } else if (bufferRules &&
  1016. (SPV_SUCCESS != (recursive_status = checkLayout(
  1017. id, sc_str, deco_str, false, 0,
  1018. constraints, vstate)))) {
  1019. return recursive_status;
  1020. }
  1021. }
  1022. }
  1023. }
  1024. }
  1025. }
  1026. return SPV_SUCCESS;
  1027. }
  1028. // Returns true if |decoration| cannot be applied to the same id more than once.
  1029. bool AtMostOncePerId(SpvDecoration decoration) {
  1030. return decoration == SpvDecorationArrayStride;
  1031. }
  1032. // Returns true if |decoration| cannot be applied to the same member more than
  1033. // once.
  1034. bool AtMostOncePerMember(SpvDecoration decoration) {
  1035. switch (decoration) {
  1036. case SpvDecorationOffset:
  1037. case SpvDecorationMatrixStride:
  1038. case SpvDecorationRowMajor:
  1039. case SpvDecorationColMajor:
  1040. return true;
  1041. default:
  1042. return false;
  1043. }
  1044. }
  1045. // Returns the string name for |decoration|.
  1046. const char* GetDecorationName(SpvDecoration decoration) {
  1047. switch (decoration) {
  1048. case SpvDecorationAliased:
  1049. return "Aliased";
  1050. case SpvDecorationRestrict:
  1051. return "Restrict";
  1052. case SpvDecorationArrayStride:
  1053. return "ArrayStride";
  1054. case SpvDecorationOffset:
  1055. return "Offset";
  1056. case SpvDecorationMatrixStride:
  1057. return "MatrixStride";
  1058. case SpvDecorationRowMajor:
  1059. return "RowMajor";
  1060. case SpvDecorationColMajor:
  1061. return "ColMajor";
  1062. case SpvDecorationBlock:
  1063. return "Block";
  1064. case SpvDecorationBufferBlock:
  1065. return "BufferBlock";
  1066. default:
  1067. return "";
  1068. }
  1069. }
  1070. spv_result_t CheckDecorationsCompatibility(ValidationState_t& vstate) {
  1071. using PerIDKey = std::tuple<SpvDecoration, uint32_t>;
  1072. using PerMemberKey = std::tuple<SpvDecoration, uint32_t, uint32_t>;
  1073. // An Array of pairs where the decorations in the pair cannot both be applied
  1074. // to the same id.
  1075. static const SpvDecoration mutually_exclusive_per_id[][2] = {
  1076. {SpvDecorationBlock, SpvDecorationBufferBlock},
  1077. {SpvDecorationRestrict, SpvDecorationAliased}};
  1078. static const auto num_mutually_exclusive_per_id_pairs =
  1079. sizeof(mutually_exclusive_per_id) / (2 * sizeof(SpvDecoration));
  1080. // An Array of pairs where the decorations in the pair cannot both be applied
  1081. // to the same member.
  1082. static const SpvDecoration mutually_exclusive_per_member[][2] = {
  1083. {SpvDecorationRowMajor, SpvDecorationColMajor}};
  1084. static const auto num_mutually_exclusive_per_mem_pairs =
  1085. sizeof(mutually_exclusive_per_member) / (2 * sizeof(SpvDecoration));
  1086. std::set<PerIDKey> seen_per_id;
  1087. std::set<PerMemberKey> seen_per_member;
  1088. for (const auto& inst : vstate.ordered_instructions()) {
  1089. const auto& words = inst.words();
  1090. if (SpvOpDecorate == inst.opcode()) {
  1091. const auto id = words[1];
  1092. const auto dec_type = static_cast<SpvDecoration>(words[2]);
  1093. const auto k = PerIDKey(dec_type, id);
  1094. const auto already_used = !seen_per_id.insert(k).second;
  1095. if (already_used && AtMostOncePerId(dec_type)) {
  1096. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1097. << "ID '" << id << "' decorated with "
  1098. << GetDecorationName(dec_type)
  1099. << " multiple times is not allowed.";
  1100. }
  1101. // Verify certain mutually exclusive decorations are not both applied on
  1102. // an ID.
  1103. for (uint32_t pair_idx = 0;
  1104. pair_idx < num_mutually_exclusive_per_id_pairs; ++pair_idx) {
  1105. SpvDecoration excl_dec_type = SpvDecorationMax;
  1106. if (mutually_exclusive_per_id[pair_idx][0] == dec_type) {
  1107. excl_dec_type = mutually_exclusive_per_id[pair_idx][1];
  1108. } else if (mutually_exclusive_per_id[pair_idx][1] == dec_type) {
  1109. excl_dec_type = mutually_exclusive_per_id[pair_idx][0];
  1110. } else {
  1111. continue;
  1112. }
  1113. const auto excl_k = PerIDKey(excl_dec_type, id);
  1114. if (seen_per_id.find(excl_k) != seen_per_id.end()) {
  1115. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1116. << "ID '" << id << "' decorated with both "
  1117. << GetDecorationName(dec_type) << " and "
  1118. << GetDecorationName(excl_dec_type) << " is not allowed.";
  1119. }
  1120. }
  1121. } else if (SpvOpMemberDecorate == inst.opcode()) {
  1122. const auto id = words[1];
  1123. const auto member_id = words[2];
  1124. const auto dec_type = static_cast<SpvDecoration>(words[3]);
  1125. const auto k = PerMemberKey(dec_type, id, member_id);
  1126. const auto already_used = !seen_per_member.insert(k).second;
  1127. if (already_used && AtMostOncePerMember(dec_type)) {
  1128. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1129. << "ID '" << id << "', member '" << member_id
  1130. << "' decorated with " << GetDecorationName(dec_type)
  1131. << " multiple times is not allowed.";
  1132. }
  1133. // Verify certain mutually exclusive decorations are not both applied on
  1134. // a (ID, member) tuple.
  1135. for (uint32_t pair_idx = 0;
  1136. pair_idx < num_mutually_exclusive_per_mem_pairs; ++pair_idx) {
  1137. SpvDecoration excl_dec_type = SpvDecorationMax;
  1138. if (mutually_exclusive_per_member[pair_idx][0] == dec_type) {
  1139. excl_dec_type = mutually_exclusive_per_member[pair_idx][1];
  1140. } else if (mutually_exclusive_per_member[pair_idx][1] == dec_type) {
  1141. excl_dec_type = mutually_exclusive_per_member[pair_idx][0];
  1142. } else {
  1143. continue;
  1144. }
  1145. const auto excl_k = PerMemberKey(excl_dec_type, id, member_id);
  1146. if (seen_per_member.find(excl_k) != seen_per_member.end()) {
  1147. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1148. << "ID '" << id << "', member '" << member_id
  1149. << "' decorated with both " << GetDecorationName(dec_type)
  1150. << " and " << GetDecorationName(excl_dec_type)
  1151. << " is not allowed.";
  1152. }
  1153. }
  1154. }
  1155. }
  1156. return SPV_SUCCESS;
  1157. }
  1158. spv_result_t CheckVulkanMemoryModelDeprecatedDecorations(
  1159. ValidationState_t& vstate) {
  1160. if (vstate.memory_model() != SpvMemoryModelVulkanKHR) return SPV_SUCCESS;
  1161. std::string msg;
  1162. std::ostringstream str(msg);
  1163. for (const auto& def : vstate.all_definitions()) {
  1164. const auto inst = def.second;
  1165. const auto id = inst->id();
  1166. for (const auto& dec : vstate.id_decorations(id)) {
  1167. const auto member = dec.struct_member_index();
  1168. if (dec.dec_type() == SpvDecorationCoherent ||
  1169. dec.dec_type() == SpvDecorationVolatile) {
  1170. str << (dec.dec_type() == SpvDecorationCoherent ? "Coherent"
  1171. : "Volatile");
  1172. str << " decoration targeting " << vstate.getIdName(id);
  1173. if (member != Decoration::kInvalidMember) {
  1174. str << " (member index " << member << ")";
  1175. }
  1176. str << " is banned when using the Vulkan memory model.";
  1177. return vstate.diag(SPV_ERROR_INVALID_ID, inst) << str.str();
  1178. }
  1179. }
  1180. }
  1181. return SPV_SUCCESS;
  1182. }
  1183. // Returns SPV_SUCCESS if validation rules are satisfied for FPRoundingMode
  1184. // decorations. Otherwise emits a diagnostic and returns something other than
  1185. // SPV_SUCCESS.
  1186. spv_result_t CheckFPRoundingModeForShaders(ValidationState_t& vstate,
  1187. const Instruction& inst) {
  1188. // Validates width-only conversion instruction for floating-point object
  1189. // i.e., OpFConvert
  1190. if (inst.opcode() != SpvOpFConvert) {
  1191. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1192. << "FPRoundingMode decoration can be applied only to a "
  1193. "width-only conversion instruction for floating-point "
  1194. "object.";
  1195. }
  1196. // Validates Object operand of an OpStore
  1197. for (const auto& use : inst.uses()) {
  1198. const auto store = use.first;
  1199. if (store->opcode() == SpvOpFConvert) continue;
  1200. if (spvOpcodeIsDebug(store->opcode())) continue;
  1201. if (spvOpcodeIsDecoration(store->opcode())) continue;
  1202. if (store->opcode() != SpvOpStore) {
  1203. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1204. << "FPRoundingMode decoration can be applied only to the "
  1205. "Object operand of an OpStore.";
  1206. }
  1207. if (use.second != 2) {
  1208. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1209. << "FPRoundingMode decoration can be applied only to the "
  1210. "Object operand of an OpStore.";
  1211. }
  1212. const auto ptr_inst = vstate.FindDef(store->GetOperandAs<uint32_t>(0));
  1213. const auto ptr_type = vstate.FindDef(ptr_inst->GetOperandAs<uint32_t>(0));
  1214. const auto half_float_id = ptr_type->GetOperandAs<uint32_t>(2);
  1215. if (!vstate.IsFloatScalarOrVectorType(half_float_id) ||
  1216. vstate.GetBitWidth(half_float_id) != 16) {
  1217. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1218. << "FPRoundingMode decoration can be applied only to the "
  1219. "Object operand of an OpStore storing through a pointer "
  1220. "to "
  1221. "a 16-bit floating-point scalar or vector object.";
  1222. }
  1223. // Validates storage class of the pointer to the OpStore
  1224. const auto storage = ptr_type->GetOperandAs<uint32_t>(1);
  1225. if (storage != SpvStorageClassStorageBuffer &&
  1226. storage != SpvStorageClassUniform &&
  1227. storage != SpvStorageClassPushConstant &&
  1228. storage != SpvStorageClassInput && storage != SpvStorageClassOutput &&
  1229. storage != SpvStorageClassPhysicalStorageBufferEXT) {
  1230. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1231. << "FPRoundingMode decoration can be applied only to the "
  1232. "Object operand of an OpStore in the StorageBuffer, "
  1233. "PhysicalStorageBufferEXT, Uniform, PushConstant, Input, or "
  1234. "Output Storage Classes.";
  1235. }
  1236. }
  1237. return SPV_SUCCESS;
  1238. }
  1239. // Returns SPV_SUCCESS if validation rules are satisfied for the NonWritable
  1240. // decoration. Otherwise emits a diagnostic and returns something other than
  1241. // SPV_SUCCESS. The |inst| parameter is the object being decorated. This must
  1242. // be called after TypePass and AnnotateCheckDecorationsOfBuffers are called.
  1243. spv_result_t CheckNonWritableDecoration(ValidationState_t& vstate,
  1244. const Instruction& inst,
  1245. const Decoration& decoration) {
  1246. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1247. if (decoration.struct_member_index() == Decoration::kInvalidMember) {
  1248. // The target must be a memory object declaration.
  1249. // First, it must be a variable or function parameter.
  1250. const auto opcode = inst.opcode();
  1251. const auto type_id = inst.type_id();
  1252. if (opcode != SpvOpVariable && opcode != SpvOpFunctionParameter) {
  1253. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1254. << "Target of NonWritable decoration must be a memory object "
  1255. "declaration (a variable or a function parameter)";
  1256. }
  1257. const auto var_storage_class = opcode == SpvOpVariable
  1258. ? inst.GetOperandAs<SpvStorageClass>(2)
  1259. : SpvStorageClassMax;
  1260. if ((var_storage_class == SpvStorageClassFunction ||
  1261. var_storage_class == SpvStorageClassPrivate) &&
  1262. vstate.features().nonwritable_var_in_function_or_private) {
  1263. // New permitted feature in SPIR-V 1.4.
  1264. } else if (
  1265. // It may point to a UBO, SSBO, or storage image.
  1266. vstate.IsPointerToUniformBlock(type_id) ||
  1267. vstate.IsPointerToStorageBuffer(type_id) ||
  1268. vstate.IsPointerToStorageImage(type_id)) {
  1269. } else {
  1270. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1271. << "Target of NonWritable decoration is invalid: must point to a "
  1272. "storage image, uniform block, "
  1273. << (vstate.features().nonwritable_var_in_function_or_private
  1274. ? "storage buffer, or variable in Private or Function "
  1275. "storage class"
  1276. : "or storage buffer");
  1277. }
  1278. }
  1279. return SPV_SUCCESS;
  1280. }
  1281. // Returns SPV_SUCCESS if validation rules are satisfied for Uniform or
  1282. // UniformId decorations. Otherwise emits a diagnostic and returns something
  1283. // other than SPV_SUCCESS. Assumes each decoration on a group has been
  1284. // propagated down to the group members. The |inst| parameter is the object
  1285. // being decorated.
  1286. spv_result_t CheckUniformDecoration(ValidationState_t& vstate,
  1287. const Instruction& inst,
  1288. const Decoration& decoration) {
  1289. const char* const dec_name =
  1290. decoration.dec_type() == SpvDecorationUniform ? "Uniform" : "UniformId";
  1291. // Uniform or UniformId must decorate an "object"
  1292. // - has a result ID
  1293. // - is an instantiation of a non-void type. So it has a type ID, and that
  1294. // type is not void.
  1295. // We already know the result ID is non-zero.
  1296. if (inst.type_id() == 0) {
  1297. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1298. << dec_name << " decoration applied to a non-object";
  1299. }
  1300. if (Instruction* type_inst = vstate.FindDef(inst.type_id())) {
  1301. if (type_inst->opcode() == SpvOpTypeVoid) {
  1302. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1303. << dec_name << " decoration applied to a value with void type";
  1304. }
  1305. } else {
  1306. // We might never get here because this would have been rejected earlier in
  1307. // the flow.
  1308. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1309. << dec_name << " decoration applied to an object with invalid type";
  1310. }
  1311. // Use of Uniform with OpDecorate is checked elsewhere.
  1312. // Use of UniformId with OpDecorateId is checked elsewhere.
  1313. if (decoration.dec_type() == SpvDecorationUniformId) {
  1314. assert(decoration.params().size() == 1 &&
  1315. "Grammar ensures UniformId has one parameter");
  1316. // The scope id is an execution scope.
  1317. if (auto error =
  1318. ValidateExecutionScope(vstate, &inst, decoration.params()[0]))
  1319. return error;
  1320. }
  1321. return SPV_SUCCESS;
  1322. }
  1323. // Returns SPV_SUCCESS if validation rules are satisfied for NoSignedWrap or
  1324. // NoUnsignedWrap decorations. Otherwise emits a diagnostic and returns
  1325. // something other than SPV_SUCCESS. Assumes each decoration on a group has been
  1326. // propagated down to the group members.
  1327. spv_result_t CheckIntegerWrapDecoration(ValidationState_t& vstate,
  1328. const Instruction& inst,
  1329. const Decoration& decoration) {
  1330. switch (inst.opcode()) {
  1331. case SpvOpIAdd:
  1332. case SpvOpISub:
  1333. case SpvOpIMul:
  1334. case SpvOpShiftLeftLogical:
  1335. case SpvOpSNegate:
  1336. return SPV_SUCCESS;
  1337. case SpvOpExtInst:
  1338. // TODO(dneto): Only certain extended instructions allow these
  1339. // decorations. For now allow anything.
  1340. return SPV_SUCCESS;
  1341. default:
  1342. break;
  1343. }
  1344. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1345. << (decoration.dec_type() == SpvDecorationNoSignedWrap
  1346. ? "NoSignedWrap"
  1347. : "NoUnsignedWrap")
  1348. << " decoration may not be applied to "
  1349. << spvOpcodeString(inst.opcode());
  1350. }
  1351. // Returns SPV_SUCCESS if validation rules are satisfied for the Component
  1352. // decoration. Otherwise emits a diagnostic and returns something other than
  1353. // SPV_SUCCESS.
  1354. spv_result_t CheckComponentDecoration(ValidationState_t& vstate,
  1355. const Instruction& inst,
  1356. const Decoration& decoration) {
  1357. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1358. uint32_t type_id;
  1359. if (decoration.struct_member_index() == Decoration::kInvalidMember) {
  1360. // The target must be a memory object declaration.
  1361. const auto opcode = inst.opcode();
  1362. if (opcode != SpvOpVariable && opcode != SpvOpFunctionParameter) {
  1363. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1364. << "Target of Component decoration must be a memory object "
  1365. "declaration (a variable or a function parameter)";
  1366. }
  1367. // Only valid for the Input and Output Storage Classes.
  1368. const auto storage_class = opcode == SpvOpVariable
  1369. ? inst.GetOperandAs<SpvStorageClass>(2)
  1370. : SpvStorageClassMax;
  1371. if (storage_class != SpvStorageClassInput &&
  1372. storage_class != SpvStorageClassOutput &&
  1373. storage_class != SpvStorageClassMax) {
  1374. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1375. << "Target of Component decoration is invalid: must point to a "
  1376. "Storage Class of Input(1) or Output(3). Found Storage "
  1377. "Class "
  1378. << storage_class;
  1379. }
  1380. type_id = inst.type_id();
  1381. if (vstate.IsPointerType(type_id)) {
  1382. const auto pointer = vstate.FindDef(type_id);
  1383. type_id = pointer->GetOperandAs<uint32_t>(2);
  1384. }
  1385. } else {
  1386. if (inst.opcode() != SpvOpTypeStruct) {
  1387. return vstate.diag(SPV_ERROR_INVALID_DATA, &inst)
  1388. << "Attempted to get underlying data type via member index for "
  1389. "non-struct type.";
  1390. }
  1391. type_id = inst.word(decoration.struct_member_index() + 2);
  1392. }
  1393. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  1394. // Strip the array, if present.
  1395. if (vstate.GetIdOpcode(type_id) == SpvOpTypeArray) {
  1396. type_id = vstate.FindDef(type_id)->word(2u);
  1397. }
  1398. if (!vstate.IsIntScalarOrVectorType(type_id) &&
  1399. !vstate.IsFloatScalarOrVectorType(type_id)) {
  1400. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1401. << "Component decoration specified for type "
  1402. << vstate.getIdName(type_id) << " that is not a scalar or vector";
  1403. }
  1404. // For 16-, and 32-bit types, it is invalid if this sequence of components
  1405. // gets larger than 3.
  1406. const auto bit_width = vstate.GetBitWidth(type_id);
  1407. if (bit_width == 16 || bit_width == 32) {
  1408. assert(decoration.params().size() == 1 &&
  1409. "Grammar ensures Component has one parameter");
  1410. const auto component = decoration.params()[0];
  1411. const auto last_component = component + vstate.GetDimension(type_id) - 1;
  1412. if (last_component > 3) {
  1413. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1414. << "Sequence of components starting with " << component
  1415. << " and ending with " << last_component
  1416. << " gets larger than 3";
  1417. }
  1418. }
  1419. }
  1420. return SPV_SUCCESS;
  1421. }
  1422. #define PASS_OR_BAIL_AT_LINE(X, LINE) \
  1423. { \
  1424. spv_result_t e##LINE = (X); \
  1425. if (e##LINE != SPV_SUCCESS) return e##LINE; \
  1426. }
  1427. #define PASS_OR_BAIL(X) PASS_OR_BAIL_AT_LINE(X, __LINE__)
  1428. // Check rules for decorations where we start from the decoration rather
  1429. // than the decorated object. Assumes each decoration on a group have been
  1430. // propagated down to the group members.
  1431. spv_result_t CheckDecorationsFromDecoration(ValidationState_t& vstate) {
  1432. // Some rules are only checked for shaders.
  1433. const bool is_shader = vstate.HasCapability(SpvCapabilityShader);
  1434. for (const auto& kv : vstate.id_decorations()) {
  1435. const uint32_t id = kv.first;
  1436. const auto& decorations = kv.second;
  1437. if (decorations.empty()) continue;
  1438. const Instruction* inst = vstate.FindDef(id);
  1439. assert(inst);
  1440. // We assume the decorations applied to a decoration group have already
  1441. // been propagated down to the group members.
  1442. if (inst->opcode() == SpvOpDecorationGroup) continue;
  1443. for (const auto& decoration : decorations) {
  1444. switch (decoration.dec_type()) {
  1445. case SpvDecorationComponent:
  1446. PASS_OR_BAIL(CheckComponentDecoration(vstate, *inst, decoration));
  1447. break;
  1448. case SpvDecorationFPRoundingMode:
  1449. if (is_shader)
  1450. PASS_OR_BAIL(CheckFPRoundingModeForShaders(vstate, *inst));
  1451. break;
  1452. case SpvDecorationNonWritable:
  1453. PASS_OR_BAIL(CheckNonWritableDecoration(vstate, *inst, decoration));
  1454. break;
  1455. case SpvDecorationUniform:
  1456. case SpvDecorationUniformId:
  1457. PASS_OR_BAIL(CheckUniformDecoration(vstate, *inst, decoration));
  1458. break;
  1459. case SpvDecorationNoSignedWrap:
  1460. case SpvDecorationNoUnsignedWrap:
  1461. PASS_OR_BAIL(CheckIntegerWrapDecoration(vstate, *inst, decoration));
  1462. break;
  1463. default:
  1464. break;
  1465. }
  1466. }
  1467. }
  1468. return SPV_SUCCESS;
  1469. }
  1470. } // namespace
  1471. spv_result_t ValidateDecorations(ValidationState_t& vstate) {
  1472. if (auto error = CheckImportedVariableInitialization(vstate)) return error;
  1473. if (auto error = CheckDecorationsOfEntryPoints(vstate)) return error;
  1474. if (auto error = CheckDecorationsOfBuffers(vstate)) return error;
  1475. if (auto error = CheckDecorationsCompatibility(vstate)) return error;
  1476. if (auto error = CheckLinkageAttrOfFunctions(vstate)) return error;
  1477. if (auto error = CheckVulkanMemoryModelDeprecatedDecorations(vstate))
  1478. return error;
  1479. if (auto error = CheckDecorationsFromDecoration(vstate)) return error;
  1480. return SPV_SUCCESS;
  1481. }
  1482. } // namespace val
  1483. } // namespace spvtools