xref: /aosp_15_r20/external/angle/src/compiler/translator/tree_ops/glsl/apple/RewriteRowMajorMatrices.cpp (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1 //
2 // Copyright 2019 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // RewriteRowMajorMatrices: Rewrite row-major matrices as column-major.
7 //
8 
9 #include "compiler/translator/tree_ops/glsl/apple/RewriteRowMajorMatrices.h"
10 
11 #include "compiler/translator/Compiler.h"
12 #include "compiler/translator/ImmutableStringBuilder.h"
13 #include "compiler/translator/StaticType.h"
14 #include "compiler/translator/SymbolTable.h"
15 #include "compiler/translator/tree_util/IntermNode_util.h"
16 #include "compiler/translator/tree_util/IntermTraverse.h"
17 #include "compiler/translator/tree_util/ReplaceVariable.h"
18 
19 namespace sh
20 {
21 namespace
22 {
23 // Only structs with matrices are tracked.  If layout(row_major) is applied to a struct that doesn't
24 // have matrices, it's silently dropped.  This is also used to avoid creating duplicates for inner
25 // structs that don't have matrices.
26 struct StructConversionData
27 {
28     // The converted struct with every matrix transposed.
29     TStructure *convertedStruct = nullptr;
30 
31     // The copy-from and copy-to functions copying from a struct to its converted version and back.
32     TFunction *copyFromOriginal = nullptr;
33     TFunction *copyToOriginal   = nullptr;
34 };
35 
DoesFieldContainRowMajorMatrix(const TField * field,bool isBlockRowMajor)36 bool DoesFieldContainRowMajorMatrix(const TField *field, bool isBlockRowMajor)
37 {
38     TLayoutMatrixPacking matrixPacking = field->type()->getLayoutQualifier().matrixPacking;
39 
40     // The field is row major if either explicitly specified as such, or if it inherits it from the
41     // block layout qualifier.
42     if (matrixPacking == EmpColumnMajor || (matrixPacking == EmpUnspecified && !isBlockRowMajor))
43     {
44         return false;
45     }
46 
47     // The field is qualified with row_major, but if it's not a matrix or a struct containing
48     // matrices, that's a useless qualifier.
49     const TType *type = field->type();
50     return type->isMatrix() || type->isStructureContainingMatrices();
51 }
52 
DuplicateField(const TField * field)53 TField *DuplicateField(const TField *field)
54 {
55     return new TField(new TType(*field->type()), field->name(), field->line(), field->symbolType());
56 }
57 
SetColumnMajor(TType * type)58 void SetColumnMajor(TType *type)
59 {
60     TLayoutQualifier layoutQualifier = type->getLayoutQualifier();
61     layoutQualifier.matrixPacking    = EmpColumnMajor;
62     type->setLayoutQualifier(layoutQualifier);
63 }
64 
TransposeMatrixType(const TType * type)65 TType *TransposeMatrixType(const TType *type)
66 {
67     TType *newType = new TType(*type);
68 
69     SetColumnMajor(newType);
70 
71     newType->setPrimarySize(type->getRows());
72     newType->setSecondarySize(type->getCols());
73 
74     return newType;
75 }
76 
CopyArraySizes(const TType * from,TType * to)77 void CopyArraySizes(const TType *from, TType *to)
78 {
79     if (from->isArray())
80     {
81         to->makeArrays(from->getArraySizes());
82     }
83 }
84 
85 // Determine if the node is an index node (array index or struct field selection).  For the purposes
86 // of this transformation, swizzle nodes are considered index nodes too.
IsIndexNode(TIntermNode * node,TIntermNode * child)87 bool IsIndexNode(TIntermNode *node, TIntermNode *child)
88 {
89     if (node->getAsSwizzleNode())
90     {
91         return true;
92     }
93 
94     TIntermBinary *binaryNode = node->getAsBinaryNode();
95     if (binaryNode == nullptr || child != binaryNode->getLeft())
96     {
97         return false;
98     }
99 
100     TOperator op = binaryNode->getOp();
101 
102     return op == EOpIndexDirect || op == EOpIndexDirectInterfaceBlock ||
103            op == EOpIndexDirectStruct || op == EOpIndexIndirect;
104 }
105 
CopyToTempVariable(TSymbolTable * symbolTable,TIntermTyped * node,TIntermSequence * prependStatements)106 TIntermSymbol *CopyToTempVariable(TSymbolTable *symbolTable,
107                                   TIntermTyped *node,
108                                   TIntermSequence *prependStatements)
109 {
110     TVariable *temp              = CreateTempVariable(symbolTable, &node->getType(), EvqTemporary);
111     TIntermDeclaration *tempDecl = CreateTempInitDeclarationNode(temp, node);
112     prependStatements->push_back(tempDecl);
113 
114     return new TIntermSymbol(temp);
115 }
116 
CreateStructCopyCall(const TFunction * copyFunc,TIntermTyped * expression)117 TIntermAggregate *CreateStructCopyCall(const TFunction *copyFunc, TIntermTyped *expression)
118 {
119     TIntermSequence args = {expression};
120     return TIntermAggregate::CreateFunctionCall(*copyFunc, &args);
121 }
122 
CreateTransposeCall(TSymbolTable * symbolTable,TIntermTyped * expression)123 TIntermTyped *CreateTransposeCall(TSymbolTable *symbolTable, TIntermTyped *expression)
124 {
125     TIntermSequence args = {expression};
126     return CreateBuiltInFunctionCallNode("transpose", &args, *symbolTable, 300);
127 }
128 
GetIndex(TSymbolTable * symbolTable,TIntermNode * node,TIntermSequence * indices,TIntermSequence * prependStatements)129 TOperator GetIndex(TSymbolTable *symbolTable,
130                    TIntermNode *node,
131                    TIntermSequence *indices,
132                    TIntermSequence *prependStatements)
133 {
134     // Swizzle nodes are converted EOpIndexDirect for simplicity, with one index per swizzle
135     // channel.
136     TIntermSwizzle *asSwizzle = node->getAsSwizzleNode();
137     if (asSwizzle)
138     {
139         for (int channel : asSwizzle->getSwizzleOffsets())
140         {
141             indices->push_back(CreateIndexNode(channel));
142         }
143         return EOpIndexDirect;
144     }
145 
146     TIntermBinary *binaryNode = node->getAsBinaryNode();
147     ASSERT(binaryNode);
148 
149     TOperator op = binaryNode->getOp();
150     ASSERT(op == EOpIndexDirect || op == EOpIndexDirectInterfaceBlock ||
151            op == EOpIndexDirectStruct || op == EOpIndexIndirect);
152 
153     TIntermTyped *rhs = binaryNode->getRight()->deepCopy();
154     if (rhs->getAsConstantUnion() == nullptr)
155     {
156         rhs = CopyToTempVariable(symbolTable, rhs, prependStatements);
157     }
158 
159     indices->push_back(rhs);
160     return op;
161 }
162 
ReplicateIndexNode(TSymbolTable * symbolTable,TIntermNode * node,TIntermTyped * lhs,TIntermSequence * indices)163 TIntermTyped *ReplicateIndexNode(TSymbolTable *symbolTable,
164                                  TIntermNode *node,
165                                  TIntermTyped *lhs,
166                                  TIntermSequence *indices)
167 {
168     TIntermSwizzle *asSwizzle = node->getAsSwizzleNode();
169     if (asSwizzle)
170     {
171         return new TIntermSwizzle(lhs, asSwizzle->getSwizzleOffsets());
172     }
173 
174     TIntermBinary *binaryNode = node->getAsBinaryNode();
175     ASSERT(binaryNode);
176 
177     ASSERT(indices->size() == 1);
178     TIntermTyped *rhs = indices->front()->getAsTyped();
179 
180     return new TIntermBinary(binaryNode->getOp(), lhs, rhs);
181 }
182 
GetIndexOp(TIntermNode * node)183 TOperator GetIndexOp(TIntermNode *node)
184 {
185     return node->getAsConstantUnion() ? EOpIndexDirect : EOpIndexIndirect;
186 }
187 
IsConvertedField(TIntermTyped * indexNode,const angle::HashMap<const TField *,bool> & convertedFields)188 bool IsConvertedField(TIntermTyped *indexNode,
189                       const angle::HashMap<const TField *, bool> &convertedFields)
190 {
191     TIntermBinary *asBinary = indexNode->getAsBinaryNode();
192     if (asBinary == nullptr)
193     {
194         return false;
195     }
196 
197     if (asBinary->getOp() != EOpIndexDirectInterfaceBlock)
198     {
199         return false;
200     }
201 
202     const TInterfaceBlock *interfaceBlock = asBinary->getLeft()->getType().getInterfaceBlock();
203     ASSERT(interfaceBlock);
204 
205     TIntermConstantUnion *fieldIndexNode = asBinary->getRight()->getAsConstantUnion();
206     ASSERT(fieldIndexNode);
207     ASSERT(fieldIndexNode->getConstantValue() != nullptr);
208 
209     int fieldIndex      = fieldIndexNode->getConstantValue()->getIConst();
210     const TField *field = interfaceBlock->fields()[fieldIndex];
211 
212     return convertedFields.count(field) > 0 && convertedFields.at(field);
213 }
214 
215 // A helper class to transform expressions of array type.  Iterates over every element of the
216 // array.
217 class TransformArrayHelper
218 {
219   public:
TransformArrayHelper(TIntermTyped * baseExpression)220     TransformArrayHelper(TIntermTyped *baseExpression)
221         : mBaseExpression(baseExpression),
222           mBaseExpressionType(baseExpression->getType()),
223           mArrayIndices(mBaseExpressionType.getArraySizes().size(), 0)
224     {}
225 
getNextElement(TIntermTyped * valueExpression,TIntermTyped ** valueElementOut)226     TIntermTyped *getNextElement(TIntermTyped *valueExpression, TIntermTyped **valueElementOut)
227     {
228         const TSpan<const unsigned int> &arraySizes = mBaseExpressionType.getArraySizes();
229 
230         // If the last index overflows, element enumeration is done.
231         if (mArrayIndices.back() >= arraySizes.back())
232         {
233             return nullptr;
234         }
235 
236         TIntermTyped *element = getCurrentElement(mBaseExpression);
237         if (valueExpression)
238         {
239             *valueElementOut = getCurrentElement(valueExpression);
240         }
241 
242         incrementIndices(arraySizes);
243         return element;
244     }
245 
accumulateForRead(TSymbolTable * symbolTable,TIntermTyped * transformedElement,TIntermSequence * prependStatements)246     void accumulateForRead(TSymbolTable *symbolTable,
247                            TIntermTyped *transformedElement,
248                            TIntermSequence *prependStatements)
249     {
250         TIntermTyped *temp = CopyToTempVariable(symbolTable, transformedElement, prependStatements);
251         mReadTransformConstructorArgs.push_back(temp);
252     }
253 
constructReadTransformExpression()254     TIntermTyped *constructReadTransformExpression()
255     {
256         const TSpan<const unsigned int> &baseTypeArraySizes = mBaseExpressionType.getArraySizes();
257         TVector<unsigned int> arraySizes(baseTypeArraySizes.begin(), baseTypeArraySizes.end());
258         TIntermTyped *firstElement = mReadTransformConstructorArgs.front()->getAsTyped();
259         const TType &baseType      = firstElement->getType();
260 
261         // If N dimensions, acc[0] == size[0] and acc[i] == size[i] * acc[i-1].
262         // The last value is unused, and is not present.
263         TVector<unsigned int> accumulatedArraySizes(arraySizes.size() - 1);
264 
265         if (accumulatedArraySizes.size() > 0)
266         {
267             accumulatedArraySizes[0] = arraySizes[0];
268         }
269         for (size_t index = 1; index + 1 < arraySizes.size(); ++index)
270         {
271             accumulatedArraySizes[index] = accumulatedArraySizes[index - 1] * arraySizes[index];
272         }
273 
274         return constructReadTransformExpressionHelper(arraySizes, accumulatedArraySizes, baseType,
275                                                       0);
276     }
277 
278   private:
getCurrentElement(TIntermTyped * expression)279     TIntermTyped *getCurrentElement(TIntermTyped *expression)
280     {
281         TIntermTyped *element = expression->deepCopy();
282         for (auto it = mArrayIndices.rbegin(); it != mArrayIndices.rend(); ++it)
283         {
284             unsigned int index = *it;
285             element            = new TIntermBinary(EOpIndexDirect, element, CreateIndexNode(index));
286         }
287         return element;
288     }
289 
incrementIndices(const TSpan<const unsigned int> & arraySizes)290     void incrementIndices(const TSpan<const unsigned int> &arraySizes)
291     {
292         // Assume mArrayIndices is an N digit number, where digit i is in the range
293         // [0, arraySizes[i]).  This function increments this number.  Last digit is the most
294         // significant digit.
295         for (size_t digitIndex = 0; digitIndex < arraySizes.size(); ++digitIndex)
296         {
297             ++mArrayIndices[digitIndex];
298             if (mArrayIndices[digitIndex] < arraySizes[digitIndex])
299             {
300                 break;
301             }
302             if (digitIndex + 1 != arraySizes.size())
303             {
304                 // This digit has now overflown and is reset to 0, carry will be added to the next
305                 // digit.  The most significant digit will keep the overflow though, to make it
306                 // clear we have exhausted the range.
307                 mArrayIndices[digitIndex] = 0;
308             }
309         }
310     }
311 
constructReadTransformExpressionHelper(const TVector<unsigned int> & arraySizes,const TVector<unsigned int> & accumulatedArraySizes,const TType & baseType,size_t elementsOffset)312     TIntermTyped *constructReadTransformExpressionHelper(
313         const TVector<unsigned int> &arraySizes,
314         const TVector<unsigned int> &accumulatedArraySizes,
315         const TType &baseType,
316         size_t elementsOffset)
317     {
318         ASSERT(!arraySizes.empty());
319 
320         TType *transformedType = new TType(baseType);
321         transformedType->makeArrays(arraySizes);
322 
323         // If one dimensional, create the constructor with the given elements.
324         if (arraySizes.size() == 1)
325         {
326             ASSERT(accumulatedArraySizes.size() == 0);
327 
328             auto sliceStart = mReadTransformConstructorArgs.begin() + elementsOffset;
329             TIntermSequence slice(sliceStart, sliceStart + arraySizes[0]);
330 
331             return TIntermAggregate::CreateConstructor(*transformedType, &slice);
332         }
333 
334         // If not, create constructors for every column recursively.
335         TVector<unsigned int> subArraySizes(arraySizes.begin(), arraySizes.end() - 1);
336         TVector<unsigned int> subArrayAccumulatedSizes(accumulatedArraySizes.begin(),
337                                                        accumulatedArraySizes.end() - 1);
338 
339         TIntermSequence constructorArgs;
340         unsigned int colStride = accumulatedArraySizes.back();
341         for (size_t col = 0; col < arraySizes.back(); ++col)
342         {
343             size_t colElementsOffset = elementsOffset + col * colStride;
344 
345             constructorArgs.push_back(constructReadTransformExpressionHelper(
346                 subArraySizes, subArrayAccumulatedSizes, baseType, colElementsOffset));
347         }
348 
349         return TIntermAggregate::CreateConstructor(*transformedType, &constructorArgs);
350     }
351 
352     TIntermTyped *mBaseExpression;
353     const TType &mBaseExpressionType;
354     TVector<unsigned int> mArrayIndices;
355 
356     TIntermSequence mReadTransformConstructorArgs;
357 };
358 
359 // Traverser that:
360 //
361 // 1. Converts |layout(row_major) matCxR M| to |layout(column_major) matRxC Mt|.
362 // 2. Converts |layout(row_major) S s| to |layout(column_major) St st|, where S is a struct that
363 //    contains matrices, and St is a new struct with the transformation in 1 applied to matrix
364 //    members (recursively).
365 // 3. When read from, the following transformations are applied:
366 //
367 //            M       -> transpose(Mt)
368 //            M[c]    -> gvecN(Mt[0][c], Mt[1][c], ..., Mt[N-1][c])
369 //            M[c][r] -> Mt[r][c]
370 //            M[c].yz -> gvec2(Mt[1][c], Mt[2][c])
371 //            MArr    -> MType[D1]..[DN](transpose(MtArr[0]...[0]), ...)
372 //            s       -> copy_St_to_S(st)
373 //            sArr    -> SType[D1]...[DN](copy_St_to_S(stArr[0]..[0]), ...)
374 //            (matrix reads through struct are transformed similarly to M)
375 //
376 // 4. When written to, the following transformations are applied:
377 //
378 //      M = exp       -> Mt = transpose(exp)
379 //      M[c] = exp    -> temp = exp
380 //                       Mt[0][c] = temp[0]
381 //                       Mt[1][c] = temp[1]
382 //                       ...
383 //                       Mt[N-1][c] = temp[N-1]
384 //      M[c][r] = exp -> Mt[r][c] = exp
385 //      M[c].yz = exp -> temp = exp
386 //                       Mt[1][c] = temp[0]
387 //                       Mt[2][c] = temp[1]
388 //      MArr = exp    -> temp = exp
389 //                       Mt = MtType[D1]..[DN](temp([0]...[0]), ...)
390 //      s = exp       -> st = copy_S_to_St(exp)
391 //      sArr = exp    -> temp = exp
392 //                       St = StType[D1]...[DN](copy_S_to_St(temp[0]..[0]), ...)
393 //      (matrix writes through struct are transformed similarly to M)
394 //
395 // 5. If any of the above is passed to an `inout` parameter, both transformations are applied:
396 //
397 //            f(M[c]) -> temp = gvecN(Mt[0][c], Mt[1][c], ..., Mt[N-1][c])
398 //                       f(temp)
399 //                       Mt[0][c] = temp[0]
400 //                       Mt[1][c] = temp[1]
401 //                       ...
402 //                       Mt[N-1][c] = temp[N-1]
403 //
404 //               f(s) -> temp = copy_St_to_S(st)
405 //                       f(temp)
406 //                       st = copy_S_to_St(temp)
407 //
408 //    If passed to an `out` parameter, the `temp` parameter is simply not initialized.
409 //
410 // 6. If the expression leading to the matrix or struct has array subscripts, temp values are
411 //    created for them to avoid duplicating side effects.
412 //
413 class RewriteRowMajorMatricesTraverser : public TIntermTraverser
414 {
415   public:
RewriteRowMajorMatricesTraverser(TCompiler * compiler,TSymbolTable * symbolTable)416     RewriteRowMajorMatricesTraverser(TCompiler *compiler, TSymbolTable *symbolTable)
417         : TIntermTraverser(true, true, true, symbolTable),
418           mCompiler(compiler),
419           mStructMapOut(&mOuterPass.structMap),
420           mInterfaceBlockMap(&mOuterPass.interfaceBlockMap),
421           mInterfaceBlockFieldConvertedIn(mOuterPass.interfaceBlockFieldConverted),
422           mCopyFunctionDefinitionsOut(&mOuterPass.copyFunctionDefinitions),
423           mOuterTraverser(nullptr),
424           mInnerPassRoot(nullptr),
425           mIsProcessingInnerPassSubtree(false)
426     {}
427 
visitDeclaration(Visit visit,TIntermDeclaration * node)428     bool visitDeclaration(Visit visit, TIntermDeclaration *node) override
429     {
430         // No need to process declarations in inner passes.
431         if (mInnerPassRoot != nullptr)
432         {
433             return true;
434         }
435 
436         if (visit != PreVisit)
437         {
438             return true;
439         }
440 
441         const TIntermSequence &sequence = *(node->getSequence());
442 
443         TIntermTyped *variable = sequence.front()->getAsTyped();
444         const TType &type      = variable->getType();
445 
446         // If it's a struct declaration that has matrices, remember it.  If a row-major instance
447         // of it is created, it will have to be converted.
448         if (type.isStructSpecifier() && type.isStructureContainingMatrices())
449         {
450             const TStructure *structure = type.getStruct();
451             ASSERT(structure);
452 
453             ASSERT(mOuterPass.structMap.count(structure) == 0);
454 
455             StructConversionData structData;
456             mOuterPass.structMap[structure] = structData;
457 
458             return false;
459         }
460 
461         // If it's an interface block, it may have to be converted if it contains any row-major
462         // fields.
463         if (type.isInterfaceBlock() && type.getInterfaceBlock()->containsMatrices())
464         {
465             const TInterfaceBlock *block = type.getInterfaceBlock();
466             ASSERT(block);
467             bool isBlockRowMajor = type.getLayoutQualifier().matrixPacking == EmpRowMajor;
468 
469             const TFieldList &fields = block->fields();
470             bool anyRowMajor         = isBlockRowMajor;
471 
472             for (const TField *field : fields)
473             {
474                 if (DoesFieldContainRowMajorMatrix(field, isBlockRowMajor))
475                 {
476                     anyRowMajor = true;
477                     break;
478                 }
479             }
480 
481             if (anyRowMajor)
482             {
483                 convertInterfaceBlock(node);
484             }
485 
486             return false;
487         }
488 
489         return true;
490     }
491 
visitSymbol(TIntermSymbol * symbol)492     void visitSymbol(TIntermSymbol *symbol) override
493     {
494         // If in inner pass, only process if the symbol is under that root.
495         if (mInnerPassRoot != nullptr && !mIsProcessingInnerPassSubtree)
496         {
497             return;
498         }
499 
500         const TVariable *variable = &symbol->variable();
501         bool needsRewrite         = mInterfaceBlockMap->count(variable) != 0;
502 
503         // If it's a field of a nameless interface block, it may still need conversion.
504         if (!needsRewrite)
505         {
506             // Nameless interface block field symbols have the interface block pointer set, but are
507             // not interface blocks.
508             if (symbol->getType().getInterfaceBlock() && !variable->getType().isInterfaceBlock())
509             {
510                 needsRewrite = convertNamelessInterfaceBlockField(symbol);
511             }
512         }
513 
514         if (needsRewrite)
515         {
516             transformExpression(symbol);
517         }
518     }
519 
visitBinary(Visit visit,TIntermBinary * node)520     bool visitBinary(Visit visit, TIntermBinary *node) override
521     {
522         if (node == mInnerPassRoot)
523         {
524             // We only want to process the right-hand side of an assignment in inner passes.  When
525             // visit is InVisit, the left-hand side is already processed, and the right-hand side is
526             // next.  Set a flag to mark this duration.
527             mIsProcessingInnerPassSubtree = visit == InVisit;
528         }
529 
530         return true;
531     }
532 
getStructCopyFunctions()533     TIntermSequence *getStructCopyFunctions() { return &mOuterPass.copyFunctionDefinitions; }
534 
535   private:
536     typedef angle::HashMap<const TStructure *, StructConversionData> StructMap;
537     typedef angle::HashMap<const TVariable *, TVariable *> InterfaceBlockMap;
538     typedef angle::HashMap<const TField *, bool> InterfaceBlockFieldConverted;
539 
RewriteRowMajorMatricesTraverser(TSymbolTable * symbolTable,RewriteRowMajorMatricesTraverser * outerTraverser,InterfaceBlockMap * interfaceBlockMap,const InterfaceBlockFieldConverted & interfaceBlockFieldConverted,StructMap * structMap,TIntermSequence * copyFunctionDefinitions,TIntermBinary * innerPassRoot)540     RewriteRowMajorMatricesTraverser(
541         TSymbolTable *symbolTable,
542         RewriteRowMajorMatricesTraverser *outerTraverser,
543         InterfaceBlockMap *interfaceBlockMap,
544         const InterfaceBlockFieldConverted &interfaceBlockFieldConverted,
545         StructMap *structMap,
546         TIntermSequence *copyFunctionDefinitions,
547         TIntermBinary *innerPassRoot)
548         : TIntermTraverser(true, true, true, symbolTable),
549           mStructMapOut(structMap),
550           mInterfaceBlockMap(interfaceBlockMap),
551           mInterfaceBlockFieldConvertedIn(interfaceBlockFieldConverted),
552           mCopyFunctionDefinitionsOut(copyFunctionDefinitions),
553           mOuterTraverser(outerTraverser),
554           mInnerPassRoot(innerPassRoot),
555           mIsProcessingInnerPassSubtree(false)
556     {}
557 
convertInterfaceBlock(TIntermDeclaration * node)558     void convertInterfaceBlock(TIntermDeclaration *node)
559     {
560         ASSERT(mInnerPassRoot == nullptr);
561 
562         const TIntermSequence &sequence = *(node->getSequence());
563 
564         TIntermTyped *variableNode   = sequence.front()->getAsTyped();
565         const TType &type            = variableNode->getType();
566         const TInterfaceBlock *block = type.getInterfaceBlock();
567         ASSERT(block);
568 
569         bool isBlockRowMajor = type.getLayoutQualifier().matrixPacking == EmpRowMajor;
570 
571         // Recreate the struct with its row-major fields converted to column-major equivalents.
572         TIntermSequence newDeclarations;
573 
574         TFieldList *newFields = new TFieldList;
575         for (const TField *field : block->fields())
576         {
577             TField *newField = nullptr;
578 
579             if (DoesFieldContainRowMajorMatrix(field, isBlockRowMajor))
580             {
581                 newField = convertField(field, &newDeclarations);
582 
583                 // Remember that this field was converted.
584                 mOuterPass.interfaceBlockFieldConverted[field] = true;
585             }
586             else
587             {
588                 newField = DuplicateField(field);
589             }
590 
591             newFields->push_back(newField);
592         }
593 
594         // Create a new interface block with these fields.
595         TLayoutQualifier blockLayoutQualifier = type.getLayoutQualifier();
596         blockLayoutQualifier.matrixPacking    = EmpColumnMajor;
597 
598         TInterfaceBlock *newInterfaceBlock =
599             new TInterfaceBlock(mSymbolTable, block->name(), newFields, blockLayoutQualifier,
600                                 block->symbolType(), block->extensions());
601 
602         // Create a new declaration with the new type.  Declarations are separated at this point,
603         // so there should be only one variable here.
604         ASSERT(sequence.size() == 1);
605 
606         TType *newInterfaceBlockType =
607             new TType(newInterfaceBlock, type.getQualifier(), blockLayoutQualifier);
608 
609         TIntermDeclaration *newDeclaration = new TIntermDeclaration;
610         const TVariable *variable          = &variableNode->getAsSymbolNode()->variable();
611 
612         const TType *newType = newInterfaceBlockType;
613         if (type.isArray())
614         {
615             TType *newArrayType = new TType(*newType);
616             CopyArraySizes(&type, newArrayType);
617             newType = newArrayType;
618         }
619 
620         // If the interface block variable itself is temp, use an empty name.
621         bool variableIsTemp = variable->symbolType() == SymbolType::Empty;
622         const ImmutableString &variableName =
623             variableIsTemp ? kEmptyImmutableString : variable->name();
624 
625         TVariable *newVariable = new TVariable(mSymbolTable, variableName, newType,
626                                                variable->symbolType(), variable->extensions());
627 
628         newDeclaration->appendDeclarator(new TIntermSymbol(newVariable));
629 
630         mOuterPass.interfaceBlockMap[variable] = newVariable;
631 
632         newDeclarations.push_back(newDeclaration);
633 
634         // Replace the interface block definition with the new one, prepending any new struct
635         // definitions.
636         mMultiReplacements.emplace_back(getParentNode()->getAsBlock(), node,
637                                         std::move(newDeclarations));
638     }
639 
convertNamelessInterfaceBlockField(TIntermSymbol * symbol)640     bool convertNamelessInterfaceBlockField(TIntermSymbol *symbol)
641     {
642         const TVariable *variable             = &symbol->variable();
643         const TInterfaceBlock *interfaceBlock = symbol->getType().getInterfaceBlock();
644 
645         // Find the variable corresponding to this interface block.  If the interface block
646         // is not rewritten, or this refers to a field that is not rewritten, there's
647         // nothing to do.
648         for (auto iter : *mInterfaceBlockMap)
649         {
650             // Skip other rewritten nameless interface block fields.
651             if (!iter.first->getType().isInterfaceBlock())
652             {
653                 continue;
654             }
655 
656             // Skip if this is not a field of this rewritten interface block.
657             if (iter.first->getType().getInterfaceBlock() != interfaceBlock)
658             {
659                 continue;
660             }
661 
662             const ImmutableString symbolName = symbol->getName();
663 
664             // Find which field it is
665             const TVector<TField *> fields = interfaceBlock->fields();
666             const size_t fieldIndex        = variable->getType().getInterfaceBlockFieldIndex();
667             ASSERT(fieldIndex < fields.size());
668 
669             const TField *field = fields[fieldIndex];
670             ASSERT(field->name() == symbolName);
671 
672             // If this field doesn't need a rewrite, there's nothing to do.
673             if (mInterfaceBlockFieldConvertedIn.count(field) == 0 ||
674                 !mInterfaceBlockFieldConvertedIn.at(field))
675             {
676                 break;
677             }
678 
679             // Create a new variable that references the replaced interface block.
680             TType *newType = new TType(variable->getType());
681             newType->setInterfaceBlockField(iter.second->getType().getInterfaceBlock(), fieldIndex);
682 
683             TVariable *newVariable = new TVariable(mSymbolTable, variable->name(), newType,
684                                                    variable->symbolType(), variable->extensions());
685 
686             (*mInterfaceBlockMap)[variable] = newVariable;
687 
688             return true;
689         }
690 
691         return false;
692     }
693 
convertStruct(const TStructure * structure,TIntermSequence * newDeclarations)694     void convertStruct(const TStructure *structure, TIntermSequence *newDeclarations)
695     {
696         ASSERT(mInnerPassRoot == nullptr);
697 
698         ASSERT(mOuterPass.structMap.count(structure) != 0);
699         StructConversionData *structData = &mOuterPass.structMap[structure];
700 
701         if (structData->convertedStruct)
702         {
703             return;
704         }
705 
706         TFieldList *newFields = new TFieldList;
707         for (const TField *field : structure->fields())
708         {
709             newFields->push_back(convertField(field, newDeclarations));
710         }
711 
712         // Create unique names for the converted structs.  We can't leave them nameless and have
713         // a name autogenerated similar to temp variables, as nameless structs exist.  A fake
714         // variable is created for the sole purpose of generating a temp name.
715         TVariable *newStructTypeName =
716             new TVariable(mSymbolTable, kEmptyImmutableString,
717                           StaticType::GetBasic<EbtUInt, EbpUndefined>(), SymbolType::Empty);
718 
719         TStructure *newStruct = new TStructure(mSymbolTable, newStructTypeName->name(), newFields,
720                                                SymbolType::AngleInternal);
721         TType *newType        = new TType(newStruct, true);
722         TVariable *newStructVar =
723             new TVariable(mSymbolTable, kEmptyImmutableString, newType, SymbolType::Empty);
724 
725         TIntermDeclaration *structDecl = new TIntermDeclaration;
726         structDecl->appendDeclarator(new TIntermSymbol(newStructVar));
727 
728         newDeclarations->push_back(structDecl);
729 
730         structData->convertedStruct = newStruct;
731     }
732 
convertField(const TField * field,TIntermSequence * newDeclarations)733     TField *convertField(const TField *field, TIntermSequence *newDeclarations)
734     {
735         ASSERT(mInnerPassRoot == nullptr);
736 
737         TField *newField = nullptr;
738 
739         const TType *fieldType = field->type();
740         TType *newType         = nullptr;
741 
742         if (fieldType->isStructureContainingMatrices())
743         {
744             // If the field is a struct instance, convert the struct and replace the field
745             // with an instance of the new struct.
746             const TStructure *fieldTypeStruct = fieldType->getStruct();
747             convertStruct(fieldTypeStruct, newDeclarations);
748 
749             StructConversionData &structData = mOuterPass.structMap[fieldTypeStruct];
750             newType                          = new TType(structData.convertedStruct, false);
751             SetColumnMajor(newType);
752             CopyArraySizes(fieldType, newType);
753         }
754         else if (fieldType->isMatrix())
755         {
756             // If the field is a matrix, transpose the matrix and replace the field with
757             // that, removing the matrix packing qualifier.
758             newType = TransposeMatrixType(fieldType);
759         }
760 
761         if (newType)
762         {
763             newField = new TField(newType, field->name(), field->line(), field->symbolType());
764         }
765         else
766         {
767             newField = DuplicateField(field);
768         }
769 
770         return newField;
771     }
772 
determineAccess(TIntermNode * expression,TIntermNode * accessor,bool * isReadOut,bool * isWriteOut)773     void determineAccess(TIntermNode *expression,
774                          TIntermNode *accessor,
775                          bool *isReadOut,
776                          bool *isWriteOut)
777     {
778         // If passing to a function, look at whether the parameter is in, out or inout.
779         TIntermAggregate *functionCall = accessor->getAsAggregate();
780 
781         if (functionCall)
782         {
783             TIntermSequence *arguments = functionCall->getSequence();
784             for (size_t argIndex = 0; argIndex < arguments->size(); ++argIndex)
785             {
786                 if ((*arguments)[argIndex] == expression)
787                 {
788                     TQualifier qualifier = EvqParamIn;
789 
790                     // If the aggregate is not a function call, it's a constructor, and so every
791                     // argument is an input.
792                     const TFunction *function = functionCall->getFunction();
793                     if (function)
794                     {
795                         const TVariable *param = function->getParam(argIndex);
796                         qualifier              = param->getType().getQualifier();
797                     }
798 
799                     *isReadOut  = qualifier != EvqParamOut;
800                     *isWriteOut = qualifier == EvqParamOut || qualifier == EvqParamInOut;
801                     break;
802                 }
803             }
804             return;
805         }
806 
807         TIntermBinary *assignment = accessor->getAsBinaryNode();
808         if (assignment && IsAssignment(assignment->getOp()))
809         {
810             // If expression is on the right of assignment, it's being read from.
811             *isReadOut = assignment->getRight() == expression;
812             // If it's on the left of assignment, it's being written to.
813             *isWriteOut = assignment->getLeft() == expression;
814             return;
815         }
816 
817         // Any other usage is a read.
818         *isReadOut  = true;
819         *isWriteOut = false;
820     }
821 
transformExpression(TIntermSymbol * symbol)822     void transformExpression(TIntermSymbol *symbol)
823     {
824         // Walk up the parent chain while the nodes are EOpIndex* (whether array indexing or struct
825         // field selection) or swizzle and construct the replacement expression.  This traversal can
826         // lead to one of the following possibilities:
827         //
828         // - a.b[N].etc.s (struct, or struct array): copy function should be declared and used,
829         // - a.b[N].etc.M (matrix or matrix array): transpose() should be used,
830         // - a.b[N].etc.M[c] (a column): each element in column needs to be handled separately,
831         // - a.b[N].etc.M[c].yz (multiple elements): similar to whole column, but a subset of
832         //   elements,
833         // - a.b[N].etc.M[c][r] (an element): single element to handle.
834         // - a.b[N].etc.x (not struct or matrix): not modified
835         //
836         // primaryIndex will contain c, if any.  secondaryIndices will contain {0, ..., R-1}
837         // (if no [r] or swizzle), {r} (if [r]), or {1, 2} (corresponding to .yz) if any.
838         //
839         // In all cases, the base symbol is replaced.  |baseExpression| will contain everything up
840         // to (and not including) the last index/swizzle operations, i.e. a.b[N].etc.s/M/x.  Any
841         // non constant array subscript is assigned to a temp variable to avoid duplicating side
842         // effects.
843         //
844         // ---
845         //
846         // NOTE that due to the use of insertStatementsInParentBlock, cases like this will be
847         // mistranslated, and this bug is likely present in most transformations that use this
848         // feature:
849         //
850         //     if (x == 1 && a.b[x = 2].etc.M = value)
851         //
852         // which will translate to:
853         //
854         //     temp = (x = 2)
855         //     if (x == 1 && a.b[temp].etc.M = transpose(value))
856         //
857         // See http://anglebug.com/42262472.
858         //
859         TIntermTyped *baseExpression =
860             new TIntermSymbol(mInterfaceBlockMap->at(&symbol->variable()));
861         const TStructure *structure = nullptr;
862 
863         TIntermNode *primaryIndex = nullptr;
864         TIntermSequence secondaryIndices;
865 
866         // In some cases, it is necessary to prepend or append statements.  Those are captured in
867         // |prependStatements| and |appendStatements|.
868         TIntermSequence prependStatements;
869         TIntermSequence appendStatements;
870 
871         // If the expression is neither a struct or matrix, no modification is necessary.
872         // If it's a struct that doesn't have matrices, again there's no transformation necessary.
873         // If it's an interface block matrix field that didn't need to be transposed, no
874         // transpformation is necessary.
875         //
876         // In all these cases, |baseExpression| contains all of the original expression.
877         //
878         // If the starting symbol itself is a field of a nameless interface block, it needs
879         // conversion if we reach here.
880         bool requiresTransformation = !symbol->getType().isInterfaceBlock();
881 
882         uint32_t accessorIndex         = 0;
883         TIntermTyped *previousAncestor = symbol;
884         while (IsIndexNode(getAncestorNode(accessorIndex), previousAncestor))
885         {
886             TIntermTyped *ancestor = getAncestorNode(accessorIndex)->getAsTyped();
887             ASSERT(ancestor);
888 
889             const TType &previousAncestorType = previousAncestor->getType();
890 
891             TIntermSequence indices;
892             TOperator op = GetIndex(mSymbolTable, ancestor, &indices, &prependStatements);
893 
894             bool opIsIndex     = op == EOpIndexDirect || op == EOpIndexIndirect;
895             bool isArrayIndex  = opIsIndex && previousAncestorType.isArray();
896             bool isMatrixIndex = opIsIndex && previousAncestorType.isMatrix();
897 
898             // If it's a direct index in a matrix, it's the primary index.
899             bool isMatrixPrimarySubscript = isMatrixIndex && !isArrayIndex;
900             ASSERT(!isMatrixPrimarySubscript ||
901                    (primaryIndex == nullptr && secondaryIndices.empty()));
902             // If primary index is seen and the ancestor is still an index, it must be a direct
903             // index as the secondary one.  Note that if primaryIndex is set, there can only ever be
904             // one more parent of interest, and that's subscripting the second dimension.
905             bool isMatrixSecondarySubscript = primaryIndex != nullptr;
906             ASSERT(!isMatrixSecondarySubscript || (opIsIndex && !isArrayIndex));
907 
908             if (requiresTransformation && isMatrixPrimarySubscript)
909             {
910                 ASSERT(indices.size() == 1);
911                 primaryIndex = indices.front();
912 
913                 // Default the secondary indices to include every row.  If there's a secondary
914                 // subscript provided, it will override this.
915                 const uint8_t rows = previousAncestorType.getRows();
916                 for (uint8_t r = 0; r < rows; ++r)
917                 {
918                     secondaryIndices.push_back(CreateIndexNode(r));
919                 }
920             }
921             else if (isMatrixSecondarySubscript)
922             {
923                 ASSERT(requiresTransformation);
924 
925                 secondaryIndices = indices;
926 
927                 // Indices after this point are not interesting.  There can't actually be any other
928                 // index nodes.  Unlike desktop GLSL, ESSL does not support swizzles on scalars
929                 // (like M[1][2].yyy).
930                 ++accessorIndex;
931                 break;
932             }
933             else
934             {
935                 // Replicate the expression otherwise.
936                 baseExpression =
937                     ReplicateIndexNode(mSymbolTable, ancestor, baseExpression, &indices);
938 
939                 const TType &ancestorType = ancestor->getType();
940                 structure                 = ancestorType.getStruct();
941 
942                 requiresTransformation =
943                     requiresTransformation ||
944                     IsConvertedField(ancestor, mInterfaceBlockFieldConvertedIn);
945 
946                 // If we reach a point where the expression is neither a matrix-containing struct
947                 // nor a matrix, there's no transformation required.  This can happen if we decend
948                 // through a struct marked with row-major but arrive at a member that doesn't
949                 // include a matrix.
950                 if (!ancestorType.isMatrix() && !ancestorType.isStructureContainingMatrices())
951                 {
952                     requiresTransformation = false;
953                 }
954             }
955 
956             previousAncestor = ancestor;
957             ++accessorIndex;
958         }
959 
960         TIntermNode *originalExpression =
961             accessorIndex == 0 ? symbol : getAncestorNode(accessorIndex - 1);
962         TIntermNode *accessor = getAncestorNode(accessorIndex);
963 
964         // if accessor is EOpArrayLength, we don't need to perform any transformations either.
965         // Note that this only applies to unsized arrays, as the RemoveArrayLengthMethod()
966         // transformation would have removed this operation otherwise.
967         TIntermUnary *accessorAsUnary = accessor->getAsUnaryNode();
968         if (requiresTransformation && accessorAsUnary && accessorAsUnary->getOp() == EOpArrayLength)
969         {
970             ASSERT(accessorAsUnary->getOperand() == originalExpression);
971             ASSERT(accessorAsUnary->getOperand()->getType().isUnsizedArray());
972 
973             requiresTransformation = false;
974 
975             // We need to replace the whole expression including the EOpArrayLength, to avoid
976             // confusing the replacement code as the original and new expressions don't have the
977             // same type (one is the transpose of the other).  This doesn't affect the .length()
978             // operation, so this replacement is ok, though it's not worth special-casing this in
979             // the node replacement algorithm.
980             //
981             // Note: the |if (!requiresTransformation)| immediately below will be entered after
982             // this.
983             originalExpression = accessor;
984             accessor           = getAncestorNode(accessorIndex + 1);
985             baseExpression     = new TIntermUnary(EOpArrayLength, baseExpression, nullptr);
986         }
987 
988         if (!requiresTransformation)
989         {
990             ASSERT(primaryIndex == nullptr);
991             queueReplacementWithParent(accessor, originalExpression, baseExpression,
992                                        OriginalNode::IS_DROPPED);
993 
994             RewriteRowMajorMatricesTraverser *traverser = mOuterTraverser ? mOuterTraverser : this;
995             traverser->insertStatementsInParentBlock(prependStatements, appendStatements);
996             return;
997         }
998 
999         ASSERT(structure == nullptr || primaryIndex == nullptr);
1000         ASSERT(structure != nullptr || baseExpression->getType().isMatrix());
1001 
1002         // At the end, we can determine if the expression is being read from or written to (or both,
1003         // if sent as an inout parameter to a function).  For the sake of the transformation, the
1004         // left-hand side of operations like += can be treated as "written to", without necessarily
1005         // "read from".
1006         bool isRead  = false;
1007         bool isWrite = false;
1008 
1009         determineAccess(originalExpression, accessor, &isRead, &isWrite);
1010 
1011         ASSERT(isRead || isWrite);
1012 
1013         TIntermTyped *readExpression = nullptr;
1014         if (isRead)
1015         {
1016             readExpression = transformReadExpression(
1017                 baseExpression, primaryIndex, &secondaryIndices, structure, &prependStatements);
1018 
1019             // If both read from and written to (i.e. passed to inout parameter), store the
1020             // expression in a temp variable and pass that to the function.
1021             if (isWrite)
1022             {
1023                 readExpression =
1024                     CopyToTempVariable(mSymbolTable, readExpression, &prependStatements);
1025             }
1026 
1027             // Replace the original expression with the transformed one.  Read transformations
1028             // always generate a single expression that can be used in place of the original (as
1029             // oppposed to write transformations that can generate multiple statements).
1030             queueReplacementWithParent(accessor, originalExpression, readExpression,
1031                                        OriginalNode::IS_DROPPED);
1032         }
1033 
1034         TIntermSequence postTransformPrependStatements;
1035         TIntermSequence *writeStatements = &appendStatements;
1036         TOperator assignmentOperator     = EOpAssign;
1037 
1038         if (isWrite)
1039         {
1040             TIntermTyped *valueExpression = readExpression;
1041 
1042             if (!valueExpression)
1043             {
1044                 // If there's already a read expression, this was an inout parameter and
1045                 // |valueExpression| will contain the temp variable that was passed to the function
1046                 // instead.
1047                 //
1048                 // If not, then the modification is either through being passed as an out parameter
1049                 // to a function, or an assignment.  In the former case, create a temp variable to
1050                 // be passed to the function.  In the latter case, create a temp variable that holds
1051                 // the right hand side expression.
1052                 //
1053                 // In either case, use that temp value as the value to assign to |baseExpression|.
1054 
1055                 TVariable *temp = CreateTempVariable(
1056                     mSymbolTable, &originalExpression->getAsTyped()->getType(), EvqTemporary);
1057                 TIntermDeclaration *tempDecl = nullptr;
1058 
1059                 valueExpression = new TIntermSymbol(temp);
1060 
1061                 TIntermBinary *assignment = accessor->getAsBinaryNode();
1062                 if (assignment)
1063                 {
1064                     assignmentOperator = assignment->getOp();
1065                     ASSERT(IsAssignment(assignmentOperator));
1066 
1067                     // We are converting the assignment to the left-hand side of an expression in
1068                     // the form M=exp.  A subexpression of exp itself could require a
1069                     // transformation.  This complicates things as there would be two replacements:
1070                     //
1071                     // - Replace M=exp with temp (because the return value of the assignment could
1072                     //   be used)
1073                     // - Replace exp with exp2, where parent is M=exp
1074                     //
1075                     // The second replacement however is ineffective as the whole of M=exp is
1076                     // already transformed.  What's worse, M=exp is transformed without taking exp's
1077                     // transformations into account.  To address this issue, this same traverser is
1078                     // called on the right-hand side expression, with a special flag such that it
1079                     // only processes that expression.
1080                     //
1081                     RewriteRowMajorMatricesTraverser *outerTraverser =
1082                         mOuterTraverser ? mOuterTraverser : this;
1083                     RewriteRowMajorMatricesTraverser rhsTraverser(
1084                         mSymbolTable, outerTraverser, mInterfaceBlockMap,
1085                         mInterfaceBlockFieldConvertedIn, mStructMapOut, mCopyFunctionDefinitionsOut,
1086                         assignment);
1087                     getRootNode()->traverse(&rhsTraverser);
1088                     bool valid = rhsTraverser.updateTree(mCompiler, getRootNode());
1089                     ASSERT(valid);
1090 
1091                     tempDecl = CreateTempInitDeclarationNode(temp, assignment->getRight());
1092 
1093                     // Replace the whole assignment expression with the right-hand side as a read
1094                     // expression, in case the result of the assignment is used.  For example, this
1095                     // transforms:
1096                     //
1097                     //     if ((M += exp) == X)
1098                     //     {
1099                     //         // use M
1100                     //     }
1101                     //
1102                     // to:
1103                     //
1104                     //     temp = exp;
1105                     //     M += transform(temp);
1106                     //     if (transform(M) == X)
1107                     //     {
1108                     //         // use M
1109                     //     }
1110                     //
1111                     // Note that in this case the assignment to M must be prepended in the parent
1112                     // block.  In contrast, when sent to a function, the assignment to M should be
1113                     // done after the current function call is done.
1114                     //
1115                     // If the read from M itself (to replace assigmnet) needs to generate extra
1116                     // statements, they should be appended after the statements that write to M.
1117                     // These statements are stored in postTransformPrependStatements and appended to
1118                     // prependStatements in the end.
1119                     //
1120                     writeStatements = &prependStatements;
1121 
1122                     TIntermTyped *assignmentResultExpression = transformReadExpression(
1123                         baseExpression->deepCopy(), primaryIndex, &secondaryIndices, structure,
1124                         &postTransformPrependStatements);
1125 
1126                     // Replace the whole assignment, instead of just the right hand side.
1127                     TIntermNode *accessorParent = getAncestorNode(accessorIndex + 1);
1128                     queueReplacementWithParent(accessorParent, accessor, assignmentResultExpression,
1129                                                OriginalNode::IS_DROPPED);
1130                 }
1131                 else
1132                 {
1133                     tempDecl = CreateTempDeclarationNode(temp);
1134 
1135                     // Replace the write expression (a function call argument) with the temp
1136                     // variable.
1137                     queueReplacementWithParent(accessor, originalExpression, valueExpression,
1138                                                OriginalNode::IS_DROPPED);
1139                 }
1140                 prependStatements.push_back(tempDecl);
1141             }
1142 
1143             if (isRead)
1144             {
1145                 baseExpression = baseExpression->deepCopy();
1146             }
1147             transformWriteExpression(baseExpression, primaryIndex, &secondaryIndices, structure,
1148                                      valueExpression, assignmentOperator, writeStatements);
1149         }
1150 
1151         prependStatements.insert(prependStatements.end(), postTransformPrependStatements.begin(),
1152                                  postTransformPrependStatements.end());
1153 
1154         RewriteRowMajorMatricesTraverser *traverser = mOuterTraverser ? mOuterTraverser : this;
1155         traverser->insertStatementsInParentBlock(prependStatements, appendStatements);
1156     }
1157 
transformReadExpression(TIntermTyped * baseExpression,TIntermNode * primaryIndex,TIntermSequence * secondaryIndices,const TStructure * structure,TIntermSequence * prependStatements)1158     TIntermTyped *transformReadExpression(TIntermTyped *baseExpression,
1159                                           TIntermNode *primaryIndex,
1160                                           TIntermSequence *secondaryIndices,
1161                                           const TStructure *structure,
1162                                           TIntermSequence *prependStatements)
1163     {
1164         const TType &baseExpressionType = baseExpression->getType();
1165 
1166         if (structure)
1167         {
1168             ASSERT(primaryIndex == nullptr && secondaryIndices->empty());
1169             ASSERT(mStructMapOut->count(structure) != 0);
1170             ASSERT((*mStructMapOut)[structure].convertedStruct != nullptr);
1171 
1172             // Declare copy-from-converted-to-original-struct function (if not already).
1173             declareStructCopyToOriginal(structure);
1174 
1175             const TFunction *copyToOriginal = (*mStructMapOut)[structure].copyToOriginal;
1176 
1177             if (baseExpressionType.isArray())
1178             {
1179                 // If base expression is an array, transform every element.
1180                 TransformArrayHelper transformHelper(baseExpression);
1181 
1182                 TIntermTyped *element = nullptr;
1183                 while ((element = transformHelper.getNextElement(nullptr, nullptr)) != nullptr)
1184                 {
1185                     TIntermTyped *transformedElement =
1186                         CreateStructCopyCall(copyToOriginal, element);
1187                     transformHelper.accumulateForRead(mSymbolTable, transformedElement,
1188                                                       prependStatements);
1189                 }
1190                 return transformHelper.constructReadTransformExpression();
1191             }
1192             else
1193             {
1194                 // If not reading an array, the result is simply a call to this function with the
1195                 // base expression.
1196                 return CreateStructCopyCall(copyToOriginal, baseExpression);
1197             }
1198         }
1199 
1200         // If not indexed, the result is transpose(exp)
1201         if (primaryIndex == nullptr)
1202         {
1203             ASSERT(secondaryIndices->empty());
1204 
1205             if (baseExpressionType.isArray())
1206             {
1207                 // If array, transpose every element.
1208                 TransformArrayHelper transformHelper(baseExpression);
1209 
1210                 TIntermTyped *element = nullptr;
1211                 while ((element = transformHelper.getNextElement(nullptr, nullptr)) != nullptr)
1212                 {
1213                     TIntermTyped *transformedElement = CreateTransposeCall(mSymbolTable, element);
1214                     transformHelper.accumulateForRead(mSymbolTable, transformedElement,
1215                                                       prependStatements);
1216                 }
1217                 return transformHelper.constructReadTransformExpression();
1218             }
1219             else
1220             {
1221                 return CreateTransposeCall(mSymbolTable, baseExpression);
1222             }
1223         }
1224 
1225         // If indexed the result is a vector (or just one element) where the primary and secondary
1226         // indices are swapped.
1227         ASSERT(!secondaryIndices->empty());
1228 
1229         TOperator primaryIndexOp          = GetIndexOp(primaryIndex);
1230         TIntermTyped *primaryIndexAsTyped = primaryIndex->getAsTyped();
1231 
1232         TIntermSequence transposedColumn;
1233         for (TIntermNode *secondaryIndex : *secondaryIndices)
1234         {
1235             TOperator secondaryIndexOp          = GetIndexOp(secondaryIndex);
1236             TIntermTyped *secondaryIndexAsTyped = secondaryIndex->getAsTyped();
1237 
1238             TIntermBinary *colIndexed = new TIntermBinary(
1239                 secondaryIndexOp, baseExpression->deepCopy(), secondaryIndexAsTyped->deepCopy());
1240             TIntermBinary *colRowIndexed =
1241                 new TIntermBinary(primaryIndexOp, colIndexed, primaryIndexAsTyped->deepCopy());
1242 
1243             transposedColumn.push_back(colRowIndexed);
1244         }
1245 
1246         if (secondaryIndices->size() == 1)
1247         {
1248             // If only one element, return that directly.
1249             return transposedColumn.front()->getAsTyped();
1250         }
1251 
1252         // Otherwise create a constructor with the appropriate dimension.
1253         TType *vecType = new TType(baseExpressionType.getBasicType(), secondaryIndices->size());
1254         return TIntermAggregate::CreateConstructor(*vecType, &transposedColumn);
1255     }
1256 
transformWriteExpression(TIntermTyped * baseExpression,TIntermNode * primaryIndex,TIntermSequence * secondaryIndices,const TStructure * structure,TIntermTyped * valueExpression,TOperator assignmentOperator,TIntermSequence * writeStatements)1257     void transformWriteExpression(TIntermTyped *baseExpression,
1258                                   TIntermNode *primaryIndex,
1259                                   TIntermSequence *secondaryIndices,
1260                                   const TStructure *structure,
1261                                   TIntermTyped *valueExpression,
1262                                   TOperator assignmentOperator,
1263                                   TIntermSequence *writeStatements)
1264     {
1265         const TType &baseExpressionType = baseExpression->getType();
1266 
1267         if (structure)
1268         {
1269             ASSERT(primaryIndex == nullptr && secondaryIndices->empty());
1270             ASSERT(mStructMapOut->count(structure) != 0);
1271             ASSERT((*mStructMapOut)[structure].convertedStruct != nullptr);
1272 
1273             // Declare copy-to-converted-from-original-struct function (if not already).
1274             declareStructCopyFromOriginal(structure);
1275 
1276             // The result is call to this function with the value expression assigned to base
1277             // expression.
1278             const TFunction *copyFromOriginal = (*mStructMapOut)[structure].copyFromOriginal;
1279 
1280             if (baseExpressionType.isArray())
1281             {
1282                 // If array, assign every element.
1283                 TransformArrayHelper transformHelper(baseExpression);
1284 
1285                 TIntermTyped *element      = nullptr;
1286                 TIntermTyped *valueElement = nullptr;
1287                 while ((element = transformHelper.getNextElement(valueExpression, &valueElement)) !=
1288                        nullptr)
1289                 {
1290                     TIntermTyped *functionCall =
1291                         CreateStructCopyCall(copyFromOriginal, valueElement);
1292                     writeStatements->push_back(new TIntermBinary(EOpAssign, element, functionCall));
1293                 }
1294             }
1295             else
1296             {
1297                 TIntermTyped *functionCall =
1298                     CreateStructCopyCall(copyFromOriginal, valueExpression->deepCopy());
1299                 writeStatements->push_back(
1300                     new TIntermBinary(EOpAssign, baseExpression, functionCall));
1301             }
1302 
1303             return;
1304         }
1305 
1306         // If not indexed, the result is transpose(exp)
1307         if (primaryIndex == nullptr)
1308         {
1309             ASSERT(secondaryIndices->empty());
1310 
1311             if (baseExpressionType.isArray())
1312             {
1313                 // If array, assign every element.
1314                 TransformArrayHelper transformHelper(baseExpression);
1315 
1316                 TIntermTyped *element      = nullptr;
1317                 TIntermTyped *valueElement = nullptr;
1318                 while ((element = transformHelper.getNextElement(valueExpression, &valueElement)) !=
1319                        nullptr)
1320                 {
1321                     TIntermTyped *valueTransposed = CreateTransposeCall(mSymbolTable, valueElement);
1322                     writeStatements->push_back(
1323                         new TIntermBinary(EOpAssign, element, valueTransposed));
1324                 }
1325             }
1326             else
1327             {
1328                 TIntermTyped *valueTransposed =
1329                     CreateTransposeCall(mSymbolTable, valueExpression->deepCopy());
1330                 writeStatements->push_back(
1331                     new TIntermBinary(assignmentOperator, baseExpression, valueTransposed));
1332             }
1333 
1334             return;
1335         }
1336 
1337         // If indexed, create one assignment per secondary index.  If the right-hand side is a
1338         // scalar, it's used with every assignment.  If it's a vector, the assignment is
1339         // per-component.  The right-hand side cannot be a matrix as that would imply left-hand
1340         // side being a matrix too, which is covered above where |primaryIndex == nullptr|.
1341         ASSERT(!secondaryIndices->empty());
1342 
1343         bool isValueExpressionScalar = valueExpression->getType().getNominalSize() == 1;
1344         ASSERT(isValueExpressionScalar || valueExpression->getType().getNominalSize() ==
1345                                               static_cast<int>(secondaryIndices->size()));
1346 
1347         TOperator primaryIndexOp          = GetIndexOp(primaryIndex);
1348         TIntermTyped *primaryIndexAsTyped = primaryIndex->getAsTyped();
1349 
1350         for (TIntermNode *secondaryIndex : *secondaryIndices)
1351         {
1352             TOperator secondaryIndexOp          = GetIndexOp(secondaryIndex);
1353             TIntermTyped *secondaryIndexAsTyped = secondaryIndex->getAsTyped();
1354 
1355             TIntermBinary *colIndexed = new TIntermBinary(
1356                 secondaryIndexOp, baseExpression->deepCopy(), secondaryIndexAsTyped->deepCopy());
1357             TIntermBinary *colRowIndexed =
1358                 new TIntermBinary(primaryIndexOp, colIndexed, primaryIndexAsTyped->deepCopy());
1359 
1360             TIntermTyped *valueExpressionIndexed = valueExpression->deepCopy();
1361             if (!isValueExpressionScalar)
1362             {
1363                 valueExpressionIndexed = new TIntermBinary(secondaryIndexOp, valueExpressionIndexed,
1364                                                            secondaryIndexAsTyped->deepCopy());
1365             }
1366 
1367             writeStatements->push_back(
1368                 new TIntermBinary(assignmentOperator, colRowIndexed, valueExpressionIndexed));
1369         }
1370     }
1371 
getCopyStructFieldFunction(const TType * fromFieldType,const TType * toFieldType,bool isCopyToOriginal)1372     const TFunction *getCopyStructFieldFunction(const TType *fromFieldType,
1373                                                 const TType *toFieldType,
1374                                                 bool isCopyToOriginal)
1375     {
1376         ASSERT(fromFieldType->getStruct());
1377         ASSERT(toFieldType->getStruct());
1378 
1379         // If copying from or to the original struct, the "to" field struct could require
1380         // conversion to or from the "from" field struct.  |isCopyToOriginal| tells us if we
1381         // should expect to find toField or fromField in mStructMapOut, if true or false
1382         // respectively.
1383         const TFunction *fieldCopyFunction = nullptr;
1384         if (isCopyToOriginal)
1385         {
1386             const TStructure *toFieldStruct = toFieldType->getStruct();
1387 
1388             auto iter = mStructMapOut->find(toFieldStruct);
1389             if (iter != mStructMapOut->end())
1390             {
1391                 declareStructCopyToOriginal(toFieldStruct);
1392                 fieldCopyFunction = iter->second.copyToOriginal;
1393             }
1394         }
1395         else
1396         {
1397             const TStructure *fromFieldStruct = fromFieldType->getStruct();
1398 
1399             auto iter = mStructMapOut->find(fromFieldStruct);
1400             if (iter != mStructMapOut->end())
1401             {
1402                 declareStructCopyFromOriginal(fromFieldStruct);
1403                 fieldCopyFunction = iter->second.copyFromOriginal;
1404             }
1405         }
1406 
1407         return fieldCopyFunction;
1408     }
1409 
addFieldCopy(TIntermBlock * body,TIntermTyped * to,TIntermTyped * from,bool isCopyToOriginal)1410     void addFieldCopy(TIntermBlock *body,
1411                       TIntermTyped *to,
1412                       TIntermTyped *from,
1413                       bool isCopyToOriginal)
1414     {
1415         const TType &fromType = from->getType();
1416         const TType &toType   = to->getType();
1417 
1418         TIntermTyped *rhs = from;
1419 
1420         if (fromType.getStruct())
1421         {
1422             const TFunction *fieldCopyFunction =
1423                 getCopyStructFieldFunction(&fromType, &toType, isCopyToOriginal);
1424 
1425             if (fieldCopyFunction)
1426             {
1427                 rhs = CreateStructCopyCall(fieldCopyFunction, from);
1428             }
1429         }
1430         else if (fromType.isMatrix())
1431         {
1432             rhs = CreateTransposeCall(mSymbolTable, from);
1433         }
1434 
1435         body->appendStatement(new TIntermBinary(EOpAssign, to, rhs));
1436     }
1437 
declareStructCopy(const TStructure * from,const TStructure * to,bool isCopyToOriginal)1438     TFunction *declareStructCopy(const TStructure *from,
1439                                  const TStructure *to,
1440                                  bool isCopyToOriginal)
1441     {
1442         TType *fromType = new TType(from, true);
1443         TType *toType   = new TType(to, true);
1444 
1445         // Create the parameter and return value variables.
1446         TVariable *fromVar = new TVariable(mSymbolTable, ImmutableString("from"), fromType,
1447                                            SymbolType::AngleInternal);
1448         TVariable *toVar =
1449             new TVariable(mSymbolTable, ImmutableString("to"), toType, SymbolType::AngleInternal);
1450 
1451         TIntermSymbol *fromSymbol = new TIntermSymbol(fromVar);
1452         TIntermSymbol *toSymbol   = new TIntermSymbol(toVar);
1453 
1454         // Create the function body as statements are generated.
1455         TIntermBlock *body = new TIntermBlock;
1456 
1457         // Declare the result variable.
1458         TIntermDeclaration *toDecl = new TIntermDeclaration();
1459         toDecl->appendDeclarator(toSymbol);
1460         body->appendStatement(toDecl);
1461 
1462         // Iterate over fields of the struct and copy one by one, transposing the matrices.  If a
1463         // struct is encountered that requires a transformation, this function is recursively
1464         // called.  As a result, it is important that the copy functions are placed in the code in
1465         // order.
1466         const TFieldList &fromFields = from->fields();
1467         const TFieldList &toFields   = to->fields();
1468         ASSERT(fromFields.size() == toFields.size());
1469 
1470         for (size_t fieldIndex = 0; fieldIndex < fromFields.size(); ++fieldIndex)
1471         {
1472             TIntermTyped *fieldIndexNode = CreateIndexNode(static_cast<int>(fieldIndex));
1473 
1474             TIntermTyped *fromField =
1475                 new TIntermBinary(EOpIndexDirectStruct, fromSymbol->deepCopy(), fieldIndexNode);
1476             TIntermTyped *toField = new TIntermBinary(EOpIndexDirectStruct, toSymbol->deepCopy(),
1477                                                       fieldIndexNode->deepCopy());
1478 
1479             const TType *fromFieldType = fromFields[fieldIndex]->type();
1480             bool isStructOrMatrix      = fromFieldType->getStruct() || fromFieldType->isMatrix();
1481 
1482             if (fromFieldType->isArray() && isStructOrMatrix)
1483             {
1484                 // If struct or matrix array, we need to copy element by element.
1485                 TransformArrayHelper transformHelper(toField);
1486 
1487                 TIntermTyped *toElement   = nullptr;
1488                 TIntermTyped *fromElement = nullptr;
1489                 while ((toElement = transformHelper.getNextElement(fromField, &fromElement)) !=
1490                        nullptr)
1491                 {
1492                     addFieldCopy(body, toElement, fromElement, isCopyToOriginal);
1493                 }
1494             }
1495             else
1496             {
1497                 addFieldCopy(body, toField, fromField, isCopyToOriginal);
1498             }
1499         }
1500 
1501         // Add return statement.
1502         body->appendStatement(new TIntermBranch(EOpReturn, toSymbol->deepCopy()));
1503 
1504         // Declare the function
1505         TFunction *copyFunction = new TFunction(mSymbolTable, kEmptyImmutableString,
1506                                                 SymbolType::AngleInternal, toType, true);
1507         copyFunction->addParameter(fromVar);
1508 
1509         TIntermFunctionDefinition *functionDef =
1510             CreateInternalFunctionDefinitionNode(*copyFunction, body);
1511         mCopyFunctionDefinitionsOut->push_back(functionDef);
1512 
1513         return copyFunction;
1514     }
1515 
declareStructCopyFromOriginal(const TStructure * structure)1516     void declareStructCopyFromOriginal(const TStructure *structure)
1517     {
1518         StructConversionData *structData = &(*mStructMapOut)[structure];
1519         if (structData->copyFromOriginal)
1520         {
1521             return;
1522         }
1523 
1524         structData->copyFromOriginal =
1525             declareStructCopy(structure, structData->convertedStruct, false);
1526     }
1527 
declareStructCopyToOriginal(const TStructure * structure)1528     void declareStructCopyToOriginal(const TStructure *structure)
1529     {
1530         StructConversionData *structData = &(*mStructMapOut)[structure];
1531         if (structData->copyToOriginal)
1532         {
1533             return;
1534         }
1535 
1536         structData->copyToOriginal =
1537             declareStructCopy(structData->convertedStruct, structure, true);
1538     }
1539 
1540     TCompiler *mCompiler;
1541 
1542     // This traverser can call itself to transform a subexpression before moving on.  However, it
1543     // needs to accumulate conversion functions in inner passes.  The fields below marked with Out
1544     // or In are inherited from the outer pass (for inner passes), or point to storage fields in
1545     // mOuterPass (for the outer pass).  The latter should not be used by the inner passes as they
1546     // would be empty, so they are placed inside a struct to make them explicit.
1547     struct
1548     {
1549         StructMap structMap;
1550         InterfaceBlockMap interfaceBlockMap;
1551         InterfaceBlockFieldConverted interfaceBlockFieldConverted;
1552         TIntermSequence copyFunctionDefinitions;
1553     } mOuterPass;
1554 
1555     // A map from structures with matrices to their converted version.
1556     StructMap *mStructMapOut;
1557     // A map from interface block instances with row-major matrices to their converted variable.  If
1558     // an interface block is nameless, its fields are placed in this map instead.  When a variable
1559     // in this map is encountered, it signals the start of an expression that my need conversion,
1560     // which is either "interfaceBlock.field..." or "field..." if nameless.
1561     InterfaceBlockMap *mInterfaceBlockMap;
1562     // A map from interface block fields to whether they need to be converted.  If a field was
1563     // already column-major, it shouldn't be transposed.
1564     const InterfaceBlockFieldConverted &mInterfaceBlockFieldConvertedIn;
1565 
1566     TIntermSequence *mCopyFunctionDefinitionsOut;
1567 
1568     // If set, it's an inner pass and this will point to the outer pass traverser.  All statement
1569     // insertions are stored in the outer traverser and applied at once in the end.  This prevents
1570     // the inner passes from adding statements which invalidates the outer traverser's statement
1571     // position tracking.
1572     RewriteRowMajorMatricesTraverser *mOuterTraverser;
1573 
1574     // If set, it's an inner pass that should only process the right-hand side of this particular
1575     // node.
1576     TIntermBinary *mInnerPassRoot;
1577     bool mIsProcessingInnerPassSubtree;
1578 };
1579 
1580 }  // anonymous namespace
1581 
RewriteRowMajorMatrices(TCompiler * compiler,TIntermBlock * root,TSymbolTable * symbolTable)1582 bool RewriteRowMajorMatrices(TCompiler *compiler, TIntermBlock *root, TSymbolTable *symbolTable)
1583 {
1584     RewriteRowMajorMatricesTraverser traverser(compiler, symbolTable);
1585     root->traverse(&traverser);
1586     if (!traverser.updateTree(compiler, root))
1587     {
1588         return false;
1589     }
1590 
1591     size_t firstFunctionIndex = FindFirstFunctionDefinitionIndex(root);
1592     root->insertChildNodes(firstFunctionIndex, *traverser.getStructCopyFunctions());
1593 
1594     return compiler->validateAST(root);
1595 }
1596 }  // namespace sh
1597