validate_decorations.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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. uint32_t 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 (array_stride == 0) {
  499. return fail(memberIdx) << "contains an array with stride 0";
  500. }
  501. if (!IsAlignedTo(array_stride, array_alignment))
  502. return fail(memberIdx)
  503. << "contains an array with stride " << decoration.params()[0]
  504. << " not satisfying alignment to " << alignment;
  505. }
  506. }
  507. bool is_int32 = false;
  508. bool is_const = false;
  509. uint32_t num_elements = 0;
  510. if (array_inst->opcode() == SpvOpTypeArray) {
  511. std::tie(is_int32, is_const, num_elements) =
  512. vstate.EvalInt32IfConst(array_inst->word(3));
  513. }
  514. num_elements = std::max(1u, num_elements);
  515. // Check each element recursively if it is a struct. There is a
  516. // limitation to this check if the array size is a spec constant or is a
  517. // runtime array then we will only check a single element. This means
  518. // some improper straddles might be missed.
  519. for (uint32_t i = 0; i < num_elements; ++i) {
  520. uint32_t next_offset = i * array_stride + offset;
  521. if (SpvOpTypeStruct == element_inst->opcode() &&
  522. SPV_SUCCESS != (recursive_status = checkLayout(
  523. typeId, storage_class_str, decoration_str,
  524. blockRules, next_offset, constraints, vstate)))
  525. return recursive_status;
  526. // If offsets accumulate up to a 16-byte multiple stop checking since
  527. // it will just repeat.
  528. if (i > 0 && (next_offset % 16 == 0)) break;
  529. }
  530. // Proceed to the element in case it is an array.
  531. array_inst = element_inst;
  532. array_alignment = scalar_block_layout
  533. ? getScalarAlignment(array_inst->id(), vstate)
  534. : getBaseAlignment(array_inst->id(), blockRules,
  535. constraint, constraints, vstate);
  536. const auto element_size =
  537. getSize(element_inst->id(), constraint, constraints, vstate);
  538. if (element_size > array_stride) {
  539. return fail(memberIdx)
  540. << "contains an array with stride " << array_stride
  541. << ", but with an element size of " << element_size;
  542. }
  543. }
  544. nextValidOffset = offset + size;
  545. if (!scalar_block_layout && blockRules &&
  546. (SpvOpTypeArray == opcode || SpvOpTypeStruct == opcode)) {
  547. // Uniform block rules don't permit anything in the padding of a struct
  548. // or array.
  549. nextValidOffset = align(nextValidOffset, alignment);
  550. }
  551. }
  552. return SPV_SUCCESS;
  553. }
  554. // Returns true if variable or structure id has given decoration. Handles also
  555. // nested structures.
  556. bool hasDecoration(uint32_t id, SpvDecoration decoration,
  557. ValidationState_t& vstate) {
  558. for (auto& dec : vstate.id_decorations(id)) {
  559. if (decoration == dec.dec_type()) return true;
  560. }
  561. if (SpvOpTypeStruct != vstate.FindDef(id)->opcode()) {
  562. return false;
  563. }
  564. for (auto member_id : getStructMembers(id, SpvOpTypeStruct, vstate)) {
  565. if (hasDecoration(member_id, decoration, vstate)) {
  566. return true;
  567. }
  568. }
  569. return false;
  570. }
  571. // Returns true if all ids of given type have a specified decoration.
  572. bool checkForRequiredDecoration(uint32_t struct_id, SpvDecoration decoration,
  573. SpvOp type, ValidationState_t& vstate) {
  574. const auto& members = getStructMembers(struct_id, vstate);
  575. for (size_t memberIdx = 0; memberIdx < members.size(); memberIdx++) {
  576. const auto id = members[memberIdx];
  577. if (type != vstate.FindDef(id)->opcode()) continue;
  578. bool found = false;
  579. for (auto& dec : vstate.id_decorations(id)) {
  580. if (decoration == dec.dec_type()) found = true;
  581. }
  582. for (auto& dec : vstate.id_decorations(struct_id)) {
  583. if (decoration == dec.dec_type() &&
  584. (int)memberIdx == dec.struct_member_index()) {
  585. found = true;
  586. }
  587. }
  588. if (!found) {
  589. return false;
  590. }
  591. }
  592. for (auto id : getStructMembers(struct_id, SpvOpTypeStruct, vstate)) {
  593. if (!checkForRequiredDecoration(id, decoration, type, vstate)) {
  594. return false;
  595. }
  596. }
  597. return true;
  598. }
  599. spv_result_t CheckLinkageAttrOfFunctions(ValidationState_t& vstate) {
  600. for (const auto& function : vstate.functions()) {
  601. if (function.block_count() == 0u) {
  602. // A function declaration (an OpFunction with no basic blocks), must have
  603. // a Linkage Attributes Decoration with the Import Linkage Type.
  604. if (!hasImportLinkageAttribute(function.id(), vstate)) {
  605. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  606. vstate.FindDef(function.id()))
  607. << "Function declaration (id " << function.id()
  608. << ") must have a LinkageAttributes decoration with the Import "
  609. "Linkage type.";
  610. }
  611. } else {
  612. if (hasImportLinkageAttribute(function.id(), vstate)) {
  613. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  614. vstate.FindDef(function.id()))
  615. << "Function definition (id " << function.id()
  616. << ") may not be decorated with Import Linkage type.";
  617. }
  618. }
  619. }
  620. return SPV_SUCCESS;
  621. }
  622. // Checks whether an imported variable is initialized by this module.
  623. spv_result_t CheckImportedVariableInitialization(ValidationState_t& vstate) {
  624. // According the SPIR-V Spec 2.16.1, it is illegal to initialize an imported
  625. // variable. This means that a module-scope OpVariable with initialization
  626. // value cannot be marked with the Import Linkage Type (import type id = 1).
  627. for (auto global_var_id : vstate.global_vars()) {
  628. // Initializer <id> is an optional argument for OpVariable. If initializer
  629. // <id> is present, the instruction will have 5 words.
  630. auto variable_instr = vstate.FindDef(global_var_id);
  631. if (variable_instr->words().size() == 5u &&
  632. hasImportLinkageAttribute(global_var_id, vstate)) {
  633. return vstate.diag(SPV_ERROR_INVALID_ID, variable_instr)
  634. << "A module-scope OpVariable with initialization value "
  635. "cannot be marked with the Import Linkage Type.";
  636. }
  637. }
  638. return SPV_SUCCESS;
  639. }
  640. // Checks whether a builtin variable is valid.
  641. spv_result_t CheckBuiltInVariable(uint32_t var_id, ValidationState_t& vstate) {
  642. const auto& decorations = vstate.id_decorations(var_id);
  643. for (const auto& d : decorations) {
  644. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  645. if (d.dec_type() == SpvDecorationLocation ||
  646. d.dec_type() == SpvDecorationComponent) {
  647. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  648. << "A BuiltIn variable (id " << var_id
  649. << ") cannot have any Location or Component decorations";
  650. }
  651. }
  652. }
  653. return SPV_SUCCESS;
  654. }
  655. // Checks whether proper decorations have been appied to the entry points.
  656. spv_result_t CheckDecorationsOfEntryPoints(ValidationState_t& vstate) {
  657. for (uint32_t entry_point : vstate.entry_points()) {
  658. const auto& descs = vstate.entry_point_descriptions(entry_point);
  659. int num_builtin_inputs = 0;
  660. int num_builtin_outputs = 0;
  661. for (const auto& desc : descs) {
  662. std::unordered_set<Instruction*> seen_vars;
  663. for (auto interface : desc.interfaces) {
  664. Instruction* var_instr = vstate.FindDef(interface);
  665. if (!var_instr || SpvOpVariable != var_instr->opcode()) {
  666. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  667. << "Interfaces passed to OpEntryPoint must be of type "
  668. "OpTypeVariable. Found Op"
  669. << spvOpcodeString(var_instr->opcode()) << ".";
  670. }
  671. const SpvStorageClass storage_class =
  672. var_instr->GetOperandAs<SpvStorageClass>(2);
  673. if (vstate.version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
  674. // Starting in 1.4, OpEntryPoint must list all global variables
  675. // it statically uses and those interfaces must be unique.
  676. if (storage_class == SpvStorageClassFunction) {
  677. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  678. << "OpEntryPoint interfaces should only list global "
  679. "variables";
  680. }
  681. if (!seen_vars.insert(var_instr).second) {
  682. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  683. << "Non-unique OpEntryPoint interface "
  684. << vstate.getIdName(interface) << " is disallowed";
  685. }
  686. } else {
  687. if (storage_class != SpvStorageClassInput &&
  688. storage_class != SpvStorageClassOutput) {
  689. return vstate.diag(SPV_ERROR_INVALID_ID, var_instr)
  690. << "OpEntryPoint interfaces must be OpVariables with "
  691. "Storage Class of Input(1) or Output(3). Found Storage "
  692. "Class "
  693. << storage_class << " for Entry Point id " << entry_point
  694. << ".";
  695. }
  696. }
  697. const uint32_t ptr_id = var_instr->word(1);
  698. Instruction* ptr_instr = vstate.FindDef(ptr_id);
  699. // It is guaranteed (by validator ID checks) that ptr_instr is
  700. // OpTypePointer. Word 3 of this instruction is the type being pointed
  701. // to.
  702. const uint32_t type_id = ptr_instr->word(3);
  703. Instruction* type_instr = vstate.FindDef(type_id);
  704. if (type_instr && SpvOpTypeStruct == type_instr->opcode() &&
  705. isBuiltInStruct(type_id, vstate)) {
  706. if (storage_class == SpvStorageClassInput) ++num_builtin_inputs;
  707. if (storage_class == SpvStorageClassOutput) ++num_builtin_outputs;
  708. if (num_builtin_inputs > 1 || num_builtin_outputs > 1) break;
  709. if (auto error = CheckBuiltInVariable(interface, vstate))
  710. return error;
  711. } else if (isBuiltInVar(interface, vstate)) {
  712. if (auto error = CheckBuiltInVariable(interface, vstate))
  713. return error;
  714. }
  715. }
  716. if (num_builtin_inputs > 1 || num_builtin_outputs > 1) {
  717. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  718. vstate.FindDef(entry_point))
  719. << "There must be at most one object per Storage Class that can "
  720. "contain a structure type containing members decorated with "
  721. "BuiltIn, consumed per entry-point. Entry Point id "
  722. << entry_point << " does not meet this requirement.";
  723. }
  724. // The LinkageAttributes Decoration cannot be applied to functions
  725. // targeted by an OpEntryPoint instruction
  726. for (auto& decoration : vstate.id_decorations(entry_point)) {
  727. if (SpvDecorationLinkageAttributes == decoration.dec_type()) {
  728. const char* linkage_name =
  729. reinterpret_cast<const char*>(&decoration.params()[0]);
  730. return vstate.diag(SPV_ERROR_INVALID_BINARY,
  731. vstate.FindDef(entry_point))
  732. << "The LinkageAttributes Decoration (Linkage name: "
  733. << linkage_name << ") cannot be applied to function id "
  734. << entry_point
  735. << " because it is targeted by an OpEntryPoint instruction.";
  736. }
  737. }
  738. }
  739. }
  740. return SPV_SUCCESS;
  741. }
  742. // Load |constraints| with all the member constraints for structs contained
  743. // within the given array type.
  744. void ComputeMemberConstraintsForArray(MemberConstraints* constraints,
  745. uint32_t array_id,
  746. const LayoutConstraints& inherited,
  747. ValidationState_t& vstate);
  748. // Load |constraints| with all the member constraints for the given struct,
  749. // and all its contained structs.
  750. void ComputeMemberConstraintsForStruct(MemberConstraints* constraints,
  751. uint32_t struct_id,
  752. const LayoutConstraints& inherited,
  753. ValidationState_t& vstate) {
  754. assert(constraints);
  755. const auto& members = getStructMembers(struct_id, vstate);
  756. for (uint32_t memberIdx = 0, numMembers = uint32_t(members.size());
  757. memberIdx < numMembers; memberIdx++) {
  758. LayoutConstraints& constraint =
  759. (*constraints)[std::make_pair(struct_id, memberIdx)];
  760. constraint = inherited;
  761. for (auto& decoration : vstate.id_decorations(struct_id)) {
  762. if (decoration.struct_member_index() == (int)memberIdx) {
  763. switch (decoration.dec_type()) {
  764. case SpvDecorationRowMajor:
  765. constraint.majorness = kRowMajor;
  766. break;
  767. case SpvDecorationColMajor:
  768. constraint.majorness = kColumnMajor;
  769. break;
  770. case SpvDecorationMatrixStride:
  771. constraint.matrix_stride = decoration.params()[0];
  772. break;
  773. default:
  774. break;
  775. }
  776. }
  777. }
  778. // Now recurse
  779. auto member_type_id = members[memberIdx];
  780. const auto member_type_inst = vstate.FindDef(member_type_id);
  781. const auto opcode = member_type_inst->opcode();
  782. switch (opcode) {
  783. case SpvOpTypeArray:
  784. case SpvOpTypeRuntimeArray:
  785. ComputeMemberConstraintsForArray(constraints, member_type_id, inherited,
  786. vstate);
  787. break;
  788. case SpvOpTypeStruct:
  789. ComputeMemberConstraintsForStruct(constraints, member_type_id,
  790. inherited, vstate);
  791. break;
  792. default:
  793. break;
  794. }
  795. }
  796. }
  797. void ComputeMemberConstraintsForArray(MemberConstraints* constraints,
  798. uint32_t array_id,
  799. const LayoutConstraints& inherited,
  800. ValidationState_t& vstate) {
  801. assert(constraints);
  802. auto elem_type_id = vstate.FindDef(array_id)->words()[2];
  803. const auto elem_type_inst = vstate.FindDef(elem_type_id);
  804. const auto opcode = elem_type_inst->opcode();
  805. switch (opcode) {
  806. case SpvOpTypeArray:
  807. case SpvOpTypeRuntimeArray:
  808. ComputeMemberConstraintsForArray(constraints, elem_type_id, inherited,
  809. vstate);
  810. break;
  811. case SpvOpTypeStruct:
  812. ComputeMemberConstraintsForStruct(constraints, elem_type_id, inherited,
  813. vstate);
  814. break;
  815. default:
  816. break;
  817. }
  818. }
  819. spv_result_t CheckDecorationsOfBuffers(ValidationState_t& vstate) {
  820. // Set of entry points that are known to use a push constant.
  821. std::unordered_set<uint32_t> uses_push_constant;
  822. for (const auto& inst : vstate.ordered_instructions()) {
  823. const auto& words = inst.words();
  824. if (SpvOpVariable == inst.opcode()) {
  825. const auto var_id = inst.id();
  826. // For storage class / decoration combinations, see Vulkan 14.5.4 "Offset
  827. // and Stride Assignment".
  828. const auto storageClass = words[3];
  829. const bool uniform = storageClass == SpvStorageClassUniform;
  830. const bool uniform_constant =
  831. storageClass == SpvStorageClassUniformConstant;
  832. const bool push_constant = storageClass == SpvStorageClassPushConstant;
  833. const bool storage_buffer = storageClass == SpvStorageClassStorageBuffer;
  834. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  835. // Vulkan 14.5.1: There must be no more than one PushConstant block
  836. // per entry point.
  837. if (push_constant) {
  838. auto entry_points = vstate.EntryPointReferences(var_id);
  839. for (auto ep_id : entry_points) {
  840. const bool already_used = !uses_push_constant.insert(ep_id).second;
  841. if (already_used) {
  842. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  843. << "Entry point id '" << ep_id
  844. << "' uses more than one PushConstant interface.\n"
  845. << "From Vulkan spec, section 14.5.1:\n"
  846. << "There must be no more than one push constant block "
  847. << "statically used per shader entry point.";
  848. }
  849. }
  850. }
  851. // Vulkan 14.5.2: Check DescriptorSet and Binding decoration for
  852. // UniformConstant which cannot be a struct.
  853. if (uniform_constant) {
  854. auto entry_points = vstate.EntryPointReferences(var_id);
  855. if (!entry_points.empty() &&
  856. !hasDecoration(var_id, SpvDecorationDescriptorSet, vstate)) {
  857. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  858. << "UniformConstant id '" << var_id
  859. << "' is missing DescriptorSet decoration.\n"
  860. << "From Vulkan spec, section 14.5.2:\n"
  861. << "These variables must have DescriptorSet and Binding "
  862. "decorations specified";
  863. }
  864. if (!entry_points.empty() &&
  865. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  866. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  867. << "UniformConstant id '" << var_id
  868. << "' is missing Binding decoration.\n"
  869. << "From Vulkan spec, section 14.5.2:\n"
  870. << "These variables must have DescriptorSet and Binding "
  871. "decorations specified";
  872. }
  873. }
  874. }
  875. if (spvIsOpenGLEnv(vstate.context()->target_env)) {
  876. bool has_block = hasDecoration(var_id, SpvDecorationBlock, vstate);
  877. bool has_buffer_block =
  878. hasDecoration(var_id, SpvDecorationBufferBlock, vstate);
  879. if ((uniform && (has_block || has_buffer_block)) ||
  880. (storage_buffer && has_block)) {
  881. auto entry_points = vstate.EntryPointReferences(var_id);
  882. if (!entry_points.empty() &&
  883. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  884. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  885. << (uniform ? "Uniform" : "Storage Buffer") << " id '"
  886. << var_id << "' is missing Binding decoration.\n"
  887. << "From ARB_gl_spirv extension:\n"
  888. << "Uniform and shader storage block variables must "
  889. << "also be decorated with a *Binding*.";
  890. }
  891. }
  892. }
  893. const bool phys_storage_buffer =
  894. storageClass == SpvStorageClassPhysicalStorageBufferEXT;
  895. if (uniform || push_constant || storage_buffer || phys_storage_buffer) {
  896. const auto ptrInst = vstate.FindDef(words[1]);
  897. assert(SpvOpTypePointer == ptrInst->opcode());
  898. auto id = ptrInst->words()[3];
  899. auto id_inst = vstate.FindDef(id);
  900. // Jump through one level of arraying.
  901. if (id_inst->opcode() == SpvOpTypeArray ||
  902. id_inst->opcode() == SpvOpTypeRuntimeArray) {
  903. id = id_inst->GetOperandAs<uint32_t>(1u);
  904. id_inst = vstate.FindDef(id);
  905. }
  906. // Struct requirement is checked on variables so just move on here.
  907. if (SpvOpTypeStruct != id_inst->opcode()) continue;
  908. MemberConstraints constraints;
  909. ComputeMemberConstraintsForStruct(&constraints, id, LayoutConstraints(),
  910. vstate);
  911. // Prepare for messages
  912. const char* sc_str =
  913. uniform ? "Uniform"
  914. : (push_constant ? "PushConstant" : "StorageBuffer");
  915. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  916. const bool block = hasDecoration(id, SpvDecorationBlock, vstate);
  917. const bool buffer_block =
  918. hasDecoration(id, SpvDecorationBufferBlock, vstate);
  919. if (storage_buffer && buffer_block) {
  920. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  921. << "Storage buffer id '" << var_id
  922. << " In Vulkan, BufferBlock is disallowed on variables in "
  923. "the StorageBuffer storage class";
  924. }
  925. // Vulkan 14.5.1/2: Check Block decoration for PushConstant, Uniform
  926. // and StorageBuffer variables. Uniform can also use BufferBlock.
  927. if (push_constant && !block) {
  928. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  929. << "PushConstant id '" << id
  930. << "' is missing Block decoration.\n"
  931. << "From Vulkan spec, section 14.5.1:\n"
  932. << "Such variables must be identified with a Block "
  933. "decoration";
  934. }
  935. if (storage_buffer && !block) {
  936. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  937. << "StorageBuffer id '" << id
  938. << "' is missing Block decoration.\n"
  939. << "From Vulkan spec, section 14.5.2:\n"
  940. << "Such variables must be identified with a Block "
  941. "decoration";
  942. }
  943. if (uniform && !block && !buffer_block) {
  944. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  945. << "Uniform id '" << id
  946. << "' is missing Block or BufferBlock decoration.\n"
  947. << "From Vulkan spec, section 14.5.2:\n"
  948. << "Such variables must be identified with a Block or "
  949. "BufferBlock decoration";
  950. }
  951. // Vulkan 14.5.2: Check DescriptorSet and Binding decoration for
  952. // Uniform and StorageBuffer variables.
  953. if (uniform || storage_buffer) {
  954. auto entry_points = vstate.EntryPointReferences(var_id);
  955. if (!entry_points.empty() &&
  956. !hasDecoration(var_id, SpvDecorationDescriptorSet, vstate)) {
  957. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  958. << sc_str << " id '" << var_id
  959. << "' is missing DescriptorSet decoration.\n"
  960. << "From Vulkan spec, section 14.5.2:\n"
  961. << "These variables must have DescriptorSet and Binding "
  962. "decorations specified";
  963. }
  964. if (!entry_points.empty() &&
  965. !hasDecoration(var_id, SpvDecorationBinding, vstate)) {
  966. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(var_id))
  967. << sc_str << " id '" << var_id
  968. << "' is missing Binding decoration.\n"
  969. << "From Vulkan spec, section 14.5.2:\n"
  970. << "These variables must have DescriptorSet and Binding "
  971. "decorations specified";
  972. }
  973. }
  974. }
  975. for (const auto& dec : vstate.id_decorations(id)) {
  976. const bool blockDeco = SpvDecorationBlock == dec.dec_type();
  977. const bool bufferDeco = SpvDecorationBufferBlock == dec.dec_type();
  978. const bool blockRules = uniform && blockDeco;
  979. const bool bufferRules =
  980. (uniform && bufferDeco) || (push_constant && blockDeco) ||
  981. ((storage_buffer || phys_storage_buffer) && blockDeco);
  982. if (uniform && blockDeco) {
  983. vstate.RegisterPointerToUniformBlock(ptrInst->id());
  984. vstate.RegisterStructForUniformBlock(id);
  985. }
  986. if ((uniform && bufferDeco) ||
  987. ((storage_buffer || phys_storage_buffer) && blockDeco)) {
  988. vstate.RegisterPointerToStorageBuffer(ptrInst->id());
  989. vstate.RegisterStructForStorageBuffer(id);
  990. }
  991. if (blockRules || bufferRules) {
  992. const char* deco_str = blockDeco ? "Block" : "BufferBlock";
  993. spv_result_t recursive_status = SPV_SUCCESS;
  994. if (isMissingOffsetInStruct(id, vstate)) {
  995. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  996. << "Structure id " << id << " decorated as " << deco_str
  997. << " must be explicitly laid out with Offset "
  998. "decorations.";
  999. } else if (hasDecoration(id, SpvDecorationGLSLShared, vstate)) {
  1000. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1001. << "Structure id " << id << " decorated as " << deco_str
  1002. << " must not use GLSLShared decoration.";
  1003. } else if (hasDecoration(id, SpvDecorationGLSLPacked, vstate)) {
  1004. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1005. << "Structure id " << id << " decorated as " << deco_str
  1006. << " must not use GLSLPacked decoration.";
  1007. } else if (!checkForRequiredDecoration(id, SpvDecorationArrayStride,
  1008. SpvOpTypeArray, vstate)) {
  1009. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1010. << "Structure id " << id << " decorated as " << deco_str
  1011. << " must be explicitly laid out with ArrayStride "
  1012. "decorations.";
  1013. } else if (!checkForRequiredDecoration(id,
  1014. SpvDecorationMatrixStride,
  1015. SpvOpTypeMatrix, vstate)) {
  1016. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1017. << "Structure id " << id << " decorated as " << deco_str
  1018. << " must be explicitly laid out with MatrixStride "
  1019. "decorations.";
  1020. } else if (blockRules &&
  1021. (SPV_SUCCESS != (recursive_status = checkLayout(
  1022. id, sc_str, deco_str, true, 0,
  1023. constraints, vstate)))) {
  1024. return recursive_status;
  1025. } else if (bufferRules &&
  1026. (SPV_SUCCESS != (recursive_status = checkLayout(
  1027. id, sc_str, deco_str, false, 0,
  1028. constraints, vstate)))) {
  1029. return recursive_status;
  1030. }
  1031. }
  1032. }
  1033. }
  1034. }
  1035. }
  1036. return SPV_SUCCESS;
  1037. }
  1038. // Returns true if |decoration| cannot be applied to the same id more than once.
  1039. bool AtMostOncePerId(SpvDecoration decoration) {
  1040. return decoration == SpvDecorationArrayStride;
  1041. }
  1042. // Returns true if |decoration| cannot be applied to the same member more than
  1043. // once.
  1044. bool AtMostOncePerMember(SpvDecoration decoration) {
  1045. switch (decoration) {
  1046. case SpvDecorationOffset:
  1047. case SpvDecorationMatrixStride:
  1048. case SpvDecorationRowMajor:
  1049. case SpvDecorationColMajor:
  1050. return true;
  1051. default:
  1052. return false;
  1053. }
  1054. }
  1055. // Returns the string name for |decoration|.
  1056. const char* GetDecorationName(SpvDecoration decoration) {
  1057. switch (decoration) {
  1058. case SpvDecorationAliased:
  1059. return "Aliased";
  1060. case SpvDecorationRestrict:
  1061. return "Restrict";
  1062. case SpvDecorationArrayStride:
  1063. return "ArrayStride";
  1064. case SpvDecorationOffset:
  1065. return "Offset";
  1066. case SpvDecorationMatrixStride:
  1067. return "MatrixStride";
  1068. case SpvDecorationRowMajor:
  1069. return "RowMajor";
  1070. case SpvDecorationColMajor:
  1071. return "ColMajor";
  1072. case SpvDecorationBlock:
  1073. return "Block";
  1074. case SpvDecorationBufferBlock:
  1075. return "BufferBlock";
  1076. default:
  1077. return "";
  1078. }
  1079. }
  1080. spv_result_t CheckDecorationsCompatibility(ValidationState_t& vstate) {
  1081. using PerIDKey = std::tuple<SpvDecoration, uint32_t>;
  1082. using PerMemberKey = std::tuple<SpvDecoration, uint32_t, uint32_t>;
  1083. // An Array of pairs where the decorations in the pair cannot both be applied
  1084. // to the same id.
  1085. static const SpvDecoration mutually_exclusive_per_id[][2] = {
  1086. {SpvDecorationBlock, SpvDecorationBufferBlock},
  1087. {SpvDecorationRestrict, SpvDecorationAliased}};
  1088. static const auto num_mutually_exclusive_per_id_pairs =
  1089. sizeof(mutually_exclusive_per_id) / (2 * sizeof(SpvDecoration));
  1090. // An Array of pairs where the decorations in the pair cannot both be applied
  1091. // to the same member.
  1092. static const SpvDecoration mutually_exclusive_per_member[][2] = {
  1093. {SpvDecorationRowMajor, SpvDecorationColMajor}};
  1094. static const auto num_mutually_exclusive_per_mem_pairs =
  1095. sizeof(mutually_exclusive_per_member) / (2 * sizeof(SpvDecoration));
  1096. std::set<PerIDKey> seen_per_id;
  1097. std::set<PerMemberKey> seen_per_member;
  1098. for (const auto& inst : vstate.ordered_instructions()) {
  1099. const auto& words = inst.words();
  1100. if (SpvOpDecorate == inst.opcode()) {
  1101. const auto id = words[1];
  1102. const auto dec_type = static_cast<SpvDecoration>(words[2]);
  1103. const auto k = PerIDKey(dec_type, id);
  1104. const auto already_used = !seen_per_id.insert(k).second;
  1105. if (already_used && AtMostOncePerId(dec_type)) {
  1106. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1107. << "ID '" << id << "' decorated with "
  1108. << GetDecorationName(dec_type)
  1109. << " multiple times is not allowed.";
  1110. }
  1111. // Verify certain mutually exclusive decorations are not both applied on
  1112. // an ID.
  1113. for (uint32_t pair_idx = 0;
  1114. pair_idx < num_mutually_exclusive_per_id_pairs; ++pair_idx) {
  1115. SpvDecoration excl_dec_type = SpvDecorationMax;
  1116. if (mutually_exclusive_per_id[pair_idx][0] == dec_type) {
  1117. excl_dec_type = mutually_exclusive_per_id[pair_idx][1];
  1118. } else if (mutually_exclusive_per_id[pair_idx][1] == dec_type) {
  1119. excl_dec_type = mutually_exclusive_per_id[pair_idx][0];
  1120. } else {
  1121. continue;
  1122. }
  1123. const auto excl_k = PerIDKey(excl_dec_type, id);
  1124. if (seen_per_id.find(excl_k) != seen_per_id.end()) {
  1125. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1126. << "ID '" << id << "' decorated with both "
  1127. << GetDecorationName(dec_type) << " and "
  1128. << GetDecorationName(excl_dec_type) << " is not allowed.";
  1129. }
  1130. }
  1131. } else if (SpvOpMemberDecorate == inst.opcode()) {
  1132. const auto id = words[1];
  1133. const auto member_id = words[2];
  1134. const auto dec_type = static_cast<SpvDecoration>(words[3]);
  1135. const auto k = PerMemberKey(dec_type, id, member_id);
  1136. const auto already_used = !seen_per_member.insert(k).second;
  1137. if (already_used && AtMostOncePerMember(dec_type)) {
  1138. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1139. << "ID '" << id << "', member '" << member_id
  1140. << "' decorated with " << GetDecorationName(dec_type)
  1141. << " multiple times is not allowed.";
  1142. }
  1143. // Verify certain mutually exclusive decorations are not both applied on
  1144. // a (ID, member) tuple.
  1145. for (uint32_t pair_idx = 0;
  1146. pair_idx < num_mutually_exclusive_per_mem_pairs; ++pair_idx) {
  1147. SpvDecoration excl_dec_type = SpvDecorationMax;
  1148. if (mutually_exclusive_per_member[pair_idx][0] == dec_type) {
  1149. excl_dec_type = mutually_exclusive_per_member[pair_idx][1];
  1150. } else if (mutually_exclusive_per_member[pair_idx][1] == dec_type) {
  1151. excl_dec_type = mutually_exclusive_per_member[pair_idx][0];
  1152. } else {
  1153. continue;
  1154. }
  1155. const auto excl_k = PerMemberKey(excl_dec_type, id, member_id);
  1156. if (seen_per_member.find(excl_k) != seen_per_member.end()) {
  1157. return vstate.diag(SPV_ERROR_INVALID_ID, vstate.FindDef(id))
  1158. << "ID '" << id << "', member '" << member_id
  1159. << "' decorated with both " << GetDecorationName(dec_type)
  1160. << " and " << GetDecorationName(excl_dec_type)
  1161. << " is not allowed.";
  1162. }
  1163. }
  1164. }
  1165. }
  1166. return SPV_SUCCESS;
  1167. }
  1168. spv_result_t CheckVulkanMemoryModelDeprecatedDecorations(
  1169. ValidationState_t& vstate) {
  1170. if (vstate.memory_model() != SpvMemoryModelVulkanKHR) return SPV_SUCCESS;
  1171. std::string msg;
  1172. std::ostringstream str(msg);
  1173. for (const auto& def : vstate.all_definitions()) {
  1174. const auto inst = def.second;
  1175. const auto id = inst->id();
  1176. for (const auto& dec : vstate.id_decorations(id)) {
  1177. const auto member = dec.struct_member_index();
  1178. if (dec.dec_type() == SpvDecorationCoherent ||
  1179. dec.dec_type() == SpvDecorationVolatile) {
  1180. str << (dec.dec_type() == SpvDecorationCoherent ? "Coherent"
  1181. : "Volatile");
  1182. str << " decoration targeting " << vstate.getIdName(id);
  1183. if (member != Decoration::kInvalidMember) {
  1184. str << " (member index " << member << ")";
  1185. }
  1186. str << " is banned when using the Vulkan memory model.";
  1187. return vstate.diag(SPV_ERROR_INVALID_ID, inst) << str.str();
  1188. }
  1189. }
  1190. }
  1191. return SPV_SUCCESS;
  1192. }
  1193. // Returns SPV_SUCCESS if validation rules are satisfied for FPRoundingMode
  1194. // decorations. Otherwise emits a diagnostic and returns something other than
  1195. // SPV_SUCCESS.
  1196. spv_result_t CheckFPRoundingModeForShaders(ValidationState_t& vstate,
  1197. const Instruction& inst) {
  1198. // Validates width-only conversion instruction for floating-point object
  1199. // i.e., OpFConvert
  1200. if (inst.opcode() != SpvOpFConvert) {
  1201. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1202. << "FPRoundingMode decoration can be applied only to a "
  1203. "width-only conversion instruction for floating-point "
  1204. "object.";
  1205. }
  1206. // Validates Object operand of an OpStore
  1207. for (const auto& use : inst.uses()) {
  1208. const auto store = use.first;
  1209. if (store->opcode() == SpvOpFConvert) continue;
  1210. if (spvOpcodeIsDebug(store->opcode())) continue;
  1211. if (spvOpcodeIsDecoration(store->opcode())) continue;
  1212. if (store->opcode() != SpvOpStore) {
  1213. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1214. << "FPRoundingMode decoration can be applied only to the "
  1215. "Object operand of an OpStore.";
  1216. }
  1217. if (use.second != 2) {
  1218. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1219. << "FPRoundingMode decoration can be applied only to the "
  1220. "Object operand of an OpStore.";
  1221. }
  1222. const auto ptr_inst = vstate.FindDef(store->GetOperandAs<uint32_t>(0));
  1223. const auto ptr_type = vstate.FindDef(ptr_inst->GetOperandAs<uint32_t>(0));
  1224. const auto half_float_id = ptr_type->GetOperandAs<uint32_t>(2);
  1225. if (!vstate.IsFloatScalarOrVectorType(half_float_id) ||
  1226. vstate.GetBitWidth(half_float_id) != 16) {
  1227. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1228. << "FPRoundingMode decoration can be applied only to the "
  1229. "Object operand of an OpStore storing through a pointer "
  1230. "to "
  1231. "a 16-bit floating-point scalar or vector object.";
  1232. }
  1233. // Validates storage class of the pointer to the OpStore
  1234. const auto storage = ptr_type->GetOperandAs<uint32_t>(1);
  1235. if (storage != SpvStorageClassStorageBuffer &&
  1236. storage != SpvStorageClassUniform &&
  1237. storage != SpvStorageClassPushConstant &&
  1238. storage != SpvStorageClassInput && storage != SpvStorageClassOutput &&
  1239. storage != SpvStorageClassPhysicalStorageBufferEXT) {
  1240. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1241. << "FPRoundingMode decoration can be applied only to the "
  1242. "Object operand of an OpStore in the StorageBuffer, "
  1243. "PhysicalStorageBufferEXT, Uniform, PushConstant, Input, or "
  1244. "Output Storage Classes.";
  1245. }
  1246. }
  1247. return SPV_SUCCESS;
  1248. }
  1249. // Returns SPV_SUCCESS if validation rules are satisfied for the NonWritable
  1250. // decoration. Otherwise emits a diagnostic and returns something other than
  1251. // SPV_SUCCESS. The |inst| parameter is the object being decorated. This must
  1252. // be called after TypePass and AnnotateCheckDecorationsOfBuffers are called.
  1253. spv_result_t CheckNonWritableDecoration(ValidationState_t& vstate,
  1254. const Instruction& inst,
  1255. const Decoration& decoration) {
  1256. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1257. if (decoration.struct_member_index() == Decoration::kInvalidMember) {
  1258. // The target must be a memory object declaration.
  1259. // First, it must be a variable or function parameter.
  1260. const auto opcode = inst.opcode();
  1261. const auto type_id = inst.type_id();
  1262. if (opcode != SpvOpVariable && opcode != SpvOpFunctionParameter) {
  1263. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1264. << "Target of NonWritable decoration must be a memory object "
  1265. "declaration (a variable or a function parameter)";
  1266. }
  1267. const auto var_storage_class = opcode == SpvOpVariable
  1268. ? inst.GetOperandAs<SpvStorageClass>(2)
  1269. : SpvStorageClassMax;
  1270. if ((var_storage_class == SpvStorageClassFunction ||
  1271. var_storage_class == SpvStorageClassPrivate) &&
  1272. vstate.features().nonwritable_var_in_function_or_private) {
  1273. // New permitted feature in SPIR-V 1.4.
  1274. } else if (
  1275. // It may point to a UBO, SSBO, or storage image.
  1276. vstate.IsPointerToUniformBlock(type_id) ||
  1277. vstate.IsPointerToStorageBuffer(type_id) ||
  1278. vstate.IsPointerToStorageImage(type_id)) {
  1279. } else {
  1280. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1281. << "Target of NonWritable decoration is invalid: must point to a "
  1282. "storage image, uniform block, "
  1283. << (vstate.features().nonwritable_var_in_function_or_private
  1284. ? "storage buffer, or variable in Private or Function "
  1285. "storage class"
  1286. : "or storage buffer");
  1287. }
  1288. }
  1289. return SPV_SUCCESS;
  1290. }
  1291. // Returns SPV_SUCCESS if validation rules are satisfied for Uniform or
  1292. // UniformId decorations. Otherwise emits a diagnostic and returns something
  1293. // other than SPV_SUCCESS. Assumes each decoration on a group has been
  1294. // propagated down to the group members. The |inst| parameter is the object
  1295. // being decorated.
  1296. spv_result_t CheckUniformDecoration(ValidationState_t& vstate,
  1297. const Instruction& inst,
  1298. const Decoration& decoration) {
  1299. const char* const dec_name =
  1300. decoration.dec_type() == SpvDecorationUniform ? "Uniform" : "UniformId";
  1301. // Uniform or UniformId must decorate an "object"
  1302. // - has a result ID
  1303. // - is an instantiation of a non-void type. So it has a type ID, and that
  1304. // type is not void.
  1305. // We already know the result ID is non-zero.
  1306. if (inst.type_id() == 0) {
  1307. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1308. << dec_name << " decoration applied to a non-object";
  1309. }
  1310. if (Instruction* type_inst = vstate.FindDef(inst.type_id())) {
  1311. if (type_inst->opcode() == SpvOpTypeVoid) {
  1312. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1313. << dec_name << " decoration applied to a value with void type";
  1314. }
  1315. } else {
  1316. // We might never get here because this would have been rejected earlier in
  1317. // the flow.
  1318. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1319. << dec_name << " decoration applied to an object with invalid type";
  1320. }
  1321. // Use of Uniform with OpDecorate is checked elsewhere.
  1322. // Use of UniformId with OpDecorateId is checked elsewhere.
  1323. if (decoration.dec_type() == SpvDecorationUniformId) {
  1324. assert(decoration.params().size() == 1 &&
  1325. "Grammar ensures UniformId has one parameter");
  1326. // The scope id is an execution scope.
  1327. if (auto error =
  1328. ValidateExecutionScope(vstate, &inst, decoration.params()[0]))
  1329. return error;
  1330. }
  1331. return SPV_SUCCESS;
  1332. }
  1333. // Returns SPV_SUCCESS if validation rules are satisfied for NoSignedWrap or
  1334. // NoUnsignedWrap decorations. Otherwise emits a diagnostic and returns
  1335. // something other than SPV_SUCCESS. Assumes each decoration on a group has been
  1336. // propagated down to the group members.
  1337. spv_result_t CheckIntegerWrapDecoration(ValidationState_t& vstate,
  1338. const Instruction& inst,
  1339. const Decoration& decoration) {
  1340. switch (inst.opcode()) {
  1341. case SpvOpIAdd:
  1342. case SpvOpISub:
  1343. case SpvOpIMul:
  1344. case SpvOpShiftLeftLogical:
  1345. case SpvOpSNegate:
  1346. return SPV_SUCCESS;
  1347. case SpvOpExtInst:
  1348. // TODO(dneto): Only certain extended instructions allow these
  1349. // decorations. For now allow anything.
  1350. return SPV_SUCCESS;
  1351. default:
  1352. break;
  1353. }
  1354. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1355. << (decoration.dec_type() == SpvDecorationNoSignedWrap
  1356. ? "NoSignedWrap"
  1357. : "NoUnsignedWrap")
  1358. << " decoration may not be applied to "
  1359. << spvOpcodeString(inst.opcode());
  1360. }
  1361. // Returns SPV_SUCCESS if validation rules are satisfied for the Component
  1362. // decoration. Otherwise emits a diagnostic and returns something other than
  1363. // SPV_SUCCESS.
  1364. spv_result_t CheckComponentDecoration(ValidationState_t& vstate,
  1365. const Instruction& inst,
  1366. const Decoration& decoration) {
  1367. assert(inst.id() && "Parser ensures the target of the decoration has an ID");
  1368. uint32_t type_id;
  1369. if (decoration.struct_member_index() == Decoration::kInvalidMember) {
  1370. // The target must be a memory object declaration.
  1371. const auto opcode = inst.opcode();
  1372. if (opcode != SpvOpVariable && opcode != SpvOpFunctionParameter) {
  1373. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1374. << "Target of Component decoration must be a memory object "
  1375. "declaration (a variable or a function parameter)";
  1376. }
  1377. // Only valid for the Input and Output Storage Classes.
  1378. const auto storage_class = opcode == SpvOpVariable
  1379. ? inst.GetOperandAs<SpvStorageClass>(2)
  1380. : SpvStorageClassMax;
  1381. if (storage_class != SpvStorageClassInput &&
  1382. storage_class != SpvStorageClassOutput &&
  1383. storage_class != SpvStorageClassMax) {
  1384. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1385. << "Target of Component decoration is invalid: must point to a "
  1386. "Storage Class of Input(1) or Output(3). Found Storage "
  1387. "Class "
  1388. << storage_class;
  1389. }
  1390. type_id = inst.type_id();
  1391. if (vstate.IsPointerType(type_id)) {
  1392. const auto pointer = vstate.FindDef(type_id);
  1393. type_id = pointer->GetOperandAs<uint32_t>(2);
  1394. }
  1395. } else {
  1396. if (inst.opcode() != SpvOpTypeStruct) {
  1397. return vstate.diag(SPV_ERROR_INVALID_DATA, &inst)
  1398. << "Attempted to get underlying data type via member index for "
  1399. "non-struct type.";
  1400. }
  1401. type_id = inst.word(decoration.struct_member_index() + 2);
  1402. }
  1403. if (spvIsVulkanEnv(vstate.context()->target_env)) {
  1404. // Strip the array, if present.
  1405. if (vstate.GetIdOpcode(type_id) == SpvOpTypeArray) {
  1406. type_id = vstate.FindDef(type_id)->word(2u);
  1407. }
  1408. if (!vstate.IsIntScalarOrVectorType(type_id) &&
  1409. !vstate.IsFloatScalarOrVectorType(type_id)) {
  1410. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1411. << "Component decoration specified for type "
  1412. << vstate.getIdName(type_id) << " that is not a scalar or vector";
  1413. }
  1414. // For 16-, and 32-bit types, it is invalid if this sequence of components
  1415. // gets larger than 3.
  1416. const auto bit_width = vstate.GetBitWidth(type_id);
  1417. if (bit_width == 16 || bit_width == 32) {
  1418. assert(decoration.params().size() == 1 &&
  1419. "Grammar ensures Component has one parameter");
  1420. const auto component = decoration.params()[0];
  1421. const auto last_component = component + vstate.GetDimension(type_id) - 1;
  1422. if (last_component > 3) {
  1423. return vstate.diag(SPV_ERROR_INVALID_ID, &inst)
  1424. << "Sequence of components starting with " << component
  1425. << " and ending with " << last_component
  1426. << " gets larger than 3";
  1427. }
  1428. }
  1429. }
  1430. return SPV_SUCCESS;
  1431. }
  1432. #define PASS_OR_BAIL_AT_LINE(X, LINE) \
  1433. { \
  1434. spv_result_t e##LINE = (X); \
  1435. if (e##LINE != SPV_SUCCESS) return e##LINE; \
  1436. }
  1437. #define PASS_OR_BAIL(X) PASS_OR_BAIL_AT_LINE(X, __LINE__)
  1438. // Check rules for decorations where we start from the decoration rather
  1439. // than the decorated object. Assumes each decoration on a group have been
  1440. // propagated down to the group members.
  1441. spv_result_t CheckDecorationsFromDecoration(ValidationState_t& vstate) {
  1442. // Some rules are only checked for shaders.
  1443. const bool is_shader = vstate.HasCapability(SpvCapabilityShader);
  1444. for (const auto& kv : vstate.id_decorations()) {
  1445. const uint32_t id = kv.first;
  1446. const auto& decorations = kv.second;
  1447. if (decorations.empty()) continue;
  1448. const Instruction* inst = vstate.FindDef(id);
  1449. assert(inst);
  1450. // We assume the decorations applied to a decoration group have already
  1451. // been propagated down to the group members.
  1452. if (inst->opcode() == SpvOpDecorationGroup) continue;
  1453. for (const auto& decoration : decorations) {
  1454. switch (decoration.dec_type()) {
  1455. case SpvDecorationComponent:
  1456. PASS_OR_BAIL(CheckComponentDecoration(vstate, *inst, decoration));
  1457. break;
  1458. case SpvDecorationFPRoundingMode:
  1459. if (is_shader)
  1460. PASS_OR_BAIL(CheckFPRoundingModeForShaders(vstate, *inst));
  1461. break;
  1462. case SpvDecorationNonWritable:
  1463. PASS_OR_BAIL(CheckNonWritableDecoration(vstate, *inst, decoration));
  1464. break;
  1465. case SpvDecorationUniform:
  1466. case SpvDecorationUniformId:
  1467. PASS_OR_BAIL(CheckUniformDecoration(vstate, *inst, decoration));
  1468. break;
  1469. case SpvDecorationNoSignedWrap:
  1470. case SpvDecorationNoUnsignedWrap:
  1471. PASS_OR_BAIL(CheckIntegerWrapDecoration(vstate, *inst, decoration));
  1472. break;
  1473. default:
  1474. break;
  1475. }
  1476. }
  1477. }
  1478. return SPV_SUCCESS;
  1479. }
  1480. } // namespace
  1481. spv_result_t ValidateDecorations(ValidationState_t& vstate) {
  1482. if (auto error = CheckImportedVariableInitialization(vstate)) return error;
  1483. if (auto error = CheckDecorationsOfEntryPoints(vstate)) return error;
  1484. if (auto error = CheckDecorationsOfBuffers(vstate)) return error;
  1485. if (auto error = CheckDecorationsCompatibility(vstate)) return error;
  1486. if (auto error = CheckLinkageAttrOfFunctions(vstate)) return error;
  1487. if (auto error = CheckVulkanMemoryModelDeprecatedDecorations(vstate))
  1488. return error;
  1489. if (auto error = CheckDecorationsFromDecoration(vstate)) return error;
  1490. return SPV_SUCCESS;
  1491. }
  1492. } // namespace val
  1493. } // namespace spvtools