struct_packing_pass.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. // Copyright (c) 2024 Epic Games, 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 "struct_packing_pass.h"
  15. #include <algorithm>
  16. #include "source/opt/instruction.h"
  17. #include "source/opt/ir_context.h"
  18. namespace spvtools {
  19. namespace opt {
  20. /*
  21. Std140 packing rules from the original GLSL 140 specification (see
  22. https://registry.khronos.org/OpenGL/extensions/ARB/ARB_uniform_buffer_object.txt)
  23. When using the "std140" storage layout, structures will be laid out in
  24. buffer storage with its members stored in monotonically increasing order
  25. based on their location in the declaration. A structure and each
  26. structure member have a base offset and a base alignment, from which an
  27. aligned offset is computed by rounding the base offset up to a multiple of
  28. the base alignment. The base offset of the first member of a structure is
  29. taken from the aligned offset of the structure itself. The base offset of
  30. all other structure members is derived by taking the offset of the last
  31. basic machine unit consumed by the previous member and adding one. Each
  32. structure member is stored in memory at its aligned offset. The members
  33. of a top-level uniform block are laid out in buffer storage by treating
  34. the uniform block as a structure with a base offset of zero.
  35. (1) If the member is a scalar consuming <N> basic machine units, the
  36. base alignment is <N>.
  37. (2) If the member is a two- or four-component vector with components
  38. consuming <N> basic machine units, the base alignment is 2<N> or
  39. 4<N>, respectively.
  40. (3) If the member is a three-component vector with components consuming
  41. <N> basic machine units, the base alignment is 4<N>.
  42. (4) If the member is an array of scalars or vectors, the base alignment
  43. and array stride are set to match the base alignment of a single
  44. array element, according to rules (1), (2), and (3), and rounded up
  45. to the base alignment of a vec4. The array may have padding at the
  46. end; the base offset of the member following the array is rounded up
  47. to the next multiple of the base alignment.
  48. (5) If the member is a column-major matrix with <C> columns and <R>
  49. rows, the matrix is stored identically to an array of <C> column
  50. vectors with <R> components each, according to rule (4).
  51. (6) If the member is an array of <S> column-major matrices with <C>
  52. columns and <R> rows, the matrix is stored identically to a row of
  53. <S>*<C> column vectors with <R> components each, according to rule
  54. (4).
  55. (7) If the member is a row-major matrix with <C> columns and <R> rows,
  56. the matrix is stored identically to an array of <R> row vectors
  57. with <C> components each, according to rule (4).
  58. (8) If the member is an array of <S> row-major matrices with <C> columns
  59. and <R> rows, the matrix is stored identically to a row of <S>*<R>
  60. row vectors with <C> components each, according to rule (4).
  61. (9) If the member is a structure, the base alignment of the structure is
  62. <N>, where <N> is the largest base alignment value of any of its
  63. members, and rounded up to the base alignment of a vec4. The
  64. individual members of this sub-structure are then assigned offsets
  65. by applying this set of rules recursively, where the base offset of
  66. the first member of the sub-structure is equal to the aligned offset
  67. of the structure. The structure may have padding at the end; the
  68. base offset of the member following the sub-structure is rounded up
  69. to the next multiple of the base alignment of the structure.
  70. (10) If the member is an array of <S> structures, the <S> elements of
  71. the array are laid out in order, according to rule (9).
  72. */
  73. static bool isPackingVec4Padded(StructPackingPass::PackingRules rules) {
  74. switch (rules) {
  75. case StructPackingPass::PackingRules::Std140:
  76. case StructPackingPass::PackingRules::Std140EnhancedLayout:
  77. case StructPackingPass::PackingRules::HlslCbuffer:
  78. case StructPackingPass::PackingRules::HlslCbufferPackOffset:
  79. return true;
  80. default:
  81. return false;
  82. }
  83. }
  84. static bool isPackingScalar(StructPackingPass::PackingRules rules) {
  85. switch (rules) {
  86. case StructPackingPass::PackingRules::Scalar:
  87. case StructPackingPass::PackingRules::ScalarEnhancedLayout:
  88. return true;
  89. default:
  90. return false;
  91. }
  92. }
  93. static bool isPackingHlsl(StructPackingPass::PackingRules rules) {
  94. switch (rules) {
  95. case StructPackingPass::PackingRules::HlslCbuffer:
  96. case StructPackingPass::PackingRules::HlslCbufferPackOffset:
  97. return true;
  98. default:
  99. return false;
  100. }
  101. }
  102. static uint32_t getPackedBaseSize(const analysis::Type& type) {
  103. switch (type.kind()) {
  104. case analysis::Type::kBool:
  105. return 1;
  106. case analysis::Type::kInteger:
  107. return type.AsInteger()->width() / 8;
  108. case analysis::Type::kFloat:
  109. return type.AsFloat()->width() / 8;
  110. case analysis::Type::kVector:
  111. return getPackedBaseSize(*type.AsVector()->element_type());
  112. case analysis::Type::kMatrix:
  113. return getPackedBaseSize(*type.AsMatrix()->element_type());
  114. default:
  115. break; // we only expect bool, int, float, vec, and mat here
  116. }
  117. assert(0 && "Unrecognized type to get base size");
  118. return 0;
  119. }
  120. static uint32_t getScalarElementCount(const analysis::Type& type) {
  121. switch (type.kind()) {
  122. case analysis::Type::kVector:
  123. return type.AsVector()->element_count();
  124. case analysis::Type::kMatrix:
  125. return getScalarElementCount(*type.AsMatrix()->element_type());
  126. case analysis::Type::kStruct:
  127. assert(0 && "getScalarElementCount() does not recognized struct types");
  128. return 0;
  129. default:
  130. return 1;
  131. }
  132. }
  133. // Aligns the specified value to a multiple of alignment, whereas the
  134. // alignment must be a power-of-two.
  135. static uint32_t alignPow2(uint32_t value, uint32_t alignment) {
  136. return (value + alignment - 1) & ~(alignment - 1);
  137. }
  138. void StructPackingPass::buildConstantsMap() {
  139. constantsMap_.clear();
  140. for (Instruction* instr : context()->module()->GetConstants()) {
  141. constantsMap_[instr->result_id()] = instr;
  142. }
  143. }
  144. uint32_t StructPackingPass::getPackedAlignment(
  145. const analysis::Type& type) const {
  146. switch (type.kind()) {
  147. case analysis::Type::kArray: {
  148. // Get alignment of base type and round up to minimum alignment
  149. const uint32_t minAlignment = isPackingVec4Padded(packingRules_) ? 16 : 1;
  150. return std::max<uint32_t>(
  151. minAlignment, getPackedAlignment(*type.AsArray()->element_type()));
  152. }
  153. case analysis::Type::kStruct: {
  154. // Rule 9. Struct alignment is maximum alignmnet of its members
  155. uint32_t alignment = 1;
  156. for (const analysis::Type* elementType :
  157. type.AsStruct()->element_types()) {
  158. alignment =
  159. std::max<uint32_t>(alignment, getPackedAlignment(*elementType));
  160. }
  161. if (isPackingVec4Padded(packingRules_))
  162. alignment = std::max<uint32_t>(alignment, 16u);
  163. return alignment;
  164. }
  165. default: {
  166. const uint32_t baseAlignment = getPackedBaseSize(type);
  167. // Scalar block layout always uses alignment for the most basic component
  168. if (isPackingScalar(packingRules_)) return baseAlignment;
  169. if (const analysis::Matrix* matrixType = type.AsMatrix()) {
  170. // Rule 5/7
  171. if (isPackingVec4Padded(packingRules_) ||
  172. matrixType->element_count() == 3)
  173. return baseAlignment * 4;
  174. else
  175. return baseAlignment * matrixType->element_count();
  176. } else if (const analysis::Vector* vectorType = type.AsVector()) {
  177. // Rule 1
  178. if (vectorType->element_count() == 1) return baseAlignment;
  179. // Rule 2
  180. if (vectorType->element_count() == 2 ||
  181. vectorType->element_count() == 4)
  182. return baseAlignment * vectorType->element_count();
  183. // Rule 3
  184. if (vectorType->element_count() == 3) return baseAlignment * 4;
  185. } else {
  186. // Rule 1
  187. return baseAlignment;
  188. }
  189. }
  190. }
  191. assert(0 && "Unrecognized type to get packed alignment");
  192. return 0;
  193. }
  194. static uint32_t getPadAlignment(const analysis::Type& type,
  195. uint32_t packedAlignment) {
  196. // The next member following a struct member is aligned to the base alignment
  197. // of a previous struct member.
  198. return type.kind() == analysis::Type::kStruct ? packedAlignment : 1;
  199. }
  200. uint32_t StructPackingPass::getPackedSize(const analysis::Type& type) const {
  201. switch (type.kind()) {
  202. case analysis::Type::kArray: {
  203. if (const analysis::Array* arrayType = type.AsArray()) {
  204. uint32_t size =
  205. getPackedArrayStride(*arrayType) * getArrayLength(*arrayType);
  206. // For arrays of vector and matrices in HLSL, the last element has a
  207. // size depending on its vector/matrix size to allow packing other
  208. // vectors in the last element.
  209. const analysis::Type* arraySubType = arrayType->element_type();
  210. if (isPackingHlsl(packingRules_) &&
  211. arraySubType->kind() != analysis::Type::kStruct) {
  212. size -= (4 - getScalarElementCount(*arraySubType)) *
  213. getPackedBaseSize(*arraySubType);
  214. }
  215. return size;
  216. }
  217. break;
  218. }
  219. case analysis::Type::kStruct: {
  220. uint32_t size = 0;
  221. uint32_t padAlignment = 1;
  222. for (const analysis::Type* memberType :
  223. type.AsStruct()->element_types()) {
  224. const uint32_t packedAlignment = getPackedAlignment(*memberType);
  225. const uint32_t alignment =
  226. std::max<uint32_t>(packedAlignment, padAlignment);
  227. padAlignment = getPadAlignment(*memberType, packedAlignment);
  228. size = alignPow2(size, alignment);
  229. size += getPackedSize(*memberType);
  230. }
  231. return size;
  232. }
  233. default: {
  234. const uint32_t baseAlignment = getPackedBaseSize(type);
  235. if (isPackingScalar(packingRules_)) {
  236. return getScalarElementCount(type) * baseAlignment;
  237. } else {
  238. uint32_t size = 0;
  239. if (const analysis::Matrix* matrixType = type.AsMatrix()) {
  240. const analysis::Vector* matrixSubType =
  241. matrixType->element_type()->AsVector();
  242. assert(matrixSubType != nullptr &&
  243. "Matrix sub-type is expected to be a vector type");
  244. if (isPackingVec4Padded(packingRules_) ||
  245. matrixType->element_count() == 3)
  246. size = matrixSubType->element_count() * baseAlignment * 4;
  247. else
  248. size = matrixSubType->element_count() * baseAlignment *
  249. matrixType->element_count();
  250. // For matrices in HLSL, the last element has a size depending on its
  251. // vector size to allow packing other vectors in the last element.
  252. if (isPackingHlsl(packingRules_)) {
  253. size -= (4 - matrixSubType->element_count()) *
  254. getPackedBaseSize(*matrixSubType);
  255. }
  256. } else if (const analysis::Vector* vectorType = type.AsVector()) {
  257. size = vectorType->element_count() * baseAlignment;
  258. } else {
  259. size = baseAlignment;
  260. }
  261. return size;
  262. }
  263. }
  264. }
  265. assert(0 && "Unrecognized type to get packed size");
  266. return 0;
  267. }
  268. uint32_t StructPackingPass::getPackedArrayStride(
  269. const analysis::Array& arrayType) const {
  270. // Array stride is equal to aligned size of element type
  271. const uint32_t elementSize = getPackedSize(*arrayType.element_type());
  272. const uint32_t alignment = getPackedAlignment(arrayType);
  273. return alignPow2(elementSize, alignment);
  274. }
  275. uint32_t StructPackingPass::getArrayLength(
  276. const analysis::Array& arrayType) const {
  277. return getConstantInt(arrayType.LengthId());
  278. }
  279. uint32_t StructPackingPass::getConstantInt(spv::Id id) const {
  280. auto it = constantsMap_.find(id);
  281. assert(it != constantsMap_.end() &&
  282. "Failed to map SPIR-V instruction ID to constant value");
  283. [[maybe_unused]] const analysis::Type* constType =
  284. context()->get_type_mgr()->GetType(it->second->type_id());
  285. assert(constType != nullptr &&
  286. "Failed to map SPIR-V instruction result type to definition");
  287. assert(constType->kind() == analysis::Type::kInteger &&
  288. "Failed to map SPIR-V instruction result type to integer type");
  289. return it->second->GetOperand(2).words[0];
  290. }
  291. StructPackingPass::PackingRules StructPackingPass::ParsePackingRuleFromString(
  292. const std::string& s) {
  293. if (s == "std140") return PackingRules::Std140;
  294. if (s == "std140EnhancedLayout") return PackingRules::Std140EnhancedLayout;
  295. if (s == "std430") return PackingRules::Std430;
  296. if (s == "std430EnhancedLayout") return PackingRules::Std430EnhancedLayout;
  297. if (s == "hlslCbuffer") return PackingRules::HlslCbuffer;
  298. if (s == "hlslCbufferPackOffset") return PackingRules::HlslCbufferPackOffset;
  299. if (s == "scalar") return PackingRules::Scalar;
  300. if (s == "scalarEnhancedLayout") return PackingRules::ScalarEnhancedLayout;
  301. return PackingRules::Undefined;
  302. }
  303. StructPackingPass::StructPackingPass(const char* structToPack,
  304. PackingRules rules)
  305. : structToPack_{structToPack != nullptr ? structToPack : ""},
  306. packingRules_{rules} {}
  307. Pass::Status StructPackingPass::Process() {
  308. if (packingRules_ == PackingRules::Undefined) {
  309. if (consumer()) {
  310. consumer()(SPV_MSG_ERROR, "", {0, 0, 0},
  311. "Cannot pack struct with undefined rule");
  312. }
  313. return Status::Failure;
  314. }
  315. // Build Id-to-instruction map for easier access
  316. buildConstantsMap();
  317. // Find structure of interest
  318. const uint32_t structIdToPack = findStructIdByName(structToPack_.c_str());
  319. const Instruction* structDef =
  320. context()->get_def_use_mgr()->GetDef(structIdToPack);
  321. if (structDef == nullptr || structDef->opcode() != spv::Op::OpTypeStruct) {
  322. if (consumer()) {
  323. const std::string message =
  324. "Failed to find struct with name " + structToPack_;
  325. consumer()(SPV_MSG_ERROR, "", {0, 0, 0}, message.c_str());
  326. }
  327. return Status::Failure;
  328. }
  329. // Find all struct member types
  330. std::vector<const analysis::Type*> structMemberTypes =
  331. findStructMemberTypes(*structDef);
  332. return assignStructMemberOffsets(structIdToPack, structMemberTypes);
  333. }
  334. uint32_t StructPackingPass::findStructIdByName(const char* structName) const {
  335. for (Instruction& instr : context()->module()->debugs2()) {
  336. if (instr.opcode() == spv::Op::OpName &&
  337. instr.GetOperand(1).AsString() == structName) {
  338. return instr.GetOperand(0).AsId();
  339. }
  340. }
  341. return 0;
  342. }
  343. std::vector<const analysis::Type*> StructPackingPass::findStructMemberTypes(
  344. const Instruction& structDef) const {
  345. // Found struct type to pack, now collect all types of its members
  346. assert(structDef.NumOperands() > 0 &&
  347. "Number of operands in OpTypeStruct instruction must not be zero");
  348. const uint32_t numMembers = structDef.NumOperands() - 1;
  349. std::vector<const analysis::Type*> structMemberTypes;
  350. structMemberTypes.resize(numMembers);
  351. for (uint32_t i = 0; i < numMembers; ++i) {
  352. const spv::Id memberTypeId = structDef.GetOperand(1 + i).AsId();
  353. if (const analysis::Type* memberType =
  354. context()->get_type_mgr()->GetType(memberTypeId)) {
  355. structMemberTypes[i] = memberType;
  356. }
  357. }
  358. return structMemberTypes;
  359. }
  360. Pass::Status StructPackingPass::assignStructMemberOffsets(
  361. uint32_t structIdToPack,
  362. const std::vector<const analysis::Type*>& structMemberTypes) {
  363. // Returns true if the specified instruction is a OpMemberDecorate for the
  364. // struct we're looking for with an offset decoration
  365. auto isMemberOffsetDecoration =
  366. [structIdToPack](const Instruction& instr) -> bool {
  367. return instr.opcode() == spv::Op::OpMemberDecorate &&
  368. instr.GetOperand(0).AsId() == structIdToPack &&
  369. static_cast<spv::Decoration>(instr.GetOperand(2).words[0]) ==
  370. spv::Decoration::Offset;
  371. };
  372. bool modified = false;
  373. // Find and re-assign all member offset decorations
  374. for (auto it = context()->module()->annotation_begin(),
  375. itEnd = context()->module()->annotation_end();
  376. it != itEnd; ++it) {
  377. if (isMemberOffsetDecoration(*it)) {
  378. // Found first member decoration with offset, we expect all other
  379. // offsets right after the first one
  380. uint32_t prevMemberIndex = 0;
  381. uint32_t currentOffset = 0;
  382. uint32_t padAlignment = 1;
  383. do {
  384. const uint32_t memberIndex = it->GetOperand(1).words[0];
  385. if (memberIndex < prevMemberIndex) {
  386. // Failure: we expect all members to appear in consecutive order
  387. return Status::Failure;
  388. }
  389. // Apply alignment rules to current offset
  390. const analysis::Type& memberType = *structMemberTypes[memberIndex];
  391. uint32_t packedAlignment = getPackedAlignment(memberType);
  392. uint32_t packedSize = getPackedSize(memberType);
  393. if (isPackingHlsl(packingRules_)) {
  394. // If a member crosses vec4 boundaries, alignment is size of vec4
  395. if (currentOffset / 16 != (currentOffset + packedSize - 1) / 16)
  396. packedAlignment = std::max<uint32_t>(packedAlignment, 16u);
  397. }
  398. const uint32_t alignment =
  399. std::max<uint32_t>(packedAlignment, padAlignment);
  400. currentOffset = alignPow2(currentOffset, alignment);
  401. padAlignment = getPadAlignment(memberType, packedAlignment);
  402. // Override packed offset in instruction
  403. if (it->GetOperand(3).words[0] < currentOffset) {
  404. // Failure: packing resulted in higher offset for member than
  405. // previously generated
  406. return Status::Failure;
  407. }
  408. it->GetOperand(3).words[0] = currentOffset;
  409. modified = true;
  410. // Move to next member
  411. ++it;
  412. prevMemberIndex = memberIndex;
  413. currentOffset += packedSize;
  414. } while (it != itEnd && isMemberOffsetDecoration(*it));
  415. // We're done with all decorations for the struct of interest
  416. break;
  417. }
  418. }
  419. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  420. }
  421. } // namespace opt
  422. } // namespace spvtools