1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 #include "OutputASM.h"
16 #include "Common/Math.hpp"
18 #include "common/debug.h"
21 #include "libGLESv2/Shader.h"
23 #include <GLES2/gl2.h>
24 #include <GLES2/gl2ext.h>
25 #include <GLES3/gl3.h>
29 // Integer to TString conversion
33 sprintf(buffer, "%d", i);
37 class Temporary : public TIntermSymbol
40 Temporary(OutputASM *assembler) : TIntermSymbol(TSymbolTableLevel::nextUniqueId(), "tmp", TType(EbtFloat, EbpHigh, EvqTemporary, 4, 1, false)), assembler(assembler)
46 assembler->freeTemporary(this);
50 OutputASM *const assembler;
53 class Constant : public TIntermConstantUnion
56 Constant(float x, float y, float z, float w) : TIntermConstantUnion(constants, TType(EbtFloat, EbpHigh, EvqConstExpr, 4, 1, false))
58 constants[0].setFConst(x);
59 constants[1].setFConst(y);
60 constants[2].setFConst(z);
61 constants[3].setFConst(w);
64 Constant(bool b) : TIntermConstantUnion(constants, TType(EbtBool, EbpHigh, EvqConstExpr, 1, 1, false))
66 constants[0].setBConst(b);
69 Constant(int i) : TIntermConstantUnion(constants, TType(EbtInt, EbpHigh, EvqConstExpr, 1, 1, false))
71 constants[0].setIConst(i);
79 ConstantUnion constants[4];
82 Uniform::Uniform(GLenum type, GLenum precision, const std::string &name, int arraySize, int registerIndex, int blockId, const BlockMemberInfo& blockMemberInfo) :
83 type(type), precision(precision), name(name), arraySize(arraySize), registerIndex(registerIndex), blockId(blockId), blockInfo(blockMemberInfo)
87 UniformBlock::UniformBlock(const std::string& name, unsigned int dataSize, unsigned int arraySize,
88 TLayoutBlockStorage layout, bool isRowMajorLayout, int registerIndex, int blockId) :
89 name(name), dataSize(dataSize), arraySize(arraySize), layout(layout),
90 isRowMajorLayout(isRowMajorLayout), registerIndex(registerIndex), blockId(blockId)
94 BlockLayoutEncoder::BlockLayoutEncoder(bool rowMajor)
95 : mCurrentOffset(0), isRowMajor(rowMajor)
99 BlockMemberInfo BlockLayoutEncoder::encodeType(const TType &type)
104 getBlockLayoutInfo(type, type.getArraySize(), isRowMajor, &arrayStride, &matrixStride);
106 const BlockMemberInfo memberInfo(static_cast<int>(mCurrentOffset * BytesPerComponent),
107 static_cast<int>(arrayStride * BytesPerComponent),
108 static_cast<int>(matrixStride * BytesPerComponent),
109 (matrixStride > 0) && isRowMajor);
111 advanceOffset(type, type.getArraySize(), isRowMajor, arrayStride, matrixStride);
117 size_t BlockLayoutEncoder::getBlockRegister(const BlockMemberInfo &info)
119 return (info.offset / BytesPerComponent) / ComponentsPerRegister;
123 size_t BlockLayoutEncoder::getBlockRegisterElement(const BlockMemberInfo &info)
125 return (info.offset / BytesPerComponent) % ComponentsPerRegister;
128 void BlockLayoutEncoder::nextRegister()
130 mCurrentOffset = sw::align(mCurrentOffset, ComponentsPerRegister);
133 Std140BlockEncoder::Std140BlockEncoder(bool rowMajor) : BlockLayoutEncoder(rowMajor)
137 void Std140BlockEncoder::enterAggregateType()
142 void Std140BlockEncoder::exitAggregateType()
147 void Std140BlockEncoder::getBlockLayoutInfo(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
149 size_t baseAlignment = 0;
150 int matrixStride = 0;
155 baseAlignment = ComponentsPerRegister;
156 matrixStride = ComponentsPerRegister;
160 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
161 arrayStride = ComponentsPerRegister * numRegisters;
164 else if(arraySize > 0)
166 baseAlignment = ComponentsPerRegister;
167 arrayStride = ComponentsPerRegister;
171 const size_t numComponents = type.getElementSize();
172 baseAlignment = (numComponents == 3 ? 4u : numComponents);
175 mCurrentOffset = sw::align(mCurrentOffset, baseAlignment);
177 *matrixStrideOut = matrixStride;
178 *arrayStrideOut = arrayStride;
181 void Std140BlockEncoder::advanceOffset(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
185 mCurrentOffset += arrayStride * arraySize;
187 else if(type.isMatrix())
189 ASSERT(matrixStride == ComponentsPerRegister);
190 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
191 mCurrentOffset += ComponentsPerRegister * numRegisters;
195 mCurrentOffset += type.getElementSize();
199 Attribute::Attribute()
206 Attribute::Attribute(GLenum type, const std::string &name, int arraySize, int location, int registerIndex)
210 this->arraySize = arraySize;
211 this->location = location;
212 this->registerIndex = registerIndex;
215 sw::PixelShader *Shader::getPixelShader() const
220 sw::VertexShader *Shader::getVertexShader() const
225 OutputASM::TextureFunction::TextureFunction(const TString& nodeName) : method(IMPLICIT), proj(false), offset(false)
227 TString name = TFunction::unmangleName(nodeName);
229 if(name == "texture2D" || name == "textureCube" || name == "texture" || name == "texture3D")
233 else if(name == "texture2DProj" || name == "textureProj")
238 else if(name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod")
242 else if(name == "texture2DProjLod" || name == "textureProjLod")
247 else if(name == "textureSize")
251 else if(name == "textureOffset")
256 else if(name == "textureProjOffset")
262 else if(name == "textureLodOffset")
267 else if(name == "textureProjLodOffset")
273 else if(name == "texelFetch")
277 else if(name == "texelFetchOffset")
282 else if(name == "textureGrad")
286 else if(name == "textureGradOffset")
291 else if(name == "textureProjGrad")
296 else if(name == "textureProjGradOffset")
305 OutputASM::OutputASM(TParseContext &context, Shader *shaderObject) : TIntermTraverser(true, true, true), shaderObject(shaderObject), mContext(context)
313 shader = shaderObject->getShader();
314 pixelShader = shaderObject->getPixelShader();
315 vertexShader = shaderObject->getVertexShader();
318 functionArray.push_back(Function(0, "main(", 0, 0));
320 outputQualifier = EvqOutput; // Set outputQualifier to any value other than EvqFragColor or EvqFragData
323 OutputASM::~OutputASM()
327 void OutputASM::output()
333 if(functionArray.size() > 1) // Only call main() when there are other functions
335 Instruction *callMain = emit(sw::Shader::OPCODE_CALL);
336 callMain->dst.type = sw::Shader::PARAMETER_LABEL;
337 callMain->dst.index = 0; // main()
339 emit(sw::Shader::OPCODE_RET);
342 emitShader(FUNCTION);
346 void OutputASM::emitShader(Scope scope)
349 currentScope = GLOBAL;
350 mContext.getTreeRoot()->traverse(this);
353 void OutputASM::freeTemporary(Temporary *temporary)
355 free(temporaries, temporary);
358 sw::Shader::Opcode OutputASM::getOpcode(sw::Shader::Opcode op, TIntermTyped *in) const
360 TBasicType baseType = in->getType().getBasicType();
364 case sw::Shader::OPCODE_NEG:
369 return sw::Shader::OPCODE_INEG;
374 case sw::Shader::OPCODE_ABS:
378 return sw::Shader::OPCODE_IABS;
383 case sw::Shader::OPCODE_SGN:
387 return sw::Shader::OPCODE_ISGN;
392 case sw::Shader::OPCODE_ADD:
397 return sw::Shader::OPCODE_IADD;
402 case sw::Shader::OPCODE_SUB:
407 return sw::Shader::OPCODE_ISUB;
412 case sw::Shader::OPCODE_MUL:
417 return sw::Shader::OPCODE_IMUL;
422 case sw::Shader::OPCODE_DIV:
426 return sw::Shader::OPCODE_IDIV;
428 return sw::Shader::OPCODE_UDIV;
433 case sw::Shader::OPCODE_IMOD:
434 return baseType == EbtUInt ? sw::Shader::OPCODE_UMOD : op;
435 case sw::Shader::OPCODE_ISHR:
436 return baseType == EbtUInt ? sw::Shader::OPCODE_USHR : op;
437 case sw::Shader::OPCODE_MIN:
441 return sw::Shader::OPCODE_IMIN;
443 return sw::Shader::OPCODE_UMIN;
448 case sw::Shader::OPCODE_MAX:
452 return sw::Shader::OPCODE_IMAX;
454 return sw::Shader::OPCODE_UMAX;
464 void OutputASM::visitSymbol(TIntermSymbol *symbol)
466 // Vertex varyings don't have to be actively used to successfully link
467 // against pixel shaders that use them. So make sure they're declared.
468 if(symbol->getQualifier() == EvqVaryingOut || symbol->getQualifier() == EvqInvariantVaryingOut || symbol->getQualifier() == EvqVertexOut)
470 if(symbol->getBasicType() != EbtInvariant) // Typeless declarations are not new varyings
472 declareVarying(symbol, -1);
476 TInterfaceBlock* block = symbol->getType().getInterfaceBlock();
477 // OpenGL ES 3.0.4 spec, section 2.12.6 Uniform Variables:
478 // "All members of a named uniform block declared with a shared or std140 layout qualifier
479 // are considered active, even if they are not referenced in any shader in the program.
480 // The uniform block itself is also considered active, even if no member of the block is referenced."
481 if(block && ((block->blockStorage() == EbsShared) || (block->blockStorage() == EbsStd140)))
483 uniformRegister(symbol);
487 bool OutputASM::visitBinary(Visit visit, TIntermBinary *node)
489 if(currentScope != emitScope)
494 TIntermTyped *result = node;
495 TIntermTyped *left = node->getLeft();
496 TIntermTyped *right = node->getRight();
497 const TType &leftType = left->getType();
498 const TType &rightType = right->getType();
499 const TType &resultType = node->getType();
501 if(isSamplerRegister(result))
503 return false; // Don't traverse, the register index is determined statically
506 switch(node->getOp())
509 if(visit == PostVisit)
511 assignLvalue(left, right);
516 if(visit == PostVisit)
521 case EOpMatrixTimesScalarAssign:
522 if(visit == PostVisit)
524 for(int i = 0; i < leftType.getNominalSize(); i++)
526 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right);
529 assignLvalue(left, result);
532 case EOpVectorTimesMatrixAssign:
533 if(visit == PostVisit)
535 int size = leftType.getNominalSize();
537 for(int i = 0; i < size; i++)
539 Instruction *dot = emit(sw::Shader::OPCODE_DP(size), result, 0, left, 0, right, i);
540 dot->dst.mask = 1 << i;
543 assignLvalue(left, result);
546 case EOpMatrixTimesMatrixAssign:
547 if(visit == PostVisit)
549 int dim = leftType.getNominalSize();
551 for(int i = 0; i < dim; i++)
553 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
554 mul->src[1].swizzle = 0x00;
556 for(int j = 1; j < dim; j++)
558 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
559 mad->src[1].swizzle = j * 0x55;
563 assignLvalue(left, result);
567 if(visit == PostVisit)
569 int index = right->getAsConstantUnion()->getIConst(0);
571 if(result->isMatrix() || result->isStruct() || result->isInterfaceBlock())
573 ASSERT(left->isArray());
574 copy(result, left, index * left->elementRegisterCount());
576 else if(result->isRegister())
579 if(left->isRegister())
583 else if(left->isArray())
585 srcIndex = index * left->elementRegisterCount();
587 else if(left->isMatrix())
589 ASSERT(index < left->getNominalSize()); // FIXME: Report semantic error
594 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, 0, left, srcIndex);
596 if(left->isRegister())
598 mov->src[0].swizzle = index;
604 case EOpIndexIndirect:
605 if(visit == PostVisit)
607 if(left->isArray() || left->isMatrix())
609 for(int index = 0; index < result->totalRegisterCount(); index++)
611 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index, left, index);
612 mov->dst.mask = writeMask(result, index);
614 if(left->totalRegisterCount() > 1)
616 sw::Shader::SourceParameter relativeRegister;
617 argument(relativeRegister, right);
619 mov->src[0].rel.type = relativeRegister.type;
620 mov->src[0].rel.index = relativeRegister.index;
621 mov->src[0].rel.scale = result->totalRegisterCount();
622 mov->src[0].rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
626 else if(left->isRegister())
628 emit(sw::Shader::OPCODE_EXTRACT, result, left, right);
633 case EOpIndexDirectStruct:
634 case EOpIndexDirectInterfaceBlock:
635 if(visit == PostVisit)
637 ASSERT(leftType.isStruct() || (leftType.isInterfaceBlock()));
639 const TFieldList& fields = (node->getOp() == EOpIndexDirectStruct) ?
640 leftType.getStruct()->fields() :
641 leftType.getInterfaceBlock()->fields();
642 int index = right->getAsConstantUnion()->getIConst(0);
645 for(int i = 0; i < index; i++)
647 fieldOffset += fields[i]->type()->totalRegisterCount();
650 copy(result, left, fieldOffset);
653 case EOpVectorSwizzle:
654 if(visit == PostVisit)
657 TIntermAggregate *components = right->getAsAggregate();
661 TIntermSequence &sequence = components->getSequence();
664 for(TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
666 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
670 int i = element->getUnionArrayPointer()[0].getIConst();
671 swizzle |= i << (component * 2);
679 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, left);
680 mov->src[0].swizzle = swizzle;
683 case EOpAddAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_ADD, result), result, left, left, right); break;
684 case EOpAdd: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_ADD, result), result, left, right); break;
685 case EOpSubAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_SUB, result), result, left, left, right); break;
686 case EOpSub: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_SUB, result), result, left, right); break;
687 case EOpMulAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_MUL, result), result, left, left, right); break;
688 case EOpMul: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_MUL, result), result, left, right); break;
689 case EOpDivAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_DIV, result), result, left, left, right); break;
690 case EOpDiv: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_DIV, result), result, left, right); break;
691 case EOpIModAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_IMOD, result), result, left, left, right); break;
692 case EOpIMod: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_IMOD, result), result, left, right); break;
693 case EOpBitShiftLeftAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_SHL, result, left, left, right); break;
694 case EOpBitShiftLeft: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_SHL, result, left, right); break;
695 case EOpBitShiftRightAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_ISHR, result), result, left, left, right); break;
696 case EOpBitShiftRight: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_ISHR, result), result, left, right); break;
697 case EOpBitwiseAndAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_AND, result, left, left, right); break;
698 case EOpBitwiseAnd: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_AND, result, left, right); break;
699 case EOpBitwiseXorAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_XOR, result, left, left, right); break;
700 case EOpBitwiseXor: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_XOR, result, left, right); break;
701 case EOpBitwiseOrAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_OR, result, left, left, right); break;
702 case EOpBitwiseOr: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_OR, result, left, right); break;
704 if(visit == PostVisit)
706 emitBinary(sw::Shader::OPCODE_EQ, result, left, right);
708 for(int index = 1; index < left->totalRegisterCount(); index++)
710 Temporary equal(this);
711 emit(sw::Shader::OPCODE_EQ, &equal, 0, left, index, right, index);
712 emit(sw::Shader::OPCODE_AND, result, result, &equal);
717 if(visit == PostVisit)
719 emitBinary(sw::Shader::OPCODE_NE, result, left, right);
721 for(int index = 1; index < left->totalRegisterCount(); index++)
723 Temporary notEqual(this);
724 emit(sw::Shader::OPCODE_NE, ¬Equal, 0, left, index, right, index);
725 emit(sw::Shader::OPCODE_OR, result, result, ¬Equal);
729 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, left, right); break;
730 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, left, right); break;
731 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, left, right); break;
732 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, left, right); break;
733 case EOpVectorTimesScalarAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_MUL, left), result, left, left, right); break;
734 case EOpVectorTimesScalar: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MUL, left), result, left, right); break;
735 case EOpMatrixTimesScalar:
736 if(visit == PostVisit)
740 for(int i = 0; i < leftType.getNominalSize(); i++)
742 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right, 0);
745 else if(right->isMatrix())
747 for(int i = 0; i < rightType.getNominalSize(); i++)
749 emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
755 case EOpVectorTimesMatrix:
756 if(visit == PostVisit)
758 sw::Shader::Opcode dpOpcode = sw::Shader::OPCODE_DP(leftType.getNominalSize());
760 int size = rightType.getNominalSize();
761 for(int i = 0; i < size; i++)
763 Instruction *dot = emit(dpOpcode, result, 0, left, 0, right, i);
764 dot->dst.mask = 1 << i;
768 case EOpMatrixTimesVector:
769 if(visit == PostVisit)
771 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, left, right);
772 mul->src[1].swizzle = 0x00;
774 int size = rightType.getNominalSize();
775 for(int i = 1; i < size; i++)
777 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, 0, left, i, right, 0, result);
778 mad->src[1].swizzle = i * 0x55;
782 case EOpMatrixTimesMatrix:
783 if(visit == PostVisit)
785 int dim = leftType.getNominalSize();
787 int size = rightType.getNominalSize();
788 for(int i = 0; i < size; i++)
790 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
791 mul->src[1].swizzle = 0x00;
793 for(int j = 1; j < dim; j++)
795 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
796 mad->src[1].swizzle = j * 0x55;
802 if(trivial(right, 6))
804 if(visit == PostVisit)
806 emit(sw::Shader::OPCODE_OR, result, left, right);
809 else // Short-circuit evaluation
813 emit(sw::Shader::OPCODE_MOV, result, left);
814 Instruction *ifnot = emit(sw::Shader::OPCODE_IF, 0, result);
815 ifnot->src[0].modifier = sw::Shader::MODIFIER_NOT;
817 else if(visit == PostVisit)
819 emit(sw::Shader::OPCODE_MOV, result, right);
820 emit(sw::Shader::OPCODE_ENDIF);
824 case EOpLogicalXor: if(visit == PostVisit) emit(sw::Shader::OPCODE_XOR, result, left, right); break;
826 if(trivial(right, 6))
828 if(visit == PostVisit)
830 emit(sw::Shader::OPCODE_AND, result, left, right);
833 else // Short-circuit evaluation
837 emit(sw::Shader::OPCODE_MOV, result, left);
838 emit(sw::Shader::OPCODE_IF, 0, result);
840 else if(visit == PostVisit)
842 emit(sw::Shader::OPCODE_MOV, result, right);
843 emit(sw::Shader::OPCODE_ENDIF);
847 default: UNREACHABLE(node->getOp());
853 void OutputASM::emitDeterminant(TIntermTyped *result, TIntermTyped *arg, int size, int col, int row, int outCol, int outRow)
857 case 1: // Used for cofactor computation only
859 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
860 bool isMov = (row == col);
861 sw::Shader::Opcode op = isMov ? sw::Shader::OPCODE_MOV : sw::Shader::OPCODE_NEG;
862 Instruction *mov = emit(op, result, outCol, arg, isMov ? 1 - row : row);
863 mov->src[0].swizzle = 0x55 * (isMov ? 1 - col : col);
864 mov->dst.mask = 1 << outRow;
869 static const unsigned int swizzle[3] = { 0x99, 0x88, 0x44 }; // xy?? : yzyz, xzxz, xyxy
871 bool isCofactor = (col >= 0) && (row >= 0);
872 int col0 = (isCofactor && (col <= 0)) ? 1 : 0;
873 int col1 = (isCofactor && (col <= 1)) ? 2 : 1;
874 bool negate = isCofactor && ((col & 0x01) ^ (row & 0x01));
876 Instruction *det = emit(sw::Shader::OPCODE_DET2, result, outCol, arg, negate ? col1 : col0, arg, negate ? col0 : col1);
877 det->src[0].swizzle = det->src[1].swizzle = swizzle[isCofactor ? row : 2];
878 det->dst.mask = 1 << outRow;
883 static const unsigned int swizzle[4] = { 0xF9, 0xF8, 0xF4, 0xE4 }; // xyz? : yzww, xzww, xyww, xyzw
885 bool isCofactor = (col >= 0) && (row >= 0);
886 int col0 = (isCofactor && (col <= 0)) ? 1 : 0;
887 int col1 = (isCofactor && (col <= 1)) ? 2 : 1;
888 int col2 = (isCofactor && (col <= 2)) ? 3 : 2;
889 bool negate = isCofactor && ((col & 0x01) ^ (row & 0x01));
891 Instruction *det = emit(sw::Shader::OPCODE_DET3, result, outCol, arg, col0, arg, negate ? col2 : col1, arg, negate ? col1 : col2);
892 det->src[0].swizzle = det->src[1].swizzle = det->src[2].swizzle = swizzle[isCofactor ? row : 3];
893 det->dst.mask = 1 << outRow;
898 Instruction *det = emit(sw::Shader::OPCODE_DET4, result, outCol, arg, 0, arg, 1, arg, 2, arg, 3);
899 det->dst.mask = 1 << outRow;
908 bool OutputASM::visitUnary(Visit visit, TIntermUnary *node)
910 if(currentScope != emitScope)
915 TIntermTyped *result = node;
916 TIntermTyped *arg = node->getOperand();
917 TBasicType basicType = arg->getType().getBasicType();
925 if(basicType == EbtInt || basicType == EbtUInt)
934 Constant one(one_value.f, one_value.f, one_value.f, one_value.f);
935 Constant rad(1.74532925e-2f, 1.74532925e-2f, 1.74532925e-2f, 1.74532925e-2f);
936 Constant deg(5.72957795e+1f, 5.72957795e+1f, 5.72957795e+1f, 5.72957795e+1f);
938 switch(node->getOp())
941 if(visit == PostVisit)
943 sw::Shader::Opcode negOpcode = getOpcode(sw::Shader::OPCODE_NEG, arg);
944 for(int index = 0; index < arg->totalRegisterCount(); index++)
946 emit(negOpcode, result, index, arg, index);
950 case EOpVectorLogicalNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
951 case EOpLogicalNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
952 case EOpPostIncrement:
953 if(visit == PostVisit)
957 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
958 for(int index = 0; index < arg->totalRegisterCount(); index++)
960 emit(addOpcode, arg, index, arg, index, &one);
963 assignLvalue(arg, arg);
966 case EOpPostDecrement:
967 if(visit == PostVisit)
971 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
972 for(int index = 0; index < arg->totalRegisterCount(); index++)
974 emit(subOpcode, arg, index, arg, index, &one);
977 assignLvalue(arg, arg);
980 case EOpPreIncrement:
981 if(visit == PostVisit)
983 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
984 for(int index = 0; index < arg->totalRegisterCount(); index++)
986 emit(addOpcode, result, index, arg, index, &one);
989 assignLvalue(arg, result);
992 case EOpPreDecrement:
993 if(visit == PostVisit)
995 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
996 for(int index = 0; index < arg->totalRegisterCount(); index++)
998 emit(subOpcode, result, index, arg, index, &one);
1001 assignLvalue(arg, result);
1004 case EOpRadians: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &rad); break;
1005 case EOpDegrees: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, °); break;
1006 case EOpSin: if(visit == PostVisit) emit(sw::Shader::OPCODE_SIN, result, arg); break;
1007 case EOpCos: if(visit == PostVisit) emit(sw::Shader::OPCODE_COS, result, arg); break;
1008 case EOpTan: if(visit == PostVisit) emit(sw::Shader::OPCODE_TAN, result, arg); break;
1009 case EOpAsin: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASIN, result, arg); break;
1010 case EOpAcos: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOS, result, arg); break;
1011 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN, result, arg); break;
1012 case EOpSinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_SINH, result, arg); break;
1013 case EOpCosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_COSH, result, arg); break;
1014 case EOpTanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_TANH, result, arg); break;
1015 case EOpAsinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASINH, result, arg); break;
1016 case EOpAcosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOSH, result, arg); break;
1017 case EOpAtanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATANH, result, arg); break;
1018 case EOpExp: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP, result, arg); break;
1019 case EOpLog: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG, result, arg); break;
1020 case EOpExp2: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP2, result, arg); break;
1021 case EOpLog2: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG2, result, arg); break;
1022 case EOpSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_SQRT, result, arg); break;
1023 case EOpInverseSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_RSQ, result, arg); break;
1024 case EOpAbs: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_ABS, result), result, arg); break;
1025 case EOpSign: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_SGN, result), result, arg); break;
1026 case EOpFloor: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOOR, result, arg); break;
1027 case EOpTrunc: if(visit == PostVisit) emit(sw::Shader::OPCODE_TRUNC, result, arg); break;
1028 case EOpRound: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUND, result, arg); break;
1029 case EOpRoundEven: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUNDEVEN, result, arg); break;
1030 case EOpCeil: if(visit == PostVisit) emit(sw::Shader::OPCODE_CEIL, result, arg, result); break;
1031 case EOpFract: if(visit == PostVisit) emit(sw::Shader::OPCODE_FRC, result, arg); break;
1032 case EOpIsNan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISNAN, result, arg); break;
1033 case EOpIsInf: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISINF, result, arg); break;
1034 case EOpLength: if(visit == PostVisit) emit(sw::Shader::OPCODE_LEN(dim(arg)), result, arg); break;
1035 case EOpNormalize: if(visit == PostVisit) emit(sw::Shader::OPCODE_NRM(dim(arg)), result, arg); break;
1036 case EOpDFdx: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDX, result, arg); break;
1037 case EOpDFdy: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDY, result, arg); break;
1038 case EOpFwidth: if(visit == PostVisit) emit(sw::Shader::OPCODE_FWIDTH, result, arg); break;
1039 case EOpAny: if(visit == PostVisit) emit(sw::Shader::OPCODE_ANY, result, arg); break;
1040 case EOpAll: if(visit == PostVisit) emit(sw::Shader::OPCODE_ALL, result, arg); break;
1041 case EOpFloatBitsToInt: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOINT, result, arg); break;
1042 case EOpFloatBitsToUint: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOUINT, result, arg); break;
1043 case EOpIntBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_INTBITSTOFLOAT, result, arg); break;
1044 case EOpUintBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_UINTBITSTOFLOAT, result, arg); break;
1045 case EOpPackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKSNORM2x16, result, arg); break;
1046 case EOpPackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKUNORM2x16, result, arg); break;
1047 case EOpPackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKHALF2x16, result, arg); break;
1048 case EOpUnpackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKSNORM2x16, result, arg); break;
1049 case EOpUnpackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKUNORM2x16, result, arg); break;
1050 case EOpUnpackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKHALF2x16, result, arg); break;
1052 if(visit == PostVisit)
1054 int numCols = arg->getNominalSize();
1055 int numRows = arg->getSecondarySize();
1056 for(int i = 0; i < numCols; ++i)
1058 for(int j = 0; j < numRows; ++j)
1060 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, j, arg, i);
1061 mov->src[0].swizzle = 0x55 * j;
1062 mov->dst.mask = 1 << i;
1067 case EOpDeterminant:
1068 if(visit == PostVisit)
1070 int size = arg->getNominalSize();
1071 ASSERT(size == arg->getSecondarySize());
1073 emitDeterminant(result, arg, size);
1077 if(visit == PostVisit)
1079 int size = arg->getNominalSize();
1080 ASSERT(size == arg->getSecondarySize());
1082 // Compute transposed matrix of cofactors
1083 for(int i = 0; i < size; ++i)
1085 for(int j = 0; j < size; ++j)
1087 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
1088 // For a 3x3 or 4x4 matrix, the cofactor is a transposed determinant
1089 emitDeterminant(result, arg, size - 1, j, i, i, j);
1093 // Compute 1 / determinant
1094 Temporary invDet(this);
1095 emitDeterminant(&invDet, arg, size);
1096 Constant one(1.0f, 1.0f, 1.0f, 1.0f);
1097 Instruction *div = emit(sw::Shader::OPCODE_DIV, &invDet, &one, &invDet);
1098 div->src[1].swizzle = 0x00; // xxxx
1100 // Divide transposed matrix of cofactors by determinant
1101 for(int i = 0; i < size; ++i)
1103 emit(sw::Shader::OPCODE_MUL, result, i, result, i, &invDet);
1107 default: UNREACHABLE(node->getOp());
1113 bool OutputASM::visitAggregate(Visit visit, TIntermAggregate *node)
1115 if(currentScope != emitScope && node->getOp() != EOpFunction && node->getOp() != EOpSequence)
1120 Constant zero(0.0f, 0.0f, 0.0f, 0.0f);
1122 TIntermTyped *result = node;
1123 const TType &resultType = node->getType();
1124 TIntermSequence &arg = node->getSequence();
1125 size_t argumentCount = arg.size();
1127 switch(node->getOp())
1129 case EOpSequence: break;
1130 case EOpDeclaration: break;
1131 case EOpInvariantDeclaration: break;
1132 case EOpPrototype: break;
1134 if(visit == PostVisit)
1136 copy(result, arg[1]);
1140 if(visit == PreVisit)
1142 const TString &name = node->getName();
1144 if(emitScope == FUNCTION)
1146 if(functionArray.size() > 1) // No need for a label when there's only main()
1148 Instruction *label = emit(sw::Shader::OPCODE_LABEL);
1149 label->dst.type = sw::Shader::PARAMETER_LABEL;
1151 const Function *function = findFunction(name);
1152 ASSERT(function); // Should have been added during global pass
1153 label->dst.index = function->label;
1154 currentFunction = function->label;
1157 else if(emitScope == GLOBAL)
1161 TIntermSequence &arguments = node->getSequence()[0]->getAsAggregate()->getSequence();
1162 functionArray.push_back(Function(functionArray.size(), name, &arguments, node));
1165 else UNREACHABLE(emitScope);
1167 currentScope = FUNCTION;
1169 else if(visit == PostVisit)
1171 if(emitScope == FUNCTION)
1173 if(functionArray.size() > 1) // No need to return when there's only main()
1175 emit(sw::Shader::OPCODE_RET);
1179 currentScope = GLOBAL;
1182 case EOpFunctionCall:
1183 if(visit == PostVisit)
1185 if(node->isUserDefined())
1187 const TString &name = node->getName();
1188 const Function *function = findFunction(name);
1192 mContext.error(node->getLine(), "function definition not found", name.c_str());
1196 TIntermSequence &arguments = *function->arg;
1198 for(size_t i = 0; i < argumentCount; i++)
1200 TIntermTyped *in = arguments[i]->getAsTyped();
1202 if(in->getQualifier() == EvqIn ||
1203 in->getQualifier() == EvqInOut ||
1204 in->getQualifier() == EvqConstReadOnly)
1210 Instruction *call = emit(sw::Shader::OPCODE_CALL);
1211 call->dst.type = sw::Shader::PARAMETER_LABEL;
1212 call->dst.index = function->label;
1214 if(function->ret && function->ret->getType().getBasicType() != EbtVoid)
1216 copy(result, function->ret);
1219 for(size_t i = 0; i < argumentCount; i++)
1221 TIntermTyped *argument = arguments[i]->getAsTyped();
1222 TIntermTyped *out = arg[i]->getAsTyped();
1224 if(argument->getQualifier() == EvqOut ||
1225 argument->getQualifier() == EvqInOut)
1227 copy(out, argument);
1233 const TextureFunction textureFunction(node->getName());
1234 TIntermTyped *t = arg[1]->getAsTyped();
1236 Temporary coord(this);
1238 if(textureFunction.proj)
1240 TIntermConstantUnion* constant = arg[1]->getAsConstantUnion();
1243 float projFactor = 1.0f / constant->getFConst(t->getNominalSize() - 1);
1244 Constant projCoord(constant->getFConst(0) * projFactor,
1245 constant->getFConst(1) * projFactor,
1246 constant->getFConst(2) * projFactor,
1248 emit(sw::Shader::OPCODE_MOV, &coord, &projCoord);
1252 Instruction *rcp = emit(sw::Shader::OPCODE_RCPX, &coord, arg[1]);
1253 rcp->src[0].swizzle = 0x55 * (t->getNominalSize() - 1);
1254 rcp->dst.mask = 0x7;
1256 Instruction *mul = emit(sw::Shader::OPCODE_MUL, &coord, arg[1], &coord);
1257 mul->dst.mask = 0x7;
1262 emit(sw::Shader::OPCODE_MOV, &coord, arg[1]);
1265 switch(textureFunction.method)
1267 case TextureFunction::IMPLICIT:
1269 TIntermNode* offset = textureFunction.offset ? arg[2] : 0;
1271 if(argumentCount == 2 || (textureFunction.offset && argumentCount == 3))
1273 Instruction *tex = emit(textureFunction.offset ? sw::Shader::OPCODE_TEXOFFSET : sw::Shader::OPCODE_TEX,
1274 result, &coord, arg[0], offset);
1276 else if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4)) // bias
1278 Instruction *bias = emit(sw::Shader::OPCODE_MOV, &coord, arg[textureFunction.offset ? 3 : 2]);
1279 bias->dst.mask = 0x8;
1281 Instruction *tex = emit(textureFunction.offset ? sw::Shader::OPCODE_TEXOFFSET : sw::Shader::OPCODE_TEX,
1282 result, &coord, arg[0], offset); // FIXME: Implement an efficient TEXLDB instruction
1285 else UNREACHABLE(argumentCount);
1288 case TextureFunction::LOD:
1290 Instruction *lod = emit(sw::Shader::OPCODE_MOV, &coord, arg[2]);
1291 lod->dst.mask = 0x8;
1293 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXLDLOFFSET : sw::Shader::OPCODE_TEXLDL,
1294 result, &coord, arg[0], textureFunction.offset ? arg[3] : nullptr);
1297 case TextureFunction::FETCH:
1299 if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4))
1301 TIntermNode *offset = textureFunction.offset ? arg[3] : nullptr;
1303 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXELFETCHOFFSET : sw::Shader::OPCODE_TEXELFETCH,
1304 result, arg[1], arg[0], arg[2], offset);
1306 else UNREACHABLE(argumentCount);
1309 case TextureFunction::GRAD:
1311 if(argumentCount == 4 || (textureFunction.offset && argumentCount == 5))
1313 TIntermNode *offset = textureFunction.offset ? arg[4] : nullptr;
1315 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXGRADOFFSET : sw::Shader::OPCODE_TEXGRAD,
1316 result, &coord, arg[0], arg[2], arg[3], offset);
1318 else UNREACHABLE(argumentCount);
1321 case TextureFunction::SIZE:
1322 emit(sw::Shader::OPCODE_TEXSIZE, result, arg[1], arg[0]);
1325 UNREACHABLE(textureFunction.method);
1332 case EOpConstructFloat:
1333 case EOpConstructVec2:
1334 case EOpConstructVec3:
1335 case EOpConstructVec4:
1336 case EOpConstructBool:
1337 case EOpConstructBVec2:
1338 case EOpConstructBVec3:
1339 case EOpConstructBVec4:
1340 case EOpConstructInt:
1341 case EOpConstructIVec2:
1342 case EOpConstructIVec3:
1343 case EOpConstructIVec4:
1344 case EOpConstructUInt:
1345 case EOpConstructUVec2:
1346 case EOpConstructUVec3:
1347 case EOpConstructUVec4:
1348 if(visit == PostVisit)
1352 for(size_t i = 0; i < argumentCount; i++)
1354 TIntermTyped *argi = arg[i]->getAsTyped();
1355 int size = argi->getNominalSize();
1357 if(!argi->isMatrix())
1359 Instruction *mov = emitCast(result, argi);
1360 mov->dst.mask = (0xF << component) & 0xF;
1361 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1369 while(component < resultType.getNominalSize())
1371 Instruction *mov = emitCast(result, 0, argi, column);
1372 mov->dst.mask = (0xF << component) & 0xF;
1373 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1382 case EOpConstructMat2:
1383 case EOpConstructMat2x3:
1384 case EOpConstructMat2x4:
1385 case EOpConstructMat3x2:
1386 case EOpConstructMat3:
1387 case EOpConstructMat3x4:
1388 case EOpConstructMat4x2:
1389 case EOpConstructMat4x3:
1390 case EOpConstructMat4:
1391 if(visit == PostVisit)
1393 TIntermTyped *arg0 = arg[0]->getAsTyped();
1394 const int outCols = result->getNominalSize();
1395 const int outRows = result->getSecondarySize();
1397 if(arg0->isScalar() && arg.size() == 1) // Construct scale matrix
1399 for(int i = 0; i < outCols; i++)
1401 Instruction *init = emit(sw::Shader::OPCODE_MOV, result, i, &zero);
1402 Instruction *mov = emitCast(result, i, arg0, 0);
1403 mov->dst.mask = 1 << i;
1404 ASSERT(mov->src[0].swizzle == 0x00);
1407 else if(arg0->isMatrix())
1409 const int inCols = arg0->getNominalSize();
1410 const int inRows = arg0->getSecondarySize();
1412 for(int i = 0; i < outCols; i++)
1414 if(i >= inCols || outRows > inRows)
1416 // Initialize to identity matrix
1417 Constant col((i == 0 ? 1.0f : 0.0f), (i == 1 ? 1.0f : 0.0f), (i == 2 ? 1.0f : 0.0f), (i == 3 ? 1.0f : 0.0f));
1418 Instruction *mov = emitCast(result, i, &col, 0);
1423 Instruction *mov = emitCast(result, i, arg0, i);
1424 mov->dst.mask = 0xF >> (4 - inRows);
1433 for(size_t i = 0; i < argumentCount; i++)
1435 TIntermTyped *argi = arg[i]->getAsTyped();
1436 int size = argi->getNominalSize();
1439 while(element < size)
1441 Instruction *mov = emitCast(result, column, argi, 0);
1442 mov->dst.mask = (0xF << row) & 0xF;
1443 mov->src[0].swizzle = (readSwizzle(argi, size) << (row * 2)) + 0x55 * element;
1445 int end = row + size - element;
1446 column = end >= outRows ? column + 1 : column;
1447 element = element + outRows - row;
1448 row = end >= outRows ? 0 : end;
1454 case EOpConstructStruct:
1455 if(visit == PostVisit)
1458 for(size_t i = 0; i < argumentCount; i++)
1460 TIntermTyped *argi = arg[i]->getAsTyped();
1461 int size = argi->totalRegisterCount();
1463 for(int index = 0; index < size; index++)
1465 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index + offset, argi, index);
1466 mov->dst.mask = writeMask(result, offset + index);
1473 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, arg[0], arg[1]); break;
1474 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, arg[0], arg[1]); break;
1475 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, arg[0], arg[1]); break;
1476 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, arg[0], arg[1]); break;
1477 case EOpVectorEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_EQ, result, arg[0], arg[1]); break;
1478 case EOpVectorNotEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_NE, result, arg[0], arg[1]); break;
1479 case EOpMod: if(visit == PostVisit) emit(sw::Shader::OPCODE_MOD, result, arg[0], arg[1]); break;
1481 if(visit == PostVisit)
1483 TIntermTyped* arg1 = arg[1]->getAsTyped();
1484 emit(sw::Shader::OPCODE_TRUNC, arg1, arg[0]);
1485 assignLvalue(arg1, arg1);
1486 emitBinary(sw::Shader::OPCODE_SUB, result, arg[0], arg1);
1489 case EOpPow: if(visit == PostVisit) emit(sw::Shader::OPCODE_POW, result, arg[0], arg[1]); break;
1490 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN2, result, arg[0], arg[1]); break;
1491 case EOpMin: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, arg[0], arg[1]); break;
1492 case EOpMax: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]); break;
1494 if(visit == PostVisit)
1496 emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]);
1497 emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, result, arg[2]);
1500 case EOpMix: if(visit == PostVisit) emit(sw::Shader::OPCODE_LRP, result, arg[2], arg[1], arg[0]); break;
1501 case EOpStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_STEP, result, arg[0], arg[1]); break;
1502 case EOpSmoothStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_SMOOTH, result, arg[0], arg[1], arg[2]); break;
1503 case EOpDistance: if(visit == PostVisit) emit(sw::Shader::OPCODE_DIST(dim(arg[0])), result, arg[0], arg[1]); break;
1504 case EOpDot: if(visit == PostVisit) emit(sw::Shader::OPCODE_DP(dim(arg[0])), result, arg[0], arg[1]); break;
1505 case EOpCross: if(visit == PostVisit) emit(sw::Shader::OPCODE_CRS, result, arg[0], arg[1]); break;
1506 case EOpFaceForward: if(visit == PostVisit) emit(sw::Shader::OPCODE_FORWARD(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1507 case EOpReflect: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFLECT(dim(arg[0])), result, arg[0], arg[1]); break;
1508 case EOpRefract: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFRACT(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1510 if(visit == PostVisit)
1512 TIntermTyped *arg0 = arg[0]->getAsTyped();
1513 TIntermTyped *arg1 = arg[1]->getAsTyped();
1514 ASSERT((arg0->getNominalSize() == arg1->getNominalSize()) && (arg0->getSecondarySize() == arg1->getSecondarySize()));
1516 int size = arg0->getNominalSize();
1517 for(int i = 0; i < size; i++)
1519 emit(sw::Shader::OPCODE_MUL, result, i, arg[0], i, arg[1], i);
1523 case EOpOuterProduct:
1524 if(visit == PostVisit)
1526 for(int i = 0; i < dim(arg[1]); i++)
1528 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, arg[0], 0, arg[1]);
1529 mul->src[1].swizzle = 0x55 * i;
1533 default: UNREACHABLE(node->getOp());
1539 bool OutputASM::visitSelection(Visit visit, TIntermSelection *node)
1541 if(currentScope != emitScope)
1546 TIntermTyped *condition = node->getCondition();
1547 TIntermNode *trueBlock = node->getTrueBlock();
1548 TIntermNode *falseBlock = node->getFalseBlock();
1549 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
1551 condition->traverse(this);
1553 if(node->usesTernaryOperator())
1555 if(constantCondition)
1557 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1561 trueBlock->traverse(this);
1562 copy(node, trueBlock);
1566 falseBlock->traverse(this);
1567 copy(node, falseBlock);
1570 else if(trivial(node, 6)) // Fast to compute both potential results and no side effects
1572 trueBlock->traverse(this);
1573 falseBlock->traverse(this);
1574 emit(sw::Shader::OPCODE_SELECT, node, condition, trueBlock, falseBlock);
1578 emit(sw::Shader::OPCODE_IF, 0, condition);
1582 trueBlock->traverse(this);
1583 copy(node, trueBlock);
1588 emit(sw::Shader::OPCODE_ELSE);
1589 falseBlock->traverse(this);
1590 copy(node, falseBlock);
1593 emit(sw::Shader::OPCODE_ENDIF);
1596 else // if/else statement
1598 if(constantCondition)
1600 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1606 trueBlock->traverse(this);
1613 falseBlock->traverse(this);
1619 emit(sw::Shader::OPCODE_IF, 0, condition);
1623 trueBlock->traverse(this);
1628 emit(sw::Shader::OPCODE_ELSE);
1629 falseBlock->traverse(this);
1632 emit(sw::Shader::OPCODE_ENDIF);
1639 bool OutputASM::visitLoop(Visit visit, TIntermLoop *node)
1641 if(currentScope != emitScope)
1646 unsigned int iterations = loopCount(node);
1653 bool unroll = (iterations <= 4);
1657 LoopUnrollable loopUnrollable;
1658 unroll = loopUnrollable.traverse(node);
1661 TIntermNode *init = node->getInit();
1662 TIntermTyped *condition = node->getCondition();
1663 TIntermTyped *expression = node->getExpression();
1664 TIntermNode *body = node->getBody();
1665 Constant True(true);
1667 if(node->getType() == ELoopDoWhile)
1669 Temporary iterate(this);
1670 emit(sw::Shader::OPCODE_MOV, &iterate, &True);
1672 emit(sw::Shader::OPCODE_WHILE, 0, &iterate); // FIXME: Implement real do-while
1676 body->traverse(this);
1679 emit(sw::Shader::OPCODE_TEST);
1681 condition->traverse(this);
1682 emit(sw::Shader::OPCODE_MOV, &iterate, condition);
1684 emit(sw::Shader::OPCODE_ENDWHILE);
1690 init->traverse(this);
1695 for(unsigned int i = 0; i < iterations; i++)
1697 // condition->traverse(this); // Condition could contain statements, but not in an unrollable loop
1701 body->traverse(this);
1706 expression->traverse(this);
1714 condition->traverse(this);
1721 emit(sw::Shader::OPCODE_WHILE, 0, condition);
1725 body->traverse(this);
1728 emit(sw::Shader::OPCODE_TEST);
1732 expression->traverse(this);
1737 condition->traverse(this);
1740 emit(sw::Shader::OPCODE_ENDWHILE);
1747 bool OutputASM::visitBranch(Visit visit, TIntermBranch *node)
1749 if(currentScope != emitScope)
1754 switch(node->getFlowOp())
1756 case EOpKill: if(visit == PostVisit) emit(sw::Shader::OPCODE_DISCARD); break;
1757 case EOpBreak: if(visit == PostVisit) emit(sw::Shader::OPCODE_BREAK); break;
1758 case EOpContinue: if(visit == PostVisit) emit(sw::Shader::OPCODE_CONTINUE); break;
1760 if(visit == PostVisit)
1762 TIntermTyped *value = node->getExpression();
1766 copy(functionArray[currentFunction].ret, value);
1769 emit(sw::Shader::OPCODE_LEAVE);
1772 default: UNREACHABLE(node->getFlowOp());
1778 bool OutputASM::visitSwitch(Visit visit, TIntermSwitch *node)
1780 if(currentScope != emitScope)
1785 TIntermTyped* switchValue = node->getInit();
1786 TIntermAggregate* opList = node->getStatementList();
1788 if(!switchValue || !opList)
1793 switchValue->traverse(this);
1795 emit(sw::Shader::OPCODE_SWITCH);
1797 TIntermSequence& sequence = opList->getSequence();
1798 TIntermSequence::iterator it = sequence.begin();
1799 TIntermSequence::iterator defaultIt = sequence.end();
1801 for(; it != sequence.end(); ++it)
1803 TIntermCase* currentCase = (*it)->getAsCaseNode();
1806 TIntermSequence::iterator caseIt = it;
1808 TIntermTyped* condition = currentCase->getCondition();
1809 if(condition) // non default case
1813 emit(sw::Shader::OPCODE_ELSE);
1816 condition->traverse(this);
1817 Temporary result(this);
1818 emitBinary(sw::Shader::OPCODE_EQ, &result, switchValue, condition);
1819 emit(sw::Shader::OPCODE_IF, 0, &result);
1822 for(++caseIt; caseIt != sequence.end(); ++caseIt)
1824 (*caseIt)->traverse(this);
1825 if((*caseIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1833 defaultIt = it; // The default case might not be the last case, keep it for last
1838 // If there's a default case, traverse it here
1839 if(defaultIt != sequence.end())
1841 emit(sw::Shader::OPCODE_ELSE);
1842 for(++defaultIt; defaultIt != sequence.end(); ++defaultIt)
1844 (*defaultIt)->traverse(this);
1845 if((*defaultIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1852 for(int i = 0; i < nbCases; ++i)
1854 emit(sw::Shader::OPCODE_ENDIF);
1857 emit(sw::Shader::OPCODE_ENDSWITCH);
1862 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2, TIntermNode *src3, TIntermNode *src4)
1864 return emit(op, dst, 0, src0, 0, src1, 0, src2, 0, src3, 0, src4, 0);
1867 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, int dstIndex, TIntermNode *src0, int index0, TIntermNode *src1, int index1,
1868 TIntermNode *src2, int index2, TIntermNode *src3, int index3, TIntermNode *src4, int index4)
1870 Instruction *instruction = new Instruction(op);
1874 instruction->dst.type = registerType(dst);
1875 instruction->dst.index = registerIndex(dst) + dstIndex;
1876 instruction->dst.mask = writeMask(dst);
1877 instruction->dst.integer = (dst->getBasicType() == EbtInt);
1880 argument(instruction->src[0], src0, index0);
1881 argument(instruction->src[1], src1, index1);
1882 argument(instruction->src[2], src2, index2);
1883 argument(instruction->src[3], src3, index3);
1884 argument(instruction->src[4], src4, index4);
1886 shader->append(instruction);
1891 Instruction *OutputASM::emitCast(TIntermTyped *dst, TIntermTyped *src)
1893 return emitCast(dst, 0, src, 0);
1896 Instruction *OutputASM::emitCast(TIntermTyped *dst, int dstIndex, TIntermTyped *src, int srcIndex)
1898 switch(src->getBasicType())
1901 switch(dst->getBasicType())
1903 case EbtInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1904 case EbtUInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1905 case EbtFloat: return emit(sw::Shader::OPCODE_B2F, dst, dstIndex, src, srcIndex);
1910 switch(dst->getBasicType())
1912 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1913 case EbtFloat: return emit(sw::Shader::OPCODE_I2F, dst, dstIndex, src, srcIndex);
1918 switch(dst->getBasicType())
1920 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1921 case EbtFloat: return emit(sw::Shader::OPCODE_U2F, dst, dstIndex, src, srcIndex);
1926 switch(dst->getBasicType())
1928 case EbtBool: return emit(sw::Shader::OPCODE_F2B, dst, dstIndex, src, srcIndex);
1929 case EbtInt: return emit(sw::Shader::OPCODE_F2I, dst, dstIndex, src, srcIndex);
1930 case EbtUInt: return emit(sw::Shader::OPCODE_F2U, dst, dstIndex, src, srcIndex);
1938 ASSERT((src->getBasicType() == dst->getBasicType()) ||
1939 ((src->getBasicType() == EbtInt) && (dst->getBasicType() == EbtUInt)) ||
1940 ((src->getBasicType() == EbtUInt) && (dst->getBasicType() == EbtInt)));
1942 return emit(sw::Shader::OPCODE_MOV, dst, dstIndex, src, srcIndex);
1945 void OutputASM::emitBinary(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2)
1947 for(int index = 0; index < dst->elementRegisterCount(); index++)
1949 emit(op, dst, index, src0, index, src1, index, src2, index);
1953 void OutputASM::emitAssign(sw::Shader::Opcode op, TIntermTyped *result, TIntermTyped *lhs, TIntermTyped *src0, TIntermTyped *src1)
1955 emitBinary(op, result, src0, src1);
1956 assignLvalue(lhs, result);
1959 void OutputASM::emitCmp(sw::Shader::Control cmpOp, TIntermTyped *dst, TIntermNode *left, TIntermNode *right, int index)
1961 sw::Shader::Opcode opcode;
1962 switch(left->getAsTyped()->getBasicType())
1966 opcode = sw::Shader::OPCODE_ICMP;
1969 opcode = sw::Shader::OPCODE_UCMP;
1972 opcode = sw::Shader::OPCODE_CMP;
1976 Instruction *cmp = emit(opcode, dst, 0, left, index, right, index);
1977 cmp->control = cmpOp;
1980 int componentCount(const TType &type, int registers)
1987 if(type.isArray() && registers >= type.elementRegisterCount())
1989 int index = registers / type.elementRegisterCount();
1990 registers -= index * type.elementRegisterCount();
1991 return index * type.getElementSize() + componentCount(type, registers);
1994 if(type.isStruct() || type.isInterfaceBlock())
1996 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
1999 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2001 const TType &fieldType = *((*field)->type());
2003 if(fieldType.totalRegisterCount() <= registers)
2005 registers -= fieldType.totalRegisterCount();
2006 elements += fieldType.getObjectSize();
2008 else // Register within this field
2010 return elements + componentCount(fieldType, registers);
2014 else if(type.isMatrix())
2016 return registers * type.registerSize();
2023 int registerSize(const TType &type, int registers)
2029 return registerSize(*((*(type.getStruct()->fields().begin()))->type()), 0);
2031 else if(type.isInterfaceBlock())
2033 return registerSize(*((*(type.getInterfaceBlock()->fields().begin()))->type()), 0);
2036 return type.registerSize();
2039 if(type.isArray() && registers >= type.elementRegisterCount())
2041 int index = registers / type.elementRegisterCount();
2042 registers -= index * type.elementRegisterCount();
2043 return registerSize(type, registers);
2046 if(type.isStruct() || type.isInterfaceBlock())
2048 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2051 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2053 const TType &fieldType = *((*field)->type());
2055 if(fieldType.totalRegisterCount() <= registers)
2057 registers -= fieldType.totalRegisterCount();
2058 elements += fieldType.getObjectSize();
2060 else // Register within this field
2062 return registerSize(fieldType, registers);
2066 else if(type.isMatrix())
2068 return registerSize(type, 0);
2075 int OutputASM::getBlockId(TIntermTyped *arg)
2079 const TType &type = arg->getType();
2080 TInterfaceBlock* block = type.getInterfaceBlock();
2081 if(block && (type.getQualifier() == EvqUniform))
2083 // Make sure the uniform block is declared
2084 uniformRegister(arg);
2086 const char* blockName = block->name().c_str();
2088 // Fetch uniform block index from array of blocks
2089 for(ActiveUniformBlocks::const_iterator it = shaderObject->activeUniformBlocks.begin(); it != shaderObject->activeUniformBlocks.end(); ++it)
2091 if(blockName == it->name)
2104 OutputASM::ArgumentInfo OutputASM::getArgumentInfo(TIntermTyped *arg, int index)
2106 const TType &type = arg->getType();
2107 int blockId = getBlockId(arg);
2108 ArgumentInfo argumentInfo(BlockMemberInfo::getDefaultBlockInfo(), type, -1, -1);
2111 argumentInfo.bufferIndex = 0;
2112 for(int i = 0; i < blockId; ++i)
2114 int blockArraySize = shaderObject->activeUniformBlocks[i].arraySize;
2115 argumentInfo.bufferIndex += blockArraySize > 0 ? blockArraySize : 1;
2118 const BlockDefinitionIndexMap& blockDefinition = blockDefinitions[blockId];
2120 BlockDefinitionIndexMap::const_iterator itEnd = blockDefinition.end();
2121 BlockDefinitionIndexMap::const_iterator it = itEnd;
2123 argumentInfo.clampedIndex = index;
2124 if(type.isInterfaceBlock())
2126 // Offset index to the beginning of the selected instance
2127 int blockRegisters = type.elementRegisterCount();
2128 int bufferOffset = argumentInfo.clampedIndex / blockRegisters;
2129 argumentInfo.bufferIndex += bufferOffset;
2130 argumentInfo.clampedIndex -= bufferOffset * blockRegisters;
2133 int regIndex = registerIndex(arg);
2134 for(int i = regIndex + argumentInfo.clampedIndex; i >= regIndex; --i)
2136 it = blockDefinition.find(i);
2139 argumentInfo.clampedIndex -= (i - regIndex);
2143 ASSERT(it != itEnd);
2145 argumentInfo.typedMemberInfo = it->second;
2147 int registerCount = argumentInfo.typedMemberInfo.type.totalRegisterCount();
2148 argumentInfo.clampedIndex = (argumentInfo.clampedIndex >= registerCount) ? registerCount - 1 : argumentInfo.clampedIndex;
2152 argumentInfo.clampedIndex = (index >= arg->totalRegisterCount()) ? arg->totalRegisterCount() - 1 : index;
2155 return argumentInfo;
2158 void OutputASM::argument(sw::Shader::SourceParameter ¶meter, TIntermNode *argument, int index)
2162 TIntermTyped *arg = argument->getAsTyped();
2163 Temporary unpackedUniform(this);
2165 const TType& srcType = arg->getType();
2166 TInterfaceBlock* srcBlock = srcType.getInterfaceBlock();
2167 if(srcBlock && (srcType.getQualifier() == EvqUniform))
2169 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2170 const TType &memberType = argumentInfo.typedMemberInfo.type;
2172 if(memberType.getBasicType() == EbtBool)
2174 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2175 ASSERT(argumentInfo.clampedIndex < arraySize);
2177 // Convert the packed bool, which is currently an int, to a true bool
2178 Instruction *instruction = new Instruction(sw::Shader::OPCODE_I2B);
2179 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2180 instruction->dst.index = registerIndex(&unpackedUniform);
2181 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2182 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2183 instruction->src[0].index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * argumentInfo.typedMemberInfo.arrayStride;
2185 shader->append(instruction);
2187 arg = &unpackedUniform;
2190 else if((srcBlock->matrixPacking() == EmpRowMajor) && memberType.isMatrix())
2192 int numCols = memberType.getNominalSize();
2193 int numRows = memberType.getSecondarySize();
2194 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2196 ASSERT(argumentInfo.clampedIndex < (numCols * arraySize));
2198 unsigned int dstIndex = registerIndex(&unpackedUniform);
2199 unsigned int srcSwizzle = (argumentInfo.clampedIndex % numCols) * 0x55;
2200 int arrayIndex = argumentInfo.clampedIndex / numCols;
2201 int matrixStartOffset = argumentInfo.typedMemberInfo.offset + arrayIndex * argumentInfo.typedMemberInfo.arrayStride;
2203 for(int j = 0; j < numRows; ++j)
2205 // Transpose the row major matrix
2206 Instruction *instruction = new Instruction(sw::Shader::OPCODE_MOV);
2207 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2208 instruction->dst.index = dstIndex;
2209 instruction->dst.mask = 1 << j;
2210 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2211 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2212 instruction->src[0].index = matrixStartOffset + j * argumentInfo.typedMemberInfo.matrixStride;
2213 instruction->src[0].swizzle = srcSwizzle;
2215 shader->append(instruction);
2218 arg = &unpackedUniform;
2223 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2224 const TType &type = argumentInfo.typedMemberInfo.type;
2226 int size = registerSize(type, argumentInfo.clampedIndex);
2228 parameter.type = registerType(arg);
2229 parameter.bufferIndex = argumentInfo.bufferIndex;
2231 if(arg->getAsConstantUnion() && arg->getAsConstantUnion()->getUnionArrayPointer())
2233 int component = componentCount(type, argumentInfo.clampedIndex);
2234 ConstantUnion *constants = arg->getAsConstantUnion()->getUnionArrayPointer();
2236 for(int i = 0; i < 4; i++)
2238 if(size == 1) // Replicate
2240 parameter.value[i] = constants[component + 0].getAsFloat();
2244 parameter.value[i] = constants[component + i].getAsFloat();
2248 parameter.value[i] = 0.0f;
2254 parameter.index = registerIndex(arg) + argumentInfo.clampedIndex;
2256 if(parameter.bufferIndex != -1)
2258 int stride = (argumentInfo.typedMemberInfo.matrixStride > 0) ? argumentInfo.typedMemberInfo.matrixStride : argumentInfo.typedMemberInfo.arrayStride;
2259 parameter.index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * stride;
2263 if(!IsSampler(arg->getBasicType()))
2265 parameter.swizzle = readSwizzle(arg, size);
2270 void OutputASM::copy(TIntermTyped *dst, TIntermNode *src, int offset)
2272 for(int index = 0; index < dst->totalRegisterCount(); index++)
2274 Instruction *mov = emit(sw::Shader::OPCODE_MOV, dst, index, src, offset + index);
2275 mov->dst.mask = writeMask(dst, index);
2279 int swizzleElement(int swizzle, int index)
2281 return (swizzle >> (index * 2)) & 0x03;
2284 int swizzleSwizzle(int leftSwizzle, int rightSwizzle)
2286 return (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 0)) << 0) |
2287 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 1)) << 2) |
2288 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 2)) << 4) |
2289 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 3)) << 6);
2292 void OutputASM::assignLvalue(TIntermTyped *dst, TIntermTyped *src)
2295 ((src->isVector() && (!dst->isVector() || (src->getNominalSize() != dst->getNominalSize()))) ||
2296 (src->isMatrix() && (!dst->isMatrix() || (src->getNominalSize() != dst->getNominalSize()) || (src->getSecondarySize() != dst->getSecondarySize())))))
2298 return mContext.error(src->getLine(), "Result type should match the l-value type in compound assignment", src->isVector() ? "vector" : "matrix");
2301 TIntermBinary *binary = dst->getAsBinaryNode();
2303 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && dst->isScalar())
2305 Instruction *insert = new Instruction(sw::Shader::OPCODE_INSERT);
2307 Temporary address(this);
2308 lvalue(insert->dst, address, dst);
2310 insert->src[0].type = insert->dst.type;
2311 insert->src[0].index = insert->dst.index;
2312 insert->src[0].rel = insert->dst.rel;
2313 argument(insert->src[1], src);
2314 argument(insert->src[2], binary->getRight());
2316 shader->append(insert);
2320 for(int offset = 0; offset < dst->totalRegisterCount(); offset++)
2322 Instruction *mov = new Instruction(sw::Shader::OPCODE_MOV);
2324 Temporary address(this);
2325 int swizzle = lvalue(mov->dst, address, dst);
2326 mov->dst.index += offset;
2330 mov->dst.mask = writeMask(dst, offset);
2333 argument(mov->src[0], src, offset);
2334 mov->src[0].swizzle = swizzleSwizzle(mov->src[0].swizzle, swizzle);
2336 shader->append(mov);
2341 int OutputASM::lvalue(sw::Shader::DestinationParameter &dst, Temporary &address, TIntermTyped *node)
2343 TIntermTyped *result = node;
2344 TIntermBinary *binary = node->getAsBinaryNode();
2345 TIntermSymbol *symbol = node->getAsSymbolNode();
2349 TIntermTyped *left = binary->getLeft();
2350 TIntermTyped *right = binary->getRight();
2352 int leftSwizzle = lvalue(dst, address, left); // Resolve the l-value of the left side
2354 switch(binary->getOp())
2356 case EOpIndexDirect:
2358 int rightIndex = right->getAsConstantUnion()->getIConst(0);
2360 if(left->isRegister())
2362 int leftMask = dst.mask;
2365 while((leftMask & dst.mask) == 0)
2367 dst.mask = dst.mask << 1;
2370 int element = swizzleElement(leftSwizzle, rightIndex);
2371 dst.mask = 1 << element;
2375 else if(left->isArray() || left->isMatrix())
2377 dst.index += rightIndex * result->totalRegisterCount();
2380 else UNREACHABLE(0);
2383 case EOpIndexIndirect:
2385 if(left->isRegister())
2387 // Requires INSERT instruction (handled by calling function)
2389 else if(left->isArray() || left->isMatrix())
2391 int scale = result->totalRegisterCount();
2393 if(dst.rel.type == sw::Shader::PARAMETER_VOID) // Use the index register as the relative address directly
2395 if(left->totalRegisterCount() > 1)
2397 sw::Shader::SourceParameter relativeRegister;
2398 argument(relativeRegister, right);
2400 dst.rel.index = relativeRegister.index;
2401 dst.rel.type = relativeRegister.type;
2402 dst.rel.scale = scale;
2403 dst.rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
2406 else if(dst.rel.index != registerIndex(&address)) // Move the previous index register to the address register
2410 Constant oldScale((int)dst.rel.scale);
2411 Instruction *mad = emit(sw::Shader::OPCODE_IMAD, &address, &address, &oldScale, right);
2412 mad->src[0].index = dst.rel.index;
2413 mad->src[0].type = dst.rel.type;
2417 Constant oldScale((int)dst.rel.scale);
2418 Instruction *mul = emit(sw::Shader::OPCODE_IMUL, &address, &address, &oldScale);
2419 mul->src[0].index = dst.rel.index;
2420 mul->src[0].type = dst.rel.type;
2422 Constant newScale(scale);
2423 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2426 dst.rel.type = sw::Shader::PARAMETER_TEMP;
2427 dst.rel.index = registerIndex(&address);
2430 else // Just add the new index to the address register
2434 emit(sw::Shader::OPCODE_IADD, &address, &address, right);
2438 Constant newScale(scale);
2439 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2443 else UNREACHABLE(0);
2446 case EOpIndexDirectStruct:
2447 case EOpIndexDirectInterfaceBlock:
2449 const TFieldList& fields = (binary->getOp() == EOpIndexDirectStruct) ?
2450 left->getType().getStruct()->fields() :
2451 left->getType().getInterfaceBlock()->fields();
2452 int index = right->getAsConstantUnion()->getIConst(0);
2453 int fieldOffset = 0;
2455 for(int i = 0; i < index; i++)
2457 fieldOffset += fields[i]->type()->totalRegisterCount();
2460 dst.type = registerType(left);
2461 dst.index += fieldOffset;
2462 dst.mask = writeMask(right);
2467 case EOpVectorSwizzle:
2469 ASSERT(left->isRegister());
2471 int leftMask = dst.mask;
2476 TIntermSequence &sequence = right->getAsAggregate()->getSequence();
2478 for(unsigned int i = 0; i < sequence.size(); i++)
2480 int index = sequence[i]->getAsConstantUnion()->getIConst(0);
2482 int element = swizzleElement(leftSwizzle, index);
2483 rightMask = rightMask | (1 << element);
2484 swizzle = swizzle | swizzleElement(leftSwizzle, i) << (element * 2);
2487 dst.mask = leftMask & rightMask;
2493 UNREACHABLE(binary->getOp()); // Not an l-value operator
2499 dst.type = registerType(symbol);
2500 dst.index = registerIndex(symbol);
2501 dst.mask = writeMask(symbol);
2508 sw::Shader::ParameterType OutputASM::registerType(TIntermTyped *operand)
2510 if(isSamplerRegister(operand))
2512 return sw::Shader::PARAMETER_SAMPLER;
2515 const TQualifier qualifier = operand->getQualifier();
2516 if((EvqFragColor == qualifier) || (EvqFragData == qualifier))
2518 if(((EvqFragData == qualifier) && (EvqFragColor == outputQualifier)) ||
2519 ((EvqFragColor == qualifier) && (EvqFragData == outputQualifier)))
2521 mContext.error(operand->getLine(), "static assignment to both gl_FragData and gl_FragColor", "");
2523 outputQualifier = qualifier;
2526 if(qualifier == EvqConstExpr && (!operand->getAsConstantUnion() || !operand->getAsConstantUnion()->getUnionArrayPointer()))
2528 return sw::Shader::PARAMETER_TEMP;
2533 case EvqTemporary: return sw::Shader::PARAMETER_TEMP;
2534 case EvqGlobal: return sw::Shader::PARAMETER_TEMP;
2535 case EvqConstExpr: return sw::Shader::PARAMETER_FLOAT4LITERAL; // All converted to float
2536 case EvqAttribute: return sw::Shader::PARAMETER_INPUT;
2537 case EvqVaryingIn: return sw::Shader::PARAMETER_INPUT;
2538 case EvqVaryingOut: return sw::Shader::PARAMETER_OUTPUT;
2539 case EvqVertexIn: return sw::Shader::PARAMETER_INPUT;
2540 case EvqFragmentOut: return sw::Shader::PARAMETER_COLOROUT;
2541 case EvqVertexOut: return sw::Shader::PARAMETER_OUTPUT;
2542 case EvqFragmentIn: return sw::Shader::PARAMETER_INPUT;
2543 case EvqInvariantVaryingIn: return sw::Shader::PARAMETER_INPUT; // FIXME: Guarantee invariance at the backend
2544 case EvqInvariantVaryingOut: return sw::Shader::PARAMETER_OUTPUT; // FIXME: Guarantee invariance at the backend
2545 case EvqSmooth: return sw::Shader::PARAMETER_OUTPUT;
2546 case EvqFlat: return sw::Shader::PARAMETER_OUTPUT;
2547 case EvqCentroidOut: return sw::Shader::PARAMETER_OUTPUT;
2548 case EvqSmoothIn: return sw::Shader::PARAMETER_INPUT;
2549 case EvqFlatIn: return sw::Shader::PARAMETER_INPUT;
2550 case EvqCentroidIn: return sw::Shader::PARAMETER_INPUT;
2551 case EvqUniform: return sw::Shader::PARAMETER_CONST;
2552 case EvqIn: return sw::Shader::PARAMETER_TEMP;
2553 case EvqOut: return sw::Shader::PARAMETER_TEMP;
2554 case EvqInOut: return sw::Shader::PARAMETER_TEMP;
2555 case EvqConstReadOnly: return sw::Shader::PARAMETER_TEMP;
2556 case EvqPosition: return sw::Shader::PARAMETER_OUTPUT;
2557 case EvqPointSize: return sw::Shader::PARAMETER_OUTPUT;
2558 case EvqInstanceID: return sw::Shader::PARAMETER_MISCTYPE;
2559 case EvqFragCoord: return sw::Shader::PARAMETER_MISCTYPE;
2560 case EvqFrontFacing: return sw::Shader::PARAMETER_MISCTYPE;
2561 case EvqPointCoord: return sw::Shader::PARAMETER_INPUT;
2562 case EvqFragColor: return sw::Shader::PARAMETER_COLOROUT;
2563 case EvqFragData: return sw::Shader::PARAMETER_COLOROUT;
2564 case EvqFragDepth: return sw::Shader::PARAMETER_DEPTHOUT;
2565 default: UNREACHABLE(qualifier);
2568 return sw::Shader::PARAMETER_VOID;
2571 unsigned int OutputASM::registerIndex(TIntermTyped *operand)
2573 if(isSamplerRegister(operand))
2575 return samplerRegister(operand);
2578 switch(operand->getQualifier())
2580 case EvqTemporary: return temporaryRegister(operand);
2581 case EvqGlobal: return temporaryRegister(operand);
2582 case EvqConstExpr: return temporaryRegister(operand); // Unevaluated constant expression
2583 case EvqAttribute: return attributeRegister(operand);
2584 case EvqVaryingIn: return varyingRegister(operand);
2585 case EvqVaryingOut: return varyingRegister(operand);
2586 case EvqVertexIn: return attributeRegister(operand);
2587 case EvqFragmentOut: return fragmentOutputRegister(operand);
2588 case EvqVertexOut: return varyingRegister(operand);
2589 case EvqFragmentIn: return varyingRegister(operand);
2590 case EvqInvariantVaryingIn: return varyingRegister(operand);
2591 case EvqInvariantVaryingOut: return varyingRegister(operand);
2592 case EvqSmooth: return varyingRegister(operand);
2593 case EvqFlat: return varyingRegister(operand);
2594 case EvqCentroidOut: return varyingRegister(operand);
2595 case EvqSmoothIn: return varyingRegister(operand);
2596 case EvqFlatIn: return varyingRegister(operand);
2597 case EvqCentroidIn: return varyingRegister(operand);
2598 case EvqUniform: return uniformRegister(operand);
2599 case EvqIn: return temporaryRegister(operand);
2600 case EvqOut: return temporaryRegister(operand);
2601 case EvqInOut: return temporaryRegister(operand);
2602 case EvqConstReadOnly: return temporaryRegister(operand);
2603 case EvqPosition: return varyingRegister(operand);
2604 case EvqPointSize: return varyingRegister(operand);
2605 case EvqInstanceID: vertexShader->instanceIdDeclared = true; return 0;
2606 case EvqFragCoord: pixelShader->vPosDeclared = true; return 0;
2607 case EvqFrontFacing: pixelShader->vFaceDeclared = true; return 1;
2608 case EvqPointCoord: return varyingRegister(operand);
2609 case EvqFragColor: return 0;
2610 case EvqFragData: return fragmentOutputRegister(operand);
2611 case EvqFragDepth: return 0;
2612 default: UNREACHABLE(operand->getQualifier());
2618 int OutputASM::writeMask(TIntermTyped *destination, int index)
2620 if(destination->getQualifier() == EvqPointSize)
2622 return 0x2; // Point size stored in the y component
2625 return 0xF >> (4 - registerSize(destination->getType(), index));
2628 int OutputASM::readSwizzle(TIntermTyped *argument, int size)
2630 if(argument->getQualifier() == EvqPointSize)
2632 return 0x55; // Point size stored in the y component
2635 static const unsigned char swizzleSize[5] = {0x00, 0x00, 0x54, 0xA4, 0xE4}; // (void), xxxx, xyyy, xyzz, xyzw
2637 return swizzleSize[size];
2640 // Conservatively checks whether an expression is fast to compute and has no side effects
2641 bool OutputASM::trivial(TIntermTyped *expression, int budget)
2643 if(!expression->isRegister())
2648 return cost(expression, budget) >= 0;
2651 // Returns the remaining computing budget (if < 0 the expression is too expensive or has side effects)
2652 int OutputASM::cost(TIntermNode *expression, int budget)
2659 if(expression->getAsSymbolNode())
2663 else if(expression->getAsConstantUnion())
2667 else if(expression->getAsBinaryNode())
2669 TIntermBinary *binary = expression->getAsBinaryNode();
2671 switch(binary->getOp())
2673 case EOpVectorSwizzle:
2674 case EOpIndexDirect:
2675 case EOpIndexDirectStruct:
2676 case EOpIndexDirectInterfaceBlock:
2677 return cost(binary->getLeft(), budget - 0);
2681 return cost(binary->getLeft(), cost(binary->getRight(), budget - 1));
2686 else if(expression->getAsUnaryNode())
2688 TIntermUnary *unary = expression->getAsUnaryNode();
2690 switch(unary->getOp())
2694 return cost(unary->getOperand(), budget - 1);
2699 else if(expression->getAsSelectionNode())
2701 TIntermSelection *selection = expression->getAsSelectionNode();
2703 if(selection->usesTernaryOperator())
2705 TIntermTyped *condition = selection->getCondition();
2706 TIntermNode *trueBlock = selection->getTrueBlock();
2707 TIntermNode *falseBlock = selection->getFalseBlock();
2708 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
2710 if(constantCondition)
2712 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
2716 return cost(trueBlock, budget - 0);
2720 return cost(falseBlock, budget - 0);
2725 return cost(trueBlock, cost(falseBlock, budget - 2));
2733 const Function *OutputASM::findFunction(const TString &name)
2735 for(unsigned int f = 0; f < functionArray.size(); f++)
2737 if(functionArray[f].name == name)
2739 return &functionArray[f];
2746 int OutputASM::temporaryRegister(TIntermTyped *temporary)
2748 return allocate(temporaries, temporary);
2751 int OutputASM::varyingRegister(TIntermTyped *varying)
2753 int var = lookup(varyings, varying);
2757 var = allocate(varyings, varying);
2758 int componentCount = varying->registerSize();
2759 int registerCount = varying->totalRegisterCount();
2763 if((var + registerCount) > sw::MAX_FRAGMENT_INPUTS)
2765 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "fragment shader");
2769 if(varying->getQualifier() == EvqPointCoord)
2771 ASSERT(varying->isRegister());
2772 if(componentCount >= 1) pixelShader->semantic[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2773 if(componentCount >= 2) pixelShader->semantic[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2774 if(componentCount >= 3) pixelShader->semantic[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2775 if(componentCount >= 4) pixelShader->semantic[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2779 for(int i = 0; i < varying->totalRegisterCount(); i++)
2781 if(componentCount >= 1) pixelShader->semantic[var + i][0] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2782 if(componentCount >= 2) pixelShader->semantic[var + i][1] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2783 if(componentCount >= 3) pixelShader->semantic[var + i][2] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2784 if(componentCount >= 4) pixelShader->semantic[var + i][3] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2788 else if(vertexShader)
2790 if((var + registerCount) > sw::MAX_VERTEX_OUTPUTS)
2792 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "vertex shader");
2796 if(varying->getQualifier() == EvqPosition)
2798 ASSERT(varying->isRegister());
2799 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2800 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2801 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2802 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2803 vertexShader->positionRegister = var;
2805 else if(varying->getQualifier() == EvqPointSize)
2807 ASSERT(varying->isRegister());
2808 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2809 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2810 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2811 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2812 vertexShader->pointSizeRegister = var;
2816 // Semantic indexes for user varyings will be assigned during program link to match the pixel shader
2819 else UNREACHABLE(0);
2821 declareVarying(varying, var);
2827 void OutputASM::declareVarying(TIntermTyped *varying, int reg)
2829 if(varying->getQualifier() != EvqPointCoord) // gl_PointCoord does not need linking
2831 const TType &type = varying->getType();
2832 const char *name = varying->getAsSymbolNode()->getSymbol().c_str();
2833 VaryingList &activeVaryings = shaderObject->varyings;
2835 // Check if this varying has been declared before without having a register assigned
2836 for(VaryingList::iterator v = activeVaryings.begin(); v != activeVaryings.end(); v++)
2842 ASSERT(v->reg < 0 || v->reg == reg);
2850 activeVaryings.push_back(glsl::Varying(glVariableType(type), name, varying->getArraySize(), reg, 0));
2854 int OutputASM::uniformRegister(TIntermTyped *uniform)
2856 const TType &type = uniform->getType();
2857 ASSERT(!IsSampler(type.getBasicType()));
2858 TInterfaceBlock *block = type.getAsInterfaceBlock();
2859 TIntermSymbol *symbol = uniform->getAsSymbolNode();
2860 ASSERT(symbol || block);
2864 TInterfaceBlock* parentBlock = type.getInterfaceBlock();
2865 bool isBlockMember = (!block && parentBlock);
2866 int index = isBlockMember ? lookup(uniforms, parentBlock) : lookup(uniforms, uniform);
2868 if(index == -1 || isBlockMember)
2872 index = allocate(uniforms, uniform);
2875 // Verify if the current uniform is a member of an already declared block
2876 const TString &name = symbol ? symbol->getSymbol() : block->name();
2877 int blockMemberIndex = blockMemberLookup(type, name, index);
2878 if(blockMemberIndex == -1)
2880 declareUniform(type, name, index);
2884 index = blockMemberIndex;
2894 int OutputASM::attributeRegister(TIntermTyped *attribute)
2896 ASSERT(!attribute->isArray());
2898 int index = lookup(attributes, attribute);
2902 TIntermSymbol *symbol = attribute->getAsSymbolNode();
2907 index = allocate(attributes, attribute);
2908 const TType &type = attribute->getType();
2909 int registerCount = attribute->totalRegisterCount();
2911 if(vertexShader && (index + registerCount) <= sw::MAX_VERTEX_INPUTS)
2913 for(int i = 0; i < registerCount; i++)
2915 vertexShader->input[index + i] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, index + i);
2919 ActiveAttributes &activeAttributes = shaderObject->activeAttributes;
2921 const char *name = symbol->getSymbol().c_str();
2922 activeAttributes.push_back(Attribute(glVariableType(type), name, type.getArraySize(), type.getLayoutQualifier().location, index));
2929 int OutputASM::fragmentOutputRegister(TIntermTyped *fragmentOutput)
2931 return allocate(fragmentOutputs, fragmentOutput);
2934 int OutputASM::samplerRegister(TIntermTyped *sampler)
2936 const TType &type = sampler->getType();
2937 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
2939 TIntermSymbol *symbol = sampler->getAsSymbolNode();
2940 TIntermBinary *binary = sampler->getAsBinaryNode();
2942 if(symbol && type.getQualifier() == EvqUniform)
2944 return samplerRegister(symbol);
2948 TIntermTyped *left = binary->getLeft();
2949 TIntermTyped *right = binary->getRight();
2950 const TType &leftType = left->getType();
2951 int index = right->getAsConstantUnion() ? right->getAsConstantUnion()->getIConst(0) : 0;
2954 switch(binary->getOp())
2956 case EOpIndexDirect:
2957 ASSERT(left->isArray());
2958 offset = index * leftType.elementRegisterCount();
2960 case EOpIndexDirectStruct:
2961 ASSERT(leftType.isStruct());
2963 const TFieldList &fields = leftType.getStruct()->fields();
2965 for(int i = 0; i < index; i++)
2967 offset += fields[i]->type()->totalRegisterCount();
2971 case EOpIndexIndirect: // Indirect indexing produces a temporary, not a sampler register
2973 case EOpIndexDirectInterfaceBlock: // Interface blocks can't contain samplers
2975 UNREACHABLE(binary->getOp());
2979 int base = samplerRegister(left);
2986 return base + offset;
2990 return -1; // Not a sampler register
2993 int OutputASM::samplerRegister(TIntermSymbol *sampler)
2995 const TType &type = sampler->getType();
2996 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
2998 int index = lookup(samplers, sampler);
3002 index = allocate(samplers, sampler);
3004 if(sampler->getQualifier() == EvqUniform)
3006 const char *name = sampler->getSymbol().c_str();
3007 declareUniform(type, name, index);
3014 bool OutputASM::isSamplerRegister(TIntermTyped *operand)
3016 return operand && IsSampler(operand->getBasicType()) && samplerRegister(operand) >= 0;
3019 int OutputASM::lookup(VariableArray &list, TIntermTyped *variable)
3021 for(unsigned int i = 0; i < list.size(); i++)
3023 if(list[i] == variable)
3025 return i; // Pointer match
3029 TIntermSymbol *varSymbol = variable->getAsSymbolNode();
3030 TInterfaceBlock *varBlock = variable->getType().getAsInterfaceBlock();
3034 for(unsigned int i = 0; i < list.size(); i++)
3038 TInterfaceBlock *listBlock = list[i]->getType().getAsInterfaceBlock();
3042 if(listBlock->name() == varBlock->name())
3044 ASSERT(listBlock->arraySize() == varBlock->arraySize());
3045 ASSERT(listBlock->fields() == varBlock->fields());
3046 ASSERT(listBlock->blockStorage() == varBlock->blockStorage());
3047 ASSERT(listBlock->matrixPacking() == varBlock->matrixPacking());
3057 for(unsigned int i = 0; i < list.size(); i++)
3061 TIntermSymbol *listSymbol = list[i]->getAsSymbolNode();
3065 if(listSymbol->getId() == varSymbol->getId())
3067 ASSERT(listSymbol->getSymbol() == varSymbol->getSymbol());
3068 ASSERT(listSymbol->getType() == varSymbol->getType());
3069 ASSERT(listSymbol->getQualifier() == varSymbol->getQualifier());
3081 int OutputASM::lookup(VariableArray &list, TInterfaceBlock *block)
3083 for(unsigned int i = 0; i < list.size(); i++)
3085 if(list[i] && (list[i]->getType().getInterfaceBlock() == block))
3087 return i; // Pointer match
3093 int OutputASM::allocate(VariableArray &list, TIntermTyped *variable)
3095 int index = lookup(list, variable);
3099 unsigned int registerCount = variable->blockRegisterCount();
3101 for(unsigned int i = 0; i < list.size(); i++)
3106 for( ; j < registerCount && (i + j) < list.size(); j++)
3108 if(list[i + j] != 0)
3114 if(j == registerCount) // Found free slots
3116 for(unsigned int j = 0; j < registerCount; j++)
3118 list[i + j] = variable;
3126 index = list.size();
3128 for(unsigned int i = 0; i < registerCount; i++)
3130 list.push_back(variable);
3137 void OutputASM::free(VariableArray &list, TIntermTyped *variable)
3139 int index = lookup(list, variable);
3147 int OutputASM::blockMemberLookup(const TType &type, const TString &name, int registerIndex)
3149 const TInterfaceBlock *block = type.getInterfaceBlock();
3153 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3154 const TFieldList& fields = block->fields();
3155 const TString &blockName = block->name();
3156 int fieldRegisterIndex = registerIndex;
3158 if(!type.isInterfaceBlock())
3160 // This is a uniform that's part of a block, let's see if the block is already defined
3161 for(size_t i = 0; i < activeUniformBlocks.size(); ++i)
3163 if(activeUniformBlocks[i].name == blockName.c_str())
3165 // The block is already defined, find the register for the current uniform and return it
3166 for(size_t j = 0; j < fields.size(); j++)
3168 const TString &fieldName = fields[j]->name();
3169 if(fieldName == name)
3171 return fieldRegisterIndex;
3174 fieldRegisterIndex += fields[j]->type()->totalRegisterCount();
3178 return fieldRegisterIndex;
3187 void OutputASM::declareUniform(const TType &type, const TString &name, int registerIndex, int blockId, BlockLayoutEncoder* encoder)
3189 const TStructure *structure = type.getStruct();
3190 const TInterfaceBlock *block = (type.isInterfaceBlock() || (blockId == -1)) ? type.getInterfaceBlock() : nullptr;
3192 if(!structure && !block)
3194 ActiveUniforms &activeUniforms = shaderObject->activeUniforms;
3195 const BlockMemberInfo blockInfo = encoder ? encoder->encodeType(type) : BlockMemberInfo::getDefaultBlockInfo();
3198 blockDefinitions[blockId][registerIndex] = TypedMemberInfo(blockInfo, type);
3199 shaderObject->activeUniformBlocks[blockId].fields.push_back(activeUniforms.size());
3201 int fieldRegisterIndex = encoder ? shaderObject->activeUniformBlocks[blockId].registerIndex + BlockLayoutEncoder::getBlockRegister(blockInfo) : registerIndex;
3202 activeUniforms.push_back(Uniform(glVariableType(type), glVariablePrecision(type), name.c_str(), type.getArraySize(),
3203 fieldRegisterIndex, blockId, blockInfo));
3204 if(IsSampler(type.getBasicType()))
3206 for(int i = 0; i < type.totalRegisterCount(); i++)
3208 shader->declareSampler(fieldRegisterIndex + i);
3214 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3215 const TFieldList& fields = block->fields();
3216 const TString &blockName = block->name();
3217 int fieldRegisterIndex = registerIndex;
3218 bool isUniformBlockMember = !type.isInterfaceBlock() && (blockId == -1);
3220 blockId = activeUniformBlocks.size();
3221 bool isRowMajor = block->matrixPacking() == EmpRowMajor;
3222 activeUniformBlocks.push_back(UniformBlock(blockName.c_str(), 0, block->arraySize(),
3223 block->blockStorage(), isRowMajor, registerIndex, blockId));
3224 blockDefinitions.push_back(BlockDefinitionIndexMap());
3226 Std140BlockEncoder currentBlockEncoder(isRowMajor);
3227 currentBlockEncoder.enterAggregateType();
3228 for(size_t i = 0; i < fields.size(); i++)
3230 const TType &fieldType = *(fields[i]->type());
3231 const TString &fieldName = fields[i]->name();
3232 if(isUniformBlockMember && (fieldName == name))
3234 registerIndex = fieldRegisterIndex;
3237 const TString uniformName = block->hasInstanceName() ? blockName + "." + fieldName : fieldName;
3239 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, ¤tBlockEncoder);
3240 fieldRegisterIndex += fieldType.totalRegisterCount();
3242 currentBlockEncoder.exitAggregateType();
3243 activeUniformBlocks[blockId].dataSize = currentBlockEncoder.getBlockSize();
3247 int fieldRegisterIndex = registerIndex;
3249 const TFieldList& fields = structure->fields();
3250 if(type.isArray() && (structure || type.isInterfaceBlock()))
3252 for(int i = 0; i < type.getArraySize(); i++)
3256 encoder->enterAggregateType();
3258 for(size_t j = 0; j < fields.size(); j++)
3260 const TType &fieldType = *(fields[j]->type());
3261 const TString &fieldName = fields[j]->name();
3262 const TString uniformName = name + "[" + str(i) + "]." + fieldName;
3264 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3265 fieldRegisterIndex += fieldType.totalRegisterCount();
3269 encoder->exitAggregateType();
3277 encoder->enterAggregateType();
3279 for(size_t i = 0; i < fields.size(); i++)
3281 const TType &fieldType = *(fields[i]->type());
3282 const TString &fieldName = fields[i]->name();
3283 const TString uniformName = name + "." + fieldName;
3285 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3286 fieldRegisterIndex += fieldType.totalRegisterCount();
3290 encoder->exitAggregateType();
3296 GLenum OutputASM::glVariableType(const TType &type)
3298 switch(type.getBasicType())
3305 else if(type.isVector())
3307 switch(type.getNominalSize())
3309 case 2: return GL_FLOAT_VEC2;
3310 case 3: return GL_FLOAT_VEC3;
3311 case 4: return GL_FLOAT_VEC4;
3312 default: UNREACHABLE(type.getNominalSize());
3315 else if(type.isMatrix())
3317 switch(type.getNominalSize())
3320 switch(type.getSecondarySize())
3322 case 2: return GL_FLOAT_MAT2;
3323 case 3: return GL_FLOAT_MAT2x3;
3324 case 4: return GL_FLOAT_MAT2x4;
3325 default: UNREACHABLE(type.getSecondarySize());
3328 switch(type.getSecondarySize())
3330 case 2: return GL_FLOAT_MAT3x2;
3331 case 3: return GL_FLOAT_MAT3;
3332 case 4: return GL_FLOAT_MAT3x4;
3333 default: UNREACHABLE(type.getSecondarySize());
3336 switch(type.getSecondarySize())
3338 case 2: return GL_FLOAT_MAT4x2;
3339 case 3: return GL_FLOAT_MAT4x3;
3340 case 4: return GL_FLOAT_MAT4;
3341 default: UNREACHABLE(type.getSecondarySize());
3343 default: UNREACHABLE(type.getNominalSize());
3346 else UNREACHABLE(0);
3353 else if(type.isVector())
3355 switch(type.getNominalSize())
3357 case 2: return GL_INT_VEC2;
3358 case 3: return GL_INT_VEC3;
3359 case 4: return GL_INT_VEC4;
3360 default: UNREACHABLE(type.getNominalSize());
3363 else UNREACHABLE(0);
3368 return GL_UNSIGNED_INT;
3370 else if(type.isVector())
3372 switch(type.getNominalSize())
3374 case 2: return GL_UNSIGNED_INT_VEC2;
3375 case 3: return GL_UNSIGNED_INT_VEC3;
3376 case 4: return GL_UNSIGNED_INT_VEC4;
3377 default: UNREACHABLE(type.getNominalSize());
3380 else UNREACHABLE(0);
3387 else if(type.isVector())
3389 switch(type.getNominalSize())
3391 case 2: return GL_BOOL_VEC2;
3392 case 3: return GL_BOOL_VEC3;
3393 case 4: return GL_BOOL_VEC4;
3394 default: UNREACHABLE(type.getNominalSize());
3397 else UNREACHABLE(0);
3400 return GL_SAMPLER_2D;
3402 return GL_INT_SAMPLER_2D;
3404 return GL_UNSIGNED_INT_SAMPLER_2D;
3405 case EbtSamplerCube:
3406 return GL_SAMPLER_CUBE;
3407 case EbtISamplerCube:
3408 return GL_INT_SAMPLER_CUBE;
3409 case EbtUSamplerCube:
3410 return GL_UNSIGNED_INT_SAMPLER_CUBE;
3411 case EbtSamplerExternalOES:
3412 return GL_SAMPLER_EXTERNAL_OES;
3414 return GL_SAMPLER_3D_OES;
3416 return GL_INT_SAMPLER_3D;
3418 return GL_UNSIGNED_INT_SAMPLER_3D;
3419 case EbtSampler2DArray:
3420 return GL_SAMPLER_2D_ARRAY;
3421 case EbtISampler2DArray:
3422 return GL_INT_SAMPLER_2D_ARRAY;
3423 case EbtUSampler2DArray:
3424 return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
3425 case EbtSampler2DShadow:
3426 return GL_SAMPLER_2D_SHADOW;
3427 case EbtSamplerCubeShadow:
3428 return GL_SAMPLER_CUBE_SHADOW;
3429 case EbtSampler2DArrayShadow:
3430 return GL_SAMPLER_2D_ARRAY_SHADOW;
3432 UNREACHABLE(type.getBasicType());
3439 GLenum OutputASM::glVariablePrecision(const TType &type)
3441 if(type.getBasicType() == EbtFloat)
3443 switch(type.getPrecision())
3445 case EbpHigh: return GL_HIGH_FLOAT;
3446 case EbpMedium: return GL_MEDIUM_FLOAT;
3447 case EbpLow: return GL_LOW_FLOAT;
3449 // Should be defined as the default precision by the parser
3450 default: UNREACHABLE(type.getPrecision());
3453 else if(type.getBasicType() == EbtInt)
3455 switch(type.getPrecision())
3457 case EbpHigh: return GL_HIGH_INT;
3458 case EbpMedium: return GL_MEDIUM_INT;
3459 case EbpLow: return GL_LOW_INT;
3461 // Should be defined as the default precision by the parser
3462 default: UNREACHABLE(type.getPrecision());
3466 // Other types (boolean, sampler) don't have a precision
3470 int OutputASM::dim(TIntermNode *v)
3472 TIntermTyped *vector = v->getAsTyped();
3473 ASSERT(vector && vector->isRegister());
3474 return vector->getNominalSize();
3477 int OutputASM::dim2(TIntermNode *m)
3479 TIntermTyped *matrix = m->getAsTyped();
3480 ASSERT(matrix && matrix->isMatrix() && !matrix->isArray());
3481 return matrix->getSecondarySize();
3484 // Returns ~0u if no loop count could be determined
3485 unsigned int OutputASM::loopCount(TIntermLoop *node)
3487 // Parse loops of the form:
3488 // for(int index = initial; index [comparator] limit; index += increment)
3489 TIntermSymbol *index = 0;
3490 TOperator comparator = EOpNull;
3495 // Parse index name and intial value
3498 TIntermAggregate *init = node->getInit()->getAsAggregate();
3502 TIntermSequence &sequence = init->getSequence();
3503 TIntermTyped *variable = sequence[0]->getAsTyped();
3505 if(variable && variable->getQualifier() == EvqTemporary)
3507 TIntermBinary *assign = variable->getAsBinaryNode();
3509 if(assign->getOp() == EOpInitialize)
3511 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3512 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3514 if(symbol && constant)
3516 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3519 initial = constant->getUnionArrayPointer()[0].getIConst();
3527 // Parse comparator and limit value
3528 if(index && node->getCondition())
3530 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
3531 TIntermSymbol *left = test ? test->getLeft()->getAsSymbolNode() : nullptr;
3533 if(left && (left->getId() == index->getId()))
3535 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3539 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3541 comparator = test->getOp();
3542 limit = constant->getUnionArrayPointer()[0].getIConst();
3549 if(index && comparator != EOpNull && node->getExpression())
3551 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3552 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3556 TOperator op = binaryTerminal->getOp();
3557 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3561 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3563 int value = constant->getUnionArrayPointer()[0].getIConst();
3567 case EOpAddAssign: increment = value; break;
3568 case EOpSubAssign: increment = -value; break;
3569 default: UNIMPLEMENTED();
3574 else if(unaryTerminal)
3576 TOperator op = unaryTerminal->getOp();
3580 case EOpPostIncrement: increment = 1; break;
3581 case EOpPostDecrement: increment = -1; break;
3582 case EOpPreIncrement: increment = 1; break;
3583 case EOpPreDecrement: increment = -1; break;
3584 default: UNIMPLEMENTED();
3589 if(index && comparator != EOpNull && increment != 0)
3591 if(comparator == EOpLessThanEqual)
3593 comparator = EOpLessThan;
3597 if(comparator == EOpLessThan)
3599 int iterations = (limit - initial) / increment;
3608 else UNIMPLEMENTED(); // Falls through
3614 bool LoopUnrollable::traverse(TIntermNode *node)
3617 loopUnrollable = true;
3619 node->traverse(this);
3621 return loopUnrollable;
3624 bool LoopUnrollable::visitLoop(Visit visit, TIntermLoop *loop)
3626 if(visit == PreVisit)
3630 else if(visit == PostVisit)
3638 bool LoopUnrollable::visitBranch(Visit visit, TIntermBranch *node)
3650 switch(node->getFlowOp())
3657 loopUnrollable = false;
3659 default: UNREACHABLE(node->getFlowOp());
3662 return loopUnrollable;
3665 bool LoopUnrollable::visitAggregate(Visit visit, TIntermAggregate *node)
3667 return loopUnrollable;