Coverage Report

Created: 2025-06-13 06:49

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