blob: 59949f162f7cc891b3e703f2373baff4a0f988ad [file] [log] [blame]
Nicolas Capens0bac2852016-05-07 06:09:58 -04001// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "OutputASM.h"
16#include "Common/Math.hpp"
17
18#include "common/debug.h"
19#include "InfoSink.h"
20
21#include "libGLESv2/Shader.h"
22
23#include <GLES2/gl2.h>
24#include <GLES2/gl2ext.h>
25#include <GLES3/gl3.h>
26
27namespace glsl
28{
29 // Integer to TString conversion
30 TString str(int i)
31 {
32 char buffer[20];
33 sprintf(buffer, "%d", i);
34 return buffer;
35 }
36
37 class Temporary : public TIntermSymbol
38 {
39 public:
40 Temporary(OutputASM *assembler) : TIntermSymbol(TSymbolTableLevel::nextUniqueId(), "tmp", TType(EbtFloat, EbpHigh, EvqTemporary, 4, 1, false)), assembler(assembler)
41 {
42 }
43
44 ~Temporary()
45 {
46 assembler->freeTemporary(this);
47 }
48
49 private:
50 OutputASM *const assembler;
51 };
52
53 class Constant : public TIntermConstantUnion
54 {
55 public:
56 Constant(float x, float y, float z, float w) : TIntermConstantUnion(constants, TType(EbtFloat, EbpHigh, EvqConstExpr, 4, 1, false))
57 {
58 constants[0].setFConst(x);
59 constants[1].setFConst(y);
60 constants[2].setFConst(z);
61 constants[3].setFConst(w);
62 }
63
64 Constant(bool b) : TIntermConstantUnion(constants, TType(EbtBool, EbpHigh, EvqConstExpr, 1, 1, false))
65 {
66 constants[0].setBConst(b);
67 }
68
69 Constant(int i) : TIntermConstantUnion(constants, TType(EbtInt, EbpHigh, EvqConstExpr, 1, 1, false))
70 {
71 constants[0].setIConst(i);
72 }
73
74 ~Constant()
75 {
76 }
77
78 private:
79 ConstantUnion constants[4];
80 };
81
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)
84 {
85 }
86
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)
91 {
92 }
93
94 BlockLayoutEncoder::BlockLayoutEncoder(bool rowMajor)
95 : mCurrentOffset(0), isRowMajor(rowMajor)
96 {
97 }
98
99 BlockMemberInfo BlockLayoutEncoder::encodeType(const TType &type)
100 {
101 int arrayStride;
102 int matrixStride;
103
104 getBlockLayoutInfo(type, type.getArraySize(), isRowMajor, &arrayStride, &matrixStride);
105
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);
110
111 advanceOffset(type, type.getArraySize(), isRowMajor, arrayStride, matrixStride);
112
113 return memberInfo;
114 }
115
116 // static
117 size_t BlockLayoutEncoder::getBlockRegister(const BlockMemberInfo &info)
118 {
119 return (info.offset / BytesPerComponent) / ComponentsPerRegister;
120 }
121
122 // static
123 size_t BlockLayoutEncoder::getBlockRegisterElement(const BlockMemberInfo &info)
124 {
125 return (info.offset / BytesPerComponent) % ComponentsPerRegister;
126 }
127
128 void BlockLayoutEncoder::nextRegister()
129 {
130 mCurrentOffset = sw::align(mCurrentOffset, ComponentsPerRegister);
131 }
132
133 Std140BlockEncoder::Std140BlockEncoder(bool rowMajor) : BlockLayoutEncoder(rowMajor)
134 {
135 }
136
137 void Std140BlockEncoder::enterAggregateType()
138 {
139 nextRegister();
140 }
141
142 void Std140BlockEncoder::exitAggregateType()
143 {
144 nextRegister();
145 }
146
147 void Std140BlockEncoder::getBlockLayoutInfo(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
148 {
149 size_t baseAlignment = 0;
150 int matrixStride = 0;
151 int arrayStride = 0;
152
153 if(type.isMatrix())
154 {
155 baseAlignment = ComponentsPerRegister;
156 matrixStride = ComponentsPerRegister;
157
158 if(arraySize > 0)
159 {
160 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
161 arrayStride = ComponentsPerRegister * numRegisters;
162 }
163 }
164 else if(arraySize > 0)
165 {
166 baseAlignment = ComponentsPerRegister;
167 arrayStride = ComponentsPerRegister;
168 }
169 else
170 {
171 const size_t numComponents = type.getElementSize();
172 baseAlignment = (numComponents == 3 ? 4u : numComponents);
173 }
174
175 mCurrentOffset = sw::align(mCurrentOffset, baseAlignment);
176
177 *matrixStrideOut = matrixStride;
178 *arrayStrideOut = arrayStride;
179 }
180
181 void Std140BlockEncoder::advanceOffset(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
182 {
183 if(arraySize > 0)
184 {
185 mCurrentOffset += arrayStride * arraySize;
186 }
187 else if(type.isMatrix())
188 {
189 ASSERT(matrixStride == ComponentsPerRegister);
190 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
191 mCurrentOffset += ComponentsPerRegister * numRegisters;
192 }
193 else
194 {
195 mCurrentOffset += type.getElementSize();
196 }
197 }
198
199 Attribute::Attribute()
200 {
201 type = GL_NONE;
202 arraySize = 0;
203 registerIndex = 0;
204 }
205
206 Attribute::Attribute(GLenum type, const std::string &name, int arraySize, int location, int registerIndex)
207 {
208 this->type = type;
209 this->name = name;
210 this->arraySize = arraySize;
211 this->location = location;
212 this->registerIndex = registerIndex;
213 }
214
215 sw::PixelShader *Shader::getPixelShader() const
216 {
217 return 0;
218 }
219
220 sw::VertexShader *Shader::getVertexShader() const
221 {
222 return 0;
223 }
224
225 OutputASM::TextureFunction::TextureFunction(const TString& nodeName) : method(IMPLICIT), proj(false), offset(false)
226 {
227 TString name = TFunction::unmangleName(nodeName);
228
229 if(name == "texture2D" || name == "textureCube" || name == "texture" || name == "texture3D")
230 {
231 method = IMPLICIT;
232 }
233 else if(name == "texture2DProj" || name == "textureProj")
234 {
235 method = IMPLICIT;
236 proj = true;
237 }
238 else if(name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod")
239 {
240 method = LOD;
241 }
242 else if(name == "texture2DProjLod" || name == "textureProjLod")
243 {
244 method = LOD;
245 proj = true;
246 }
247 else if(name == "textureSize")
248 {
249 method = SIZE;
250 }
251 else if(name == "textureOffset")
252 {
253 method = IMPLICIT;
254 offset = true;
255 }
256 else if(name == "textureProjOffset")
257 {
258 method = IMPLICIT;
259 offset = true;
260 proj = true;
261 }
262 else if(name == "textureLodOffset")
263 {
264 method = LOD;
265 offset = true;
266 }
267 else if(name == "textureProjLodOffset")
268 {
269 method = LOD;
270 proj = true;
271 offset = true;
272 }
273 else if(name == "texelFetch")
274 {
275 method = FETCH;
276 }
277 else if(name == "texelFetchOffset")
278 {
279 method = FETCH;
280 offset = true;
281 }
282 else if(name == "textureGrad")
283 {
284 method = GRAD;
285 }
286 else if(name == "textureGradOffset")
287 {
288 method = GRAD;
289 offset = true;
290 }
291 else if(name == "textureProjGrad")
292 {
293 method = GRAD;
294 proj = true;
295 }
296 else if(name == "textureProjGradOffset")
297 {
298 method = GRAD;
299 proj = true;
300 offset = true;
301 }
302 else UNREACHABLE(0);
303 }
304
305 OutputASM::OutputASM(TParseContext &context, Shader *shaderObject) : TIntermTraverser(true, true, true), shaderObject(shaderObject), mContext(context)
306 {
307 shader = 0;
308 pixelShader = 0;
309 vertexShader = 0;
310
311 if(shaderObject)
312 {
313 shader = shaderObject->getShader();
314 pixelShader = shaderObject->getPixelShader();
315 vertexShader = shaderObject->getVertexShader();
316 }
317
318 functionArray.push_back(Function(0, "main(", 0, 0));
319 currentFunction = 0;
320 outputQualifier = EvqOutput; // Set outputQualifier to any value other than EvqFragColor or EvqFragData
321 }
322
323 OutputASM::~OutputASM()
324 {
325 }
326
327 void OutputASM::output()
328 {
329 if(shader)
330 {
331 emitShader(GLOBAL);
332
333 if(functionArray.size() > 1) // Only call main() when there are other functions
334 {
335 Instruction *callMain = emit(sw::Shader::OPCODE_CALL);
336 callMain->dst.type = sw::Shader::PARAMETER_LABEL;
337 callMain->dst.index = 0; // main()
338
339 emit(sw::Shader::OPCODE_RET);
340 }
341
342 emitShader(FUNCTION);
343 }
344 }
345
346 void OutputASM::emitShader(Scope scope)
347 {
348 emitScope = scope;
349 currentScope = GLOBAL;
350 mContext.getTreeRoot()->traverse(this);
351 }
352
353 void OutputASM::freeTemporary(Temporary *temporary)
354 {
355 free(temporaries, temporary);
356 }
357
358 sw::Shader::Opcode OutputASM::getOpcode(sw::Shader::Opcode op, TIntermTyped *in) const
359 {
360 TBasicType baseType = in->getType().getBasicType();
361
362 switch(op)
363 {
364 case sw::Shader::OPCODE_NEG:
365 switch(baseType)
366 {
367 case EbtInt:
368 case EbtUInt:
369 return sw::Shader::OPCODE_INEG;
370 case EbtFloat:
371 default:
372 return op;
373 }
374 case sw::Shader::OPCODE_ABS:
375 switch(baseType)
376 {
377 case EbtInt:
378 return sw::Shader::OPCODE_IABS;
379 case EbtFloat:
380 default:
381 return op;
382 }
383 case sw::Shader::OPCODE_SGN:
384 switch(baseType)
385 {
386 case EbtInt:
387 return sw::Shader::OPCODE_ISGN;
388 case EbtFloat:
389 default:
390 return op;
391 }
392 case sw::Shader::OPCODE_ADD:
393 switch(baseType)
394 {
395 case EbtInt:
396 case EbtUInt:
397 return sw::Shader::OPCODE_IADD;
398 case EbtFloat:
399 default:
400 return op;
401 }
402 case sw::Shader::OPCODE_SUB:
403 switch(baseType)
404 {
405 case EbtInt:
406 case EbtUInt:
407 return sw::Shader::OPCODE_ISUB;
408 case EbtFloat:
409 default:
410 return op;
411 }
412 case sw::Shader::OPCODE_MUL:
413 switch(baseType)
414 {
415 case EbtInt:
416 case EbtUInt:
417 return sw::Shader::OPCODE_IMUL;
418 case EbtFloat:
419 default:
420 return op;
421 }
422 case sw::Shader::OPCODE_DIV:
423 switch(baseType)
424 {
425 case EbtInt:
426 return sw::Shader::OPCODE_IDIV;
427 case EbtUInt:
428 return sw::Shader::OPCODE_UDIV;
429 case EbtFloat:
430 default:
431 return op;
432 }
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:
438 switch(baseType)
439 {
440 case EbtInt:
441 return sw::Shader::OPCODE_IMIN;
442 case EbtUInt:
443 return sw::Shader::OPCODE_UMIN;
444 case EbtFloat:
445 default:
446 return op;
447 }
448 case sw::Shader::OPCODE_MAX:
449 switch(baseType)
450 {
451 case EbtInt:
452 return sw::Shader::OPCODE_IMAX;
453 case EbtUInt:
454 return sw::Shader::OPCODE_UMAX;
455 case EbtFloat:
456 default:
457 return op;
458 }
459 default:
460 return op;
461 }
462 }
463
464 void OutputASM::visitSymbol(TIntermSymbol *symbol)
465 {
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)
469 {
470 if(symbol->getBasicType() != EbtInvariant) // Typeless declarations are not new varyings
471 {
472 declareVarying(symbol, -1);
473 }
474 }
475
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)))
482 {
483 uniformRegister(symbol);
484 }
485 }
486
487 bool OutputASM::visitBinary(Visit visit, TIntermBinary *node)
488 {
489 if(currentScope != emitScope)
490 {
491 return false;
492 }
493
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();
500
501 if(isSamplerRegister(result))
502 {
503 return false; // Don't traverse, the register index is determined statically
504 }
505
506 switch(node->getOp())
507 {
508 case EOpAssign:
509 if(visit == PostVisit)
510 {
511 assignLvalue(left, right);
512 copy(result, right);
513 }
514 break;
515 case EOpInitialize:
516 if(visit == PostVisit)
517 {
518 copy(left, right);
519 }
520 break;
521 case EOpMatrixTimesScalarAssign:
522 if(visit == PostVisit)
523 {
524 for(int i = 0; i < leftType.getNominalSize(); i++)
525 {
526 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right);
527 }
528
529 assignLvalue(left, result);
530 }
531 break;
532 case EOpVectorTimesMatrixAssign:
533 if(visit == PostVisit)
534 {
535 int size = leftType.getNominalSize();
536
537 for(int i = 0; i < size; i++)
538 {
539 Instruction *dot = emit(sw::Shader::OPCODE_DP(size), result, 0, left, 0, right, i);
540 dot->dst.mask = 1 << i;
541 }
542
543 assignLvalue(left, result);
544 }
545 break;
546 case EOpMatrixTimesMatrixAssign:
547 if(visit == PostVisit)
548 {
549 int dim = leftType.getNominalSize();
550
551 for(int i = 0; i < dim; i++)
552 {
553 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
554 mul->src[1].swizzle = 0x00;
555
556 for(int j = 1; j < dim; j++)
557 {
558 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
559 mad->src[1].swizzle = j * 0x55;
560 }
561 }
562
563 assignLvalue(left, result);
564 }
565 break;
566 case EOpIndexDirect:
567 if(visit == PostVisit)
568 {
569 int index = right->getAsConstantUnion()->getIConst(0);
570
571 if(result->isMatrix() || result->isStruct() || result->isInterfaceBlock())
572 {
573 ASSERT(left->isArray());
574 copy(result, left, index * left->elementRegisterCount());
575 }
576 else if(result->isRegister())
577 {
578 int srcIndex = 0;
579 if(left->isRegister())
580 {
581 srcIndex = 0;
582 }
583 else if(left->isArray())
584 {
585 srcIndex = index * left->elementRegisterCount();
586 }
587 else if(left->isMatrix())
588 {
589 ASSERT(index < left->getNominalSize()); // FIXME: Report semantic error
590 srcIndex = index;
591 }
592 else UNREACHABLE(0);
593
594 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, 0, left, srcIndex);
595
596 if(left->isRegister())
597 {
598 mov->src[0].swizzle = index;
599 }
600 }
601 else UNREACHABLE(0);
602 }
603 break;
604 case EOpIndexIndirect:
605 if(visit == PostVisit)
606 {
607 if(left->isArray() || left->isMatrix())
608 {
609 for(int index = 0; index < result->totalRegisterCount(); index++)
610 {
611 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index, left, index);
612 mov->dst.mask = writeMask(result, index);
613
614 if(left->totalRegisterCount() > 1)
615 {
616 sw::Shader::SourceParameter relativeRegister;
617 argument(relativeRegister, right);
618
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);
623 }
624 }
625 }
626 else if(left->isRegister())
627 {
628 emit(sw::Shader::OPCODE_EXTRACT, result, left, right);
629 }
630 else UNREACHABLE(0);
631 }
632 break;
633 case EOpIndexDirectStruct:
634 case EOpIndexDirectInterfaceBlock:
635 if(visit == PostVisit)
636 {
637 ASSERT(leftType.isStruct() || (leftType.isInterfaceBlock()));
638
639 const TFieldList& fields = (node->getOp() == EOpIndexDirectStruct) ?
640 leftType.getStruct()->fields() :
641 leftType.getInterfaceBlock()->fields();
642 int index = right->getAsConstantUnion()->getIConst(0);
643 int fieldOffset = 0;
644
645 for(int i = 0; i < index; i++)
646 {
647 fieldOffset += fields[i]->type()->totalRegisterCount();
648 }
649
650 copy(result, left, fieldOffset);
651 }
652 break;
653 case EOpVectorSwizzle:
654 if(visit == PostVisit)
655 {
656 int swizzle = 0;
657 TIntermAggregate *components = right->getAsAggregate();
658
659 if(components)
660 {
661 TIntermSequence &sequence = components->getSequence();
662 int component = 0;
663
664 for(TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
665 {
666 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
667
668 if(element)
669 {
670 int i = element->getUnionArrayPointer()[0].getIConst();
671 swizzle |= i << (component * 2);
672 component++;
673 }
674 else UNREACHABLE(0);
675 }
676 }
677 else UNREACHABLE(0);
678
679 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, left);
680 mov->src[0].swizzle = swizzle;
681 }
682 break;
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;
703 case EOpEqual:
704 if(visit == PostVisit)
705 {
706 emitBinary(sw::Shader::OPCODE_EQ, result, left, right);
707
708 for(int index = 1; index < left->totalRegisterCount(); index++)
709 {
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);
713 }
714 }
715 break;
716 case EOpNotEqual:
717 if(visit == PostVisit)
718 {
719 emitBinary(sw::Shader::OPCODE_NE, result, left, right);
720
721 for(int index = 1; index < left->totalRegisterCount(); index++)
722 {
723 Temporary notEqual(this);
724 emit(sw::Shader::OPCODE_NE, &notEqual, 0, left, index, right, index);
725 emit(sw::Shader::OPCODE_OR, result, result, &notEqual);
726 }
727 }
728 break;
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)
737 {
738 if(left->isMatrix())
739 {
740 for(int i = 0; i < leftType.getNominalSize(); i++)
741 {
742 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right, 0);
743 }
744 }
745 else if(right->isMatrix())
746 {
747 for(int i = 0; i < rightType.getNominalSize(); i++)
748 {
749 emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
750 }
751 }
752 else UNREACHABLE(0);
753 }
754 break;
755 case EOpVectorTimesMatrix:
756 if(visit == PostVisit)
757 {
758 sw::Shader::Opcode dpOpcode = sw::Shader::OPCODE_DP(leftType.getNominalSize());
759
760 int size = rightType.getNominalSize();
761 for(int i = 0; i < size; i++)
762 {
763 Instruction *dot = emit(dpOpcode, result, 0, left, 0, right, i);
764 dot->dst.mask = 1 << i;
765 }
766 }
767 break;
768 case EOpMatrixTimesVector:
769 if(visit == PostVisit)
770 {
771 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, left, right);
772 mul->src[1].swizzle = 0x00;
773
774 int size = rightType.getNominalSize();
775 for(int i = 1; i < size; i++)
776 {
777 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, 0, left, i, right, 0, result);
778 mad->src[1].swizzle = i * 0x55;
779 }
780 }
781 break;
782 case EOpMatrixTimesMatrix:
783 if(visit == PostVisit)
784 {
785 int dim = leftType.getNominalSize();
786
787 int size = rightType.getNominalSize();
788 for(int i = 0; i < size; i++)
789 {
790 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
791 mul->src[1].swizzle = 0x00;
792
793 for(int j = 1; j < dim; j++)
794 {
795 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
796 mad->src[1].swizzle = j * 0x55;
797 }
798 }
799 }
800 break;
801 case EOpLogicalOr:
802 if(trivial(right, 6))
803 {
804 if(visit == PostVisit)
805 {
806 emit(sw::Shader::OPCODE_OR, result, left, right);
807 }
808 }
809 else // Short-circuit evaluation
810 {
811 if(visit == InVisit)
812 {
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;
816 }
817 else if(visit == PostVisit)
818 {
819 emit(sw::Shader::OPCODE_MOV, result, right);
820 emit(sw::Shader::OPCODE_ENDIF);
821 }
822 }
823 break;
824 case EOpLogicalXor: if(visit == PostVisit) emit(sw::Shader::OPCODE_XOR, result, left, right); break;
825 case EOpLogicalAnd:
826 if(trivial(right, 6))
827 {
828 if(visit == PostVisit)
829 {
830 emit(sw::Shader::OPCODE_AND, result, left, right);
831 }
832 }
833 else // Short-circuit evaluation
834 {
835 if(visit == InVisit)
836 {
837 emit(sw::Shader::OPCODE_MOV, result, left);
838 emit(sw::Shader::OPCODE_IF, 0, result);
839 }
840 else if(visit == PostVisit)
841 {
842 emit(sw::Shader::OPCODE_MOV, result, right);
843 emit(sw::Shader::OPCODE_ENDIF);
844 }
845 }
846 break;
847 default: UNREACHABLE(node->getOp());
848 }
849
850 return true;
851 }
852
853 void OutputASM::emitDeterminant(TIntermTyped *result, TIntermTyped *arg, int size, int col, int row, int outCol, int outRow)
854 {
855 switch(size)
856 {
857 case 1: // Used for cofactor computation only
858 {
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;
865 }
866 break;
867 case 2:
868 {
869 static const unsigned int swizzle[3] = { 0x99, 0x88, 0x44 }; // xy?? : yzyz, xzxz, xyxy
870
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));
875
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;
879 }
880 break;
881 case 3:
882 {
883 static const unsigned int swizzle[4] = { 0xF9, 0xF8, 0xF4, 0xE4 }; // xyz? : yzww, xzww, xyww, xyzw
884
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));
890
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;
894 }
895 break;
896 case 4:
897 {
898 Instruction *det = emit(sw::Shader::OPCODE_DET4, result, outCol, arg, 0, arg, 1, arg, 2, arg, 3);
899 det->dst.mask = 1 << outRow;
900 }
901 break;
902 default:
903 UNREACHABLE(size);
904 break;
905 }
906 }
907
908 bool OutputASM::visitUnary(Visit visit, TIntermUnary *node)
909 {
910 if(currentScope != emitScope)
911 {
912 return false;
913 }
914
915 TIntermTyped *result = node;
916 TIntermTyped *arg = node->getOperand();
917 TBasicType basicType = arg->getType().getBasicType();
918
919 union
920 {
921 float f;
922 int i;
923 } one_value;
924
925 if(basicType == EbtInt || basicType == EbtUInt)
926 {
927 one_value.i = 1;
928 }
929 else
930 {
931 one_value.f = 1.0f;
932 }
933
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);
937
938 switch(node->getOp())
939 {
940 case EOpNegative:
941 if(visit == PostVisit)
942 {
943 sw::Shader::Opcode negOpcode = getOpcode(sw::Shader::OPCODE_NEG, arg);
944 for(int index = 0; index < arg->totalRegisterCount(); index++)
945 {
946 emit(negOpcode, result, index, arg, index);
947 }
948 }
949 break;
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)
954 {
955 copy(result, arg);
956
957 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
958 for(int index = 0; index < arg->totalRegisterCount(); index++)
959 {
960 emit(addOpcode, arg, index, arg, index, &one);
961 }
962
963 assignLvalue(arg, arg);
964 }
965 break;
966 case EOpPostDecrement:
967 if(visit == PostVisit)
968 {
969 copy(result, arg);
970
971 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
972 for(int index = 0; index < arg->totalRegisterCount(); index++)
973 {
974 emit(subOpcode, arg, index, arg, index, &one);
975 }
976
977 assignLvalue(arg, arg);
978 }
979 break;
980 case EOpPreIncrement:
981 if(visit == PostVisit)
982 {
983 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
984 for(int index = 0; index < arg->totalRegisterCount(); index++)
985 {
986 emit(addOpcode, result, index, arg, index, &one);
987 }
988
989 assignLvalue(arg, result);
990 }
991 break;
992 case EOpPreDecrement:
993 if(visit == PostVisit)
994 {
995 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
996 for(int index = 0; index < arg->totalRegisterCount(); index++)
997 {
998 emit(subOpcode, result, index, arg, index, &one);
999 }
1000
1001 assignLvalue(arg, result);
1002 }
1003 break;
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, &deg); 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;
1051 case EOpTranspose:
1052 if(visit == PostVisit)
1053 {
1054 int numCols = arg->getNominalSize();
1055 int numRows = arg->getSecondarySize();
1056 for(int i = 0; i < numCols; ++i)
1057 {
1058 for(int j = 0; j < numRows; ++j)
1059 {
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;
1063 }
1064 }
1065 }
1066 break;
1067 case EOpDeterminant:
1068 if(visit == PostVisit)
1069 {
1070 int size = arg->getNominalSize();
1071 ASSERT(size == arg->getSecondarySize());
1072
1073 emitDeterminant(result, arg, size);
1074 }
1075 break;
1076 case EOpInverse:
1077 if(visit == PostVisit)
1078 {
1079 int size = arg->getNominalSize();
1080 ASSERT(size == arg->getSecondarySize());
1081
1082 // Compute transposed matrix of cofactors
1083 for(int i = 0; i < size; ++i)
1084 {
1085 for(int j = 0; j < size; ++j)
1086 {
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);
1090 }
1091 }
1092
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
1099
1100 // Divide transposed matrix of cofactors by determinant
1101 for(int i = 0; i < size; ++i)
1102 {
1103 emit(sw::Shader::OPCODE_MUL, result, i, result, i, &invDet);
1104 }
1105 }
1106 break;
1107 default: UNREACHABLE(node->getOp());
1108 }
1109
1110 return true;
1111 }
1112
1113 bool OutputASM::visitAggregate(Visit visit, TIntermAggregate *node)
1114 {
1115 if(currentScope != emitScope && node->getOp() != EOpFunction && node->getOp() != EOpSequence)
1116 {
1117 return false;
1118 }
1119
1120 Constant zero(0.0f, 0.0f, 0.0f, 0.0f);
1121
1122 TIntermTyped *result = node;
1123 const TType &resultType = node->getType();
1124 TIntermSequence &arg = node->getSequence();
1125 size_t argumentCount = arg.size();
1126
1127 switch(node->getOp())
1128 {
1129 case EOpSequence: break;
1130 case EOpDeclaration: break;
1131 case EOpInvariantDeclaration: break;
1132 case EOpPrototype: break;
1133 case EOpComma:
1134 if(visit == PostVisit)
1135 {
1136 copy(result, arg[1]);
1137 }
1138 break;
1139 case EOpFunction:
1140 if(visit == PreVisit)
1141 {
1142 const TString &name = node->getName();
1143
1144 if(emitScope == FUNCTION)
1145 {
1146 if(functionArray.size() > 1) // No need for a label when there's only main()
1147 {
1148 Instruction *label = emit(sw::Shader::OPCODE_LABEL);
1149 label->dst.type = sw::Shader::PARAMETER_LABEL;
1150
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;
1155 }
1156 }
1157 else if(emitScope == GLOBAL)
1158 {
1159 if(name != "main(")
1160 {
1161 TIntermSequence &arguments = node->getSequence()[0]->getAsAggregate()->getSequence();
1162 functionArray.push_back(Function(functionArray.size(), name, &arguments, node));
1163 }
1164 }
1165 else UNREACHABLE(emitScope);
1166
1167 currentScope = FUNCTION;
1168 }
1169 else if(visit == PostVisit)
1170 {
1171 if(emitScope == FUNCTION)
1172 {
1173 if(functionArray.size() > 1) // No need to return when there's only main()
1174 {
1175 emit(sw::Shader::OPCODE_RET);
1176 }
1177 }
1178
1179 currentScope = GLOBAL;
1180 }
1181 break;
1182 case EOpFunctionCall:
1183 if(visit == PostVisit)
1184 {
1185 if(node->isUserDefined())
1186 {
1187 const TString &name = node->getName();
1188 const Function *function = findFunction(name);
1189
1190 if(!function)
1191 {
1192 mContext.error(node->getLine(), "function definition not found", name.c_str());
1193 return false;
1194 }
1195
1196 TIntermSequence &arguments = *function->arg;
1197
1198 for(size_t i = 0; i < argumentCount; i++)
1199 {
1200 TIntermTyped *in = arguments[i]->getAsTyped();
1201
1202 if(in->getQualifier() == EvqIn ||
1203 in->getQualifier() == EvqInOut ||
1204 in->getQualifier() == EvqConstReadOnly)
1205 {
1206 copy(in, arg[i]);
1207 }
1208 }
1209
1210 Instruction *call = emit(sw::Shader::OPCODE_CALL);
1211 call->dst.type = sw::Shader::PARAMETER_LABEL;
1212 call->dst.index = function->label;
1213
1214 if(function->ret && function->ret->getType().getBasicType() != EbtVoid)
1215 {
1216 copy(result, function->ret);
1217 }
1218
1219 for(size_t i = 0; i < argumentCount; i++)
1220 {
1221 TIntermTyped *argument = arguments[i]->getAsTyped();
1222 TIntermTyped *out = arg[i]->getAsTyped();
1223
1224 if(argument->getQualifier() == EvqOut ||
1225 argument->getQualifier() == EvqInOut)
1226 {
1227 copy(out, argument);
1228 }
1229 }
1230 }
1231 else
1232 {
1233 const TextureFunction textureFunction(node->getName());
1234 TIntermTyped *t = arg[1]->getAsTyped();
1235
1236 Temporary coord(this);
1237
1238 if(textureFunction.proj)
1239 {
1240 TIntermConstantUnion* constant = arg[1]->getAsConstantUnion();
1241 if(constant)
1242 {
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,
1247 0.0f);
1248 emit(sw::Shader::OPCODE_MOV, &coord, &projCoord);
1249 }
1250 else
1251 {
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;
1255
1256 Instruction *mul = emit(sw::Shader::OPCODE_MUL, &coord, arg[1], &coord);
1257 mul->dst.mask = 0x7;
1258 }
1259 }
1260 else
1261 {
1262 emit(sw::Shader::OPCODE_MOV, &coord, arg[1]);
1263 }
1264
1265 switch(textureFunction.method)
1266 {
1267 case TextureFunction::IMPLICIT:
1268 {
1269 TIntermNode* offset = textureFunction.offset ? arg[2] : 0;
1270
1271 if(argumentCount == 2 || (textureFunction.offset && argumentCount == 3))
1272 {
1273 Instruction *tex = emit(textureFunction.offset ? sw::Shader::OPCODE_TEXOFFSET : sw::Shader::OPCODE_TEX,
1274 result, &coord, arg[0], offset);
1275 }
1276 else if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4)) // bias
1277 {
1278 Instruction *bias = emit(sw::Shader::OPCODE_MOV, &coord, arg[textureFunction.offset ? 3 : 2]);
1279 bias->dst.mask = 0x8;
1280
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
1283 tex->bias = true;
1284 }
1285 else UNREACHABLE(argumentCount);
1286 }
1287 break;
1288 case TextureFunction::LOD:
1289 {
1290 Instruction *lod = emit(sw::Shader::OPCODE_MOV, &coord, arg[2]);
1291 lod->dst.mask = 0x8;
1292
1293 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXLDLOFFSET : sw::Shader::OPCODE_TEXLDL,
1294 result, &coord, arg[0], textureFunction.offset ? arg[3] : nullptr);
1295 }
1296 break;
1297 case TextureFunction::FETCH:
1298 {
1299 if(argumentCount == 3 || (textureFunction.offset && argumentCount == 4))
1300 {
1301 TIntermNode *offset = textureFunction.offset ? arg[3] : nullptr;
1302
1303 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXELFETCHOFFSET : sw::Shader::OPCODE_TEXELFETCH,
1304 result, arg[1], arg[0], arg[2], offset);
1305 }
1306 else UNREACHABLE(argumentCount);
1307 }
1308 break;
1309 case TextureFunction::GRAD:
1310 {
1311 if(argumentCount == 4 || (textureFunction.offset && argumentCount == 5))
1312 {
1313 TIntermNode *offset = textureFunction.offset ? arg[4] : nullptr;
1314
1315 emit(textureFunction.offset ? sw::Shader::OPCODE_TEXGRADOFFSET : sw::Shader::OPCODE_TEXGRAD,
1316 result, &coord, arg[0], arg[2], arg[3], offset);
1317 }
1318 else UNREACHABLE(argumentCount);
1319 }
1320 break;
1321 case TextureFunction::SIZE:
1322 emit(sw::Shader::OPCODE_TEXSIZE, result, arg[1], arg[0]);
1323 break;
1324 default:
1325 UNREACHABLE(textureFunction.method);
1326 }
1327 }
1328 }
1329 break;
1330 case EOpParameters:
1331 break;
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)
1349 {
1350 int component = 0;
1351
1352 for(size_t i = 0; i < argumentCount; i++)
1353 {
1354 TIntermTyped *argi = arg[i]->getAsTyped();
1355 int size = argi->getNominalSize();
1356
1357 if(!argi->isMatrix())
1358 {
1359 Instruction *mov = emitCast(result, argi);
1360 mov->dst.mask = (0xF << component) & 0xF;
1361 mov->src[0].swizzle = readSwizzle(argi, size) << (component * 2);
1362
1363 component += size;
1364 }
1365 else // Matrix
1366 {
1367 int column = 0;
1368
1369 while(component < resultType.getNominalSize())
1370 {
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);
1374
1375 column++;
1376 component += size;
1377 }
1378 }
1379 }
1380 }
1381 break;
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)
1392 {
1393 TIntermTyped *arg0 = arg[0]->getAsTyped();
1394 const int outCols = result->getNominalSize();
1395 const int outRows = result->getSecondarySize();
1396
1397 if(arg0->isScalar() && arg.size() == 1) // Construct scale matrix
1398 {
1399 for(int i = 0; i < outCols; i++)
1400 {
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);
1405 }
1406 }
1407 else if(arg0->isMatrix())
1408 {
1409 const int inCols = arg0->getNominalSize();
1410 const int inRows = arg0->getSecondarySize();
1411
1412 for(int i = 0; i < outCols; i++)
1413 {
1414 if(i >= inCols || outRows > inRows)
1415 {
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);
1419 }
1420
1421 if(i < inCols)
1422 {
1423 Instruction *mov = emitCast(result, i, arg0, i);
1424 mov->dst.mask = 0xF >> (4 - inRows);
1425 }
1426 }
1427 }
1428 else
1429 {
1430 int column = 0;
1431 int row = 0;
1432
1433 for(size_t i = 0; i < argumentCount; i++)
1434 {
1435 TIntermTyped *argi = arg[i]->getAsTyped();
1436 int size = argi->getNominalSize();
1437 int element = 0;
1438
1439 while(element < size)
1440 {
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;
1444
1445 int end = row + size - element;
1446 column = end >= outRows ? column + 1 : column;
1447 element = element + outRows - row;
1448 row = end >= outRows ? 0 : end;
1449 }
1450 }
1451 }
1452 }
1453 break;
1454 case EOpConstructStruct:
1455 if(visit == PostVisit)
1456 {
1457 int offset = 0;
1458 for(size_t i = 0; i < argumentCount; i++)
1459 {
1460 TIntermTyped *argi = arg[i]->getAsTyped();
1461 int size = argi->totalRegisterCount();
1462
1463 for(int index = 0; index < size; index++)
1464 {
1465 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index + offset, argi, index);
1466 mov->dst.mask = writeMask(result, offset + index);
1467 }
1468
1469 offset += size;
1470 }
1471 }
1472 break;
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;
1480 case EOpModf:
1481 if(visit == PostVisit)
1482 {
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);
1487 }
1488 break;
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;
1493 case EOpClamp:
1494 if(visit == PostVisit)
1495 {
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]);
1498 }
1499 break;
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;
1509 case EOpMul:
1510 if(visit == PostVisit)
1511 {
1512 TIntermTyped *arg0 = arg[0]->getAsTyped();
1513 TIntermTyped *arg1 = arg[1]->getAsTyped();
1514 ASSERT((arg0->getNominalSize() == arg1->getNominalSize()) && (arg0->getSecondarySize() == arg1->getSecondarySize()));
1515
1516 int size = arg0->getNominalSize();
1517 for(int i = 0; i < size; i++)
1518 {
1519 emit(sw::Shader::OPCODE_MUL, result, i, arg[0], i, arg[1], i);
1520 }
1521 }
1522 break;
1523 case EOpOuterProduct:
1524 if(visit == PostVisit)
1525 {
1526 for(int i = 0; i < dim(arg[1]); i++)
1527 {
1528 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, arg[0], 0, arg[1]);
1529 mul->src[1].swizzle = 0x55 * i;
1530 }
1531 }
1532 break;
1533 default: UNREACHABLE(node->getOp());
1534 }
1535
1536 return true;
1537 }
1538
1539 bool OutputASM::visitSelection(Visit visit, TIntermSelection *node)
1540 {
1541 if(currentScope != emitScope)
1542 {
1543 return false;
1544 }
1545
1546 TIntermTyped *condition = node->getCondition();
1547 TIntermNode *trueBlock = node->getTrueBlock();
1548 TIntermNode *falseBlock = node->getFalseBlock();
1549 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
1550
1551 condition->traverse(this);
1552
1553 if(node->usesTernaryOperator())
1554 {
1555 if(constantCondition)
1556 {
1557 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1558
1559 if(trueCondition)
1560 {
1561 trueBlock->traverse(this);
1562 copy(node, trueBlock);
1563 }
1564 else
1565 {
1566 falseBlock->traverse(this);
1567 copy(node, falseBlock);
1568 }
1569 }
1570 else if(trivial(node, 6)) // Fast to compute both potential results and no side effects
1571 {
1572 trueBlock->traverse(this);
1573 falseBlock->traverse(this);
1574 emit(sw::Shader::OPCODE_SELECT, node, condition, trueBlock, falseBlock);
1575 }
1576 else
1577 {
1578 emit(sw::Shader::OPCODE_IF, 0, condition);
1579
1580 if(trueBlock)
1581 {
1582 trueBlock->traverse(this);
1583 copy(node, trueBlock);
1584 }
1585
1586 if(falseBlock)
1587 {
1588 emit(sw::Shader::OPCODE_ELSE);
1589 falseBlock->traverse(this);
1590 copy(node, falseBlock);
1591 }
1592
1593 emit(sw::Shader::OPCODE_ENDIF);
1594 }
1595 }
1596 else // if/else statement
1597 {
1598 if(constantCondition)
1599 {
1600 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1601
1602 if(trueCondition)
1603 {
1604 if(trueBlock)
1605 {
1606 trueBlock->traverse(this);
1607 }
1608 }
1609 else
1610 {
1611 if(falseBlock)
1612 {
1613 falseBlock->traverse(this);
1614 }
1615 }
1616 }
1617 else
1618 {
1619 emit(sw::Shader::OPCODE_IF, 0, condition);
1620
1621 if(trueBlock)
1622 {
1623 trueBlock->traverse(this);
1624 }
1625
1626 if(falseBlock)
1627 {
1628 emit(sw::Shader::OPCODE_ELSE);
1629 falseBlock->traverse(this);
1630 }
1631
1632 emit(sw::Shader::OPCODE_ENDIF);
1633 }
1634 }
1635
1636 return false;
1637 }
1638
1639 bool OutputASM::visitLoop(Visit visit, TIntermLoop *node)
1640 {
1641 if(currentScope != emitScope)
1642 {
1643 return false;
1644 }
1645
1646 unsigned int iterations = loopCount(node);
1647
1648 if(iterations == 0)
1649 {
1650 return false;
1651 }
1652
1653 bool unroll = (iterations <= 4);
1654
1655 if(unroll)
1656 {
1657 LoopUnrollable loopUnrollable;
1658 unroll = loopUnrollable.traverse(node);
1659 }
1660
1661 TIntermNode *init = node->getInit();
1662 TIntermTyped *condition = node->getCondition();
1663 TIntermTyped *expression = node->getExpression();
1664 TIntermNode *body = node->getBody();
1665 Constant True(true);
1666
1667 if(node->getType() == ELoopDoWhile)
1668 {
1669 Temporary iterate(this);
1670 emit(sw::Shader::OPCODE_MOV, &iterate, &True);
1671
1672 emit(sw::Shader::OPCODE_WHILE, 0, &iterate); // FIXME: Implement real do-while
1673
1674 if(body)
1675 {
1676 body->traverse(this);
1677 }
1678
1679 emit(sw::Shader::OPCODE_TEST);
1680
1681 condition->traverse(this);
1682 emit(sw::Shader::OPCODE_MOV, &iterate, condition);
1683
1684 emit(sw::Shader::OPCODE_ENDWHILE);
1685 }
1686 else
1687 {
1688 if(init)
1689 {
1690 init->traverse(this);
1691 }
1692
1693 if(unroll)
1694 {
1695 for(unsigned int i = 0; i < iterations; i++)
1696 {
1697 // condition->traverse(this); // Condition could contain statements, but not in an unrollable loop
1698
1699 if(body)
1700 {
1701 body->traverse(this);
1702 }
1703
1704 if(expression)
1705 {
1706 expression->traverse(this);
1707 }
1708 }
1709 }
1710 else
1711 {
1712 if(condition)
1713 {
1714 condition->traverse(this);
1715 }
1716 else
1717 {
1718 condition = &True;
1719 }
1720
1721 emit(sw::Shader::OPCODE_WHILE, 0, condition);
1722
1723 if(body)
1724 {
1725 body->traverse(this);
1726 }
1727
1728 emit(sw::Shader::OPCODE_TEST);
1729
1730 if(expression)
1731 {
1732 expression->traverse(this);
1733 }
1734
1735 if(condition)
1736 {
1737 condition->traverse(this);
1738 }
1739
1740 emit(sw::Shader::OPCODE_ENDWHILE);
1741 }
1742 }
1743
1744 return false;
1745 }
1746
1747 bool OutputASM::visitBranch(Visit visit, TIntermBranch *node)
1748 {
1749 if(currentScope != emitScope)
1750 {
1751 return false;
1752 }
1753
1754 switch(node->getFlowOp())
1755 {
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;
1759 case EOpReturn:
1760 if(visit == PostVisit)
1761 {
1762 TIntermTyped *value = node->getExpression();
1763
1764 if(value)
1765 {
1766 copy(functionArray[currentFunction].ret, value);
1767 }
1768
1769 emit(sw::Shader::OPCODE_LEAVE);
1770 }
1771 break;
1772 default: UNREACHABLE(node->getFlowOp());
1773 }
1774
1775 return true;
1776 }
1777
1778 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2, TIntermNode *src3, TIntermNode *src4)
1779 {
1780 return emit(op, dst, 0, src0, 0, src1, 0, src2, 0, src3, 0, src4, 0);
1781 }
1782
1783 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, int dstIndex, TIntermNode *src0, int index0, TIntermNode *src1, int index1,
1784 TIntermNode *src2, int index2, TIntermNode *src3, int index3, TIntermNode *src4, int index4)
1785 {
1786 Instruction *instruction = new Instruction(op);
1787
1788 if(dst)
1789 {
1790 instruction->dst.type = registerType(dst);
1791 instruction->dst.index = registerIndex(dst) + dstIndex;
1792 instruction->dst.mask = writeMask(dst);
1793 instruction->dst.integer = (dst->getBasicType() == EbtInt);
1794 }
1795
1796 argument(instruction->src[0], src0, index0);
1797 argument(instruction->src[1], src1, index1);
1798 argument(instruction->src[2], src2, index2);
1799 argument(instruction->src[3], src3, index3);
1800 argument(instruction->src[4], src4, index4);
1801
1802 shader->append(instruction);
1803
1804 return instruction;
1805 }
1806
1807 Instruction *OutputASM::emitCast(TIntermTyped *dst, TIntermTyped *src)
1808 {
1809 return emitCast(dst, 0, src, 0);
1810 }
1811
1812 Instruction *OutputASM::emitCast(TIntermTyped *dst, int dstIndex, TIntermTyped *src, int srcIndex)
1813 {
1814 switch(src->getBasicType())
1815 {
1816 case EbtBool:
1817 switch(dst->getBasicType())
1818 {
1819 case EbtInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1820 case EbtUInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1821 case EbtFloat: return emit(sw::Shader::OPCODE_B2F, dst, dstIndex, src, srcIndex);
1822 default: break;
1823 }
1824 break;
1825 case EbtInt:
1826 switch(dst->getBasicType())
1827 {
1828 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1829 case EbtFloat: return emit(sw::Shader::OPCODE_I2F, dst, dstIndex, src, srcIndex);
1830 default: break;
1831 }
1832 break;
1833 case EbtUInt:
1834 switch(dst->getBasicType())
1835 {
1836 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1837 case EbtFloat: return emit(sw::Shader::OPCODE_U2F, dst, dstIndex, src, srcIndex);
1838 default: break;
1839 }
1840 break;
1841 case EbtFloat:
1842 switch(dst->getBasicType())
1843 {
1844 case EbtBool: return emit(sw::Shader::OPCODE_F2B, dst, dstIndex, src, srcIndex);
1845 case EbtInt: return emit(sw::Shader::OPCODE_F2I, dst, dstIndex, src, srcIndex);
1846 case EbtUInt: return emit(sw::Shader::OPCODE_F2U, dst, dstIndex, src, srcIndex);
1847 default: break;
1848 }
1849 break;
1850 default:
1851 break;
1852 }
1853
1854 ASSERT((src->getBasicType() == dst->getBasicType()) ||
1855 ((src->getBasicType() == EbtInt) && (dst->getBasicType() == EbtUInt)) ||
1856 ((src->getBasicType() == EbtUInt) && (dst->getBasicType() == EbtInt)));
1857
1858 return emit(sw::Shader::OPCODE_MOV, dst, dstIndex, src, srcIndex);
1859 }
1860
1861 void OutputASM::emitBinary(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2)
1862 {
1863 for(int index = 0; index < dst->elementRegisterCount(); index++)
1864 {
1865 emit(op, dst, index, src0, index, src1, index, src2, index);
1866 }
1867 }
1868
1869 void OutputASM::emitAssign(sw::Shader::Opcode op, TIntermTyped *result, TIntermTyped *lhs, TIntermTyped *src0, TIntermTyped *src1)
1870 {
1871 emitBinary(op, result, src0, src1);
1872 assignLvalue(lhs, result);
1873 }
1874
1875 void OutputASM::emitCmp(sw::Shader::Control cmpOp, TIntermTyped *dst, TIntermNode *left, TIntermNode *right, int index)
1876 {
1877 sw::Shader::Opcode opcode;
1878 switch(left->getAsTyped()->getBasicType())
1879 {
1880 case EbtBool:
1881 case EbtInt:
1882 opcode = sw::Shader::OPCODE_ICMP;
1883 break;
1884 case EbtUInt:
1885 opcode = sw::Shader::OPCODE_UCMP;
1886 break;
1887 default:
1888 opcode = sw::Shader::OPCODE_CMP;
1889 break;
1890 }
1891
1892 Instruction *cmp = emit(opcode, dst, 0, left, index, right, index);
1893 cmp->control = cmpOp;
1894 }
1895
1896 int componentCount(const TType &type, int registers)
1897 {
1898 if(registers == 0)
1899 {
1900 return 0;
1901 }
1902
1903 if(type.isArray() && registers >= type.elementRegisterCount())
1904 {
1905 int index = registers / type.elementRegisterCount();
1906 registers -= index * type.elementRegisterCount();
1907 return index * type.getElementSize() + componentCount(type, registers);
1908 }
1909
1910 if(type.isStruct() || type.isInterfaceBlock())
1911 {
1912 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
1913 int elements = 0;
1914
1915 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
1916 {
1917 const TType &fieldType = *((*field)->type());
1918
1919 if(fieldType.totalRegisterCount() <= registers)
1920 {
1921 registers -= fieldType.totalRegisterCount();
1922 elements += fieldType.getObjectSize();
1923 }
1924 else // Register within this field
1925 {
1926 return elements + componentCount(fieldType, registers);
1927 }
1928 }
1929 }
1930 else if(type.isMatrix())
1931 {
1932 return registers * type.registerSize();
1933 }
1934
1935 UNREACHABLE(0);
1936 return 0;
1937 }
1938
1939 int registerSize(const TType &type, int registers)
1940 {
1941 if(registers == 0)
1942 {
1943 if(type.isStruct())
1944 {
1945 return registerSize(*((*(type.getStruct()->fields().begin()))->type()), 0);
1946 }
1947 else if(type.isInterfaceBlock())
1948 {
1949 return registerSize(*((*(type.getInterfaceBlock()->fields().begin()))->type()), 0);
1950 }
1951
1952 return type.registerSize();
1953 }
1954
1955 if(type.isArray() && registers >= type.elementRegisterCount())
1956 {
1957 int index = registers / type.elementRegisterCount();
1958 registers -= index * type.elementRegisterCount();
1959 return registerSize(type, registers);
1960 }
1961
1962 if(type.isStruct() || type.isInterfaceBlock())
1963 {
1964 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
1965 int elements = 0;
1966
1967 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
1968 {
1969 const TType &fieldType = *((*field)->type());
1970
1971 if(fieldType.totalRegisterCount() <= registers)
1972 {
1973 registers -= fieldType.totalRegisterCount();
1974 elements += fieldType.getObjectSize();
1975 }
1976 else // Register within this field
1977 {
1978 return registerSize(fieldType, registers);
1979 }
1980 }
1981 }
1982 else if(type.isMatrix())
1983 {
1984 return registerSize(type, 0);
1985 }
1986
1987 UNREACHABLE(0);
1988 return 0;
1989 }
1990
1991 int OutputASM::getBlockId(TIntermTyped *arg)
1992 {
1993 if(arg)
1994 {
1995 const TType &type = arg->getType();
1996 TInterfaceBlock* block = type.getInterfaceBlock();
1997 if(block && (type.getQualifier() == EvqUniform))
1998 {
1999 // Make sure the uniform block is declared
2000 uniformRegister(arg);
2001
2002 const char* blockName = block->name().c_str();
2003
2004 // Fetch uniform block index from array of blocks
2005 for(ActiveUniformBlocks::const_iterator it = shaderObject->activeUniformBlocks.begin(); it != shaderObject->activeUniformBlocks.end(); ++it)
2006 {
2007 if(blockName == it->name)
2008 {
2009 return it->blockId;
2010 }
2011 }
2012
2013 ASSERT(false);
2014 }
2015 }
2016
2017 return -1;
2018 }
2019
2020 OutputASM::ArgumentInfo OutputASM::getArgumentInfo(TIntermTyped *arg, int index)
2021 {
2022 const TType &type = arg->getType();
2023 int blockId = getBlockId(arg);
2024 ArgumentInfo argumentInfo(BlockMemberInfo::getDefaultBlockInfo(), type, -1, -1);
2025 if(blockId != -1)
2026 {
2027 argumentInfo.bufferIndex = 0;
2028 for(int i = 0; i < blockId; ++i)
2029 {
2030 int blockArraySize = shaderObject->activeUniformBlocks[i].arraySize;
2031 argumentInfo.bufferIndex += blockArraySize > 0 ? blockArraySize : 1;
2032 }
2033
2034 const BlockDefinitionIndexMap& blockDefinition = blockDefinitions[blockId];
2035
2036 BlockDefinitionIndexMap::const_iterator itEnd = blockDefinition.end();
2037 BlockDefinitionIndexMap::const_iterator it = itEnd;
2038
2039 argumentInfo.clampedIndex = index;
2040 if(type.isInterfaceBlock())
2041 {
2042 // Offset index to the beginning of the selected instance
2043 int blockRegisters = type.elementRegisterCount();
2044 int bufferOffset = argumentInfo.clampedIndex / blockRegisters;
2045 argumentInfo.bufferIndex += bufferOffset;
2046 argumentInfo.clampedIndex -= bufferOffset * blockRegisters;
2047 }
2048
2049 int regIndex = registerIndex(arg);
2050 for(int i = regIndex + argumentInfo.clampedIndex; i >= regIndex; --i)
2051 {
2052 it = blockDefinition.find(i);
2053 if(it != itEnd)
2054 {
2055 argumentInfo.clampedIndex -= (i - regIndex);
2056 break;
2057 }
2058 }
2059 ASSERT(it != itEnd);
2060
2061 argumentInfo.typedMemberInfo = it->second;
2062
2063 int registerCount = argumentInfo.typedMemberInfo.type.totalRegisterCount();
2064 argumentInfo.clampedIndex = (argumentInfo.clampedIndex >= registerCount) ? registerCount - 1 : argumentInfo.clampedIndex;
2065 }
2066 else
2067 {
2068 argumentInfo.clampedIndex = (index >= arg->totalRegisterCount()) ? arg->totalRegisterCount() - 1 : index;
2069 }
2070
2071 return argumentInfo;
2072 }
2073
2074 void OutputASM::argument(sw::Shader::SourceParameter &parameter, TIntermNode *argument, int index)
2075 {
2076 if(argument)
2077 {
2078 TIntermTyped *arg = argument->getAsTyped();
2079 Temporary unpackedUniform(this);
2080
2081 const TType& srcType = arg->getType();
2082 TInterfaceBlock* srcBlock = srcType.getInterfaceBlock();
2083 if(srcBlock && (srcType.getQualifier() == EvqUniform))
2084 {
2085 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2086 const TType &memberType = argumentInfo.typedMemberInfo.type;
2087
2088 if(memberType.getBasicType() == EbtBool)
2089 {
2090 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2091 ASSERT(argumentInfo.clampedIndex < arraySize);
2092
2093 // Convert the packed bool, which is currently an int, to a true bool
2094 Instruction *instruction = new Instruction(sw::Shader::OPCODE_I2B);
2095 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2096 instruction->dst.index = registerIndex(&unpackedUniform);
2097 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2098 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2099 instruction->src[0].index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * argumentInfo.typedMemberInfo.arrayStride;
2100
2101 shader->append(instruction);
2102
2103 arg = &unpackedUniform;
2104 index = 0;
2105 }
2106 else if((srcBlock->matrixPacking() == EmpRowMajor) && memberType.isMatrix())
2107 {
2108 int numCols = memberType.getNominalSize();
2109 int numRows = memberType.getSecondarySize();
2110 int arraySize = (memberType.isArray() ? memberType.getArraySize() : 1);
2111
2112 ASSERT(argumentInfo.clampedIndex < (numCols * arraySize));
2113
2114 unsigned int dstIndex = registerIndex(&unpackedUniform);
2115 unsigned int srcSwizzle = (argumentInfo.clampedIndex % numCols) * 0x55;
2116 int arrayIndex = argumentInfo.clampedIndex / numCols;
2117 int matrixStartOffset = argumentInfo.typedMemberInfo.offset + arrayIndex * argumentInfo.typedMemberInfo.arrayStride;
2118
2119 for(int j = 0; j < numRows; ++j)
2120 {
2121 // Transpose the row major matrix
2122 Instruction *instruction = new Instruction(sw::Shader::OPCODE_MOV);
2123 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2124 instruction->dst.index = dstIndex;
2125 instruction->dst.mask = 1 << j;
2126 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2127 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2128 instruction->src[0].index = matrixStartOffset + j * argumentInfo.typedMemberInfo.matrixStride;
2129 instruction->src[0].swizzle = srcSwizzle;
2130
2131 shader->append(instruction);
2132 }
2133
2134 arg = &unpackedUniform;
2135 index = 0;
2136 }
2137 }
2138
2139 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2140 const TType &type = argumentInfo.typedMemberInfo.type;
2141
2142 int size = registerSize(type, argumentInfo.clampedIndex);
2143
2144 parameter.type = registerType(arg);
2145 parameter.bufferIndex = argumentInfo.bufferIndex;
2146
2147 if(arg->getAsConstantUnion() && arg->getAsConstantUnion()->getUnionArrayPointer())
2148 {
2149 int component = componentCount(type, argumentInfo.clampedIndex);
2150 ConstantUnion *constants = arg->getAsConstantUnion()->getUnionArrayPointer();
2151
2152 for(int i = 0; i < 4; i++)
2153 {
2154 if(size == 1) // Replicate
2155 {
2156 parameter.value[i] = constants[component + 0].getAsFloat();
2157 }
2158 else if(i < size)
2159 {
2160 parameter.value[i] = constants[component + i].getAsFloat();
2161 }
2162 else
2163 {
2164 parameter.value[i] = 0.0f;
2165 }
2166 }
2167 }
2168 else
2169 {
2170 parameter.index = registerIndex(arg) + argumentInfo.clampedIndex;
2171
2172 if(parameter.bufferIndex != -1)
2173 {
2174 int stride = (argumentInfo.typedMemberInfo.matrixStride > 0) ? argumentInfo.typedMemberInfo.matrixStride : argumentInfo.typedMemberInfo.arrayStride;
2175 parameter.index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * stride;
2176 }
2177 }
2178
2179 if(!IsSampler(arg->getBasicType()))
2180 {
2181 parameter.swizzle = readSwizzle(arg, size);
2182 }
2183 }
2184 }
2185
2186 void OutputASM::copy(TIntermTyped *dst, TIntermNode *src, int offset)
2187 {
2188 for(int index = 0; index < dst->totalRegisterCount(); index++)
2189 {
2190 Instruction *mov = emit(sw::Shader::OPCODE_MOV, dst, index, src, offset + index);
2191 mov->dst.mask = writeMask(dst, index);
2192 }
2193 }
2194
2195 int swizzleElement(int swizzle, int index)
2196 {
2197 return (swizzle >> (index * 2)) & 0x03;
2198 }
2199
2200 int swizzleSwizzle(int leftSwizzle, int rightSwizzle)
2201 {
2202 return (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 0)) << 0) |
2203 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 1)) << 2) |
2204 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 2)) << 4) |
2205 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 3)) << 6);
2206 }
2207
2208 void OutputASM::assignLvalue(TIntermTyped *dst, TIntermTyped *src)
2209 {
2210 if(src &&
2211 ((src->isVector() && (!dst->isVector() || (src->getNominalSize() != dst->getNominalSize()))) ||
2212 (src->isMatrix() && (!dst->isMatrix() || (src->getNominalSize() != dst->getNominalSize()) || (src->getSecondarySize() != dst->getSecondarySize())))))
2213 {
2214 return mContext.error(src->getLine(), "Result type should match the l-value type in compound assignment", src->isVector() ? "vector" : "matrix");
2215 }
2216
2217 TIntermBinary *binary = dst->getAsBinaryNode();
2218
2219 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && dst->isScalar())
2220 {
2221 Instruction *insert = new Instruction(sw::Shader::OPCODE_INSERT);
2222
2223 Temporary address(this);
2224 lvalue(insert->dst, address, dst);
2225
2226 insert->src[0].type = insert->dst.type;
2227 insert->src[0].index = insert->dst.index;
2228 insert->src[0].rel = insert->dst.rel;
2229 argument(insert->src[1], src);
2230 argument(insert->src[2], binary->getRight());
2231
2232 shader->append(insert);
2233 }
2234 else
2235 {
2236 for(int offset = 0; offset < dst->totalRegisterCount(); offset++)
2237 {
2238 Instruction *mov = new Instruction(sw::Shader::OPCODE_MOV);
2239
2240 Temporary address(this);
2241 int swizzle = lvalue(mov->dst, address, dst);
2242 mov->dst.index += offset;
2243
2244 if(offset > 0)
2245 {
2246 mov->dst.mask = writeMask(dst, offset);
2247 }
2248
2249 argument(mov->src[0], src, offset);
2250 mov->src[0].swizzle = swizzleSwizzle(mov->src[0].swizzle, swizzle);
2251
2252 shader->append(mov);
2253 }
2254 }
2255 }
2256
2257 int OutputASM::lvalue(sw::Shader::DestinationParameter &dst, Temporary &address, TIntermTyped *node)
2258 {
2259 TIntermTyped *result = node;
2260 TIntermBinary *binary = node->getAsBinaryNode();
2261 TIntermSymbol *symbol = node->getAsSymbolNode();
2262
2263 if(binary)
2264 {
2265 TIntermTyped *left = binary->getLeft();
2266 TIntermTyped *right = binary->getRight();
2267
2268 int leftSwizzle = lvalue(dst, address, left); // Resolve the l-value of the left side
2269
2270 switch(binary->getOp())
2271 {
2272 case EOpIndexDirect:
2273 {
2274 int rightIndex = right->getAsConstantUnion()->getIConst(0);
2275
2276 if(left->isRegister())
2277 {
2278 int leftMask = dst.mask;
2279
2280 dst.mask = 1;
2281 while((leftMask & dst.mask) == 0)
2282 {
2283 dst.mask = dst.mask << 1;
2284 }
2285
2286 int element = swizzleElement(leftSwizzle, rightIndex);
2287 dst.mask = 1 << element;
2288
2289 return element;
2290 }
2291 else if(left->isArray() || left->isMatrix())
2292 {
2293 dst.index += rightIndex * result->totalRegisterCount();
2294 return 0xE4;
2295 }
2296 else UNREACHABLE(0);
2297 }
2298 break;
2299 case EOpIndexIndirect:
2300 {
2301 if(left->isRegister())
2302 {
2303 // Requires INSERT instruction (handled by calling function)
2304 }
2305 else if(left->isArray() || left->isMatrix())
2306 {
2307 int scale = result->totalRegisterCount();
2308
2309 if(dst.rel.type == sw::Shader::PARAMETER_VOID) // Use the index register as the relative address directly
2310 {
2311 if(left->totalRegisterCount() > 1)
2312 {
2313 sw::Shader::SourceParameter relativeRegister;
2314 argument(relativeRegister, right);
2315
2316 dst.rel.index = relativeRegister.index;
2317 dst.rel.type = relativeRegister.type;
2318 dst.rel.scale = scale;
2319 dst.rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
2320 }
2321 }
2322 else if(dst.rel.index != registerIndex(&address)) // Move the previous index register to the address register
2323 {
2324 if(scale == 1)
2325 {
2326 Constant oldScale((int)dst.rel.scale);
2327 Instruction *mad = emit(sw::Shader::OPCODE_IMAD, &address, &address, &oldScale, right);
2328 mad->src[0].index = dst.rel.index;
2329 mad->src[0].type = dst.rel.type;
2330 }
2331 else
2332 {
2333 Constant oldScale((int)dst.rel.scale);
2334 Instruction *mul = emit(sw::Shader::OPCODE_IMUL, &address, &address, &oldScale);
2335 mul->src[0].index = dst.rel.index;
2336 mul->src[0].type = dst.rel.type;
2337
2338 Constant newScale(scale);
2339 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2340 }
2341
2342 dst.rel.type = sw::Shader::PARAMETER_TEMP;
2343 dst.rel.index = registerIndex(&address);
2344 dst.rel.scale = 1;
2345 }
2346 else // Just add the new index to the address register
2347 {
2348 if(scale == 1)
2349 {
2350 emit(sw::Shader::OPCODE_IADD, &address, &address, right);
2351 }
2352 else
2353 {
2354 Constant newScale(scale);
2355 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2356 }
2357 }
2358 }
2359 else UNREACHABLE(0);
2360 }
2361 break;
2362 case EOpIndexDirectStruct:
2363 case EOpIndexDirectInterfaceBlock:
2364 {
2365 const TFieldList& fields = (binary->getOp() == EOpIndexDirectStruct) ?
2366 left->getType().getStruct()->fields() :
2367 left->getType().getInterfaceBlock()->fields();
2368 int index = right->getAsConstantUnion()->getIConst(0);
2369 int fieldOffset = 0;
2370
2371 for(int i = 0; i < index; i++)
2372 {
2373 fieldOffset += fields[i]->type()->totalRegisterCount();
2374 }
2375
2376 dst.type = registerType(left);
2377 dst.index += fieldOffset;
2378 dst.mask = writeMask(right);
2379
2380 return 0xE4;
2381 }
2382 break;
2383 case EOpVectorSwizzle:
2384 {
2385 ASSERT(left->isRegister());
2386
2387 int leftMask = dst.mask;
2388
2389 int swizzle = 0;
2390 int rightMask = 0;
2391
2392 TIntermSequence &sequence = right->getAsAggregate()->getSequence();
2393
2394 for(unsigned int i = 0; i < sequence.size(); i++)
2395 {
2396 int index = sequence[i]->getAsConstantUnion()->getIConst(0);
2397
2398 int element = swizzleElement(leftSwizzle, index);
2399 rightMask = rightMask | (1 << element);
2400 swizzle = swizzle | swizzleElement(leftSwizzle, i) << (element * 2);
2401 }
2402
2403 dst.mask = leftMask & rightMask;
2404
2405 return swizzle;
2406 }
2407 break;
2408 default:
2409 UNREACHABLE(binary->getOp()); // Not an l-value operator
2410 break;
2411 }
2412 }
2413 else if(symbol)
2414 {
2415 dst.type = registerType(symbol);
2416 dst.index = registerIndex(symbol);
2417 dst.mask = writeMask(symbol);
2418 return 0xE4;
2419 }
2420
2421 return 0xE4;
2422 }
2423
2424 sw::Shader::ParameterType OutputASM::registerType(TIntermTyped *operand)
2425 {
2426 if(isSamplerRegister(operand))
2427 {
2428 return sw::Shader::PARAMETER_SAMPLER;
2429 }
2430
2431 const TQualifier qualifier = operand->getQualifier();
2432 if((EvqFragColor == qualifier) || (EvqFragData == qualifier))
2433 {
2434 if(((EvqFragData == qualifier) && (EvqFragColor == outputQualifier)) ||
2435 ((EvqFragColor == qualifier) && (EvqFragData == outputQualifier)))
2436 {
2437 mContext.error(operand->getLine(), "static assignment to both gl_FragData and gl_FragColor", "");
2438 }
2439 outputQualifier = qualifier;
2440 }
2441
2442 if(qualifier == EvqConstExpr && (!operand->getAsConstantUnion() || !operand->getAsConstantUnion()->getUnionArrayPointer()))
2443 {
2444 return sw::Shader::PARAMETER_TEMP;
2445 }
2446
2447 switch(qualifier)
2448 {
2449 case EvqTemporary: return sw::Shader::PARAMETER_TEMP;
2450 case EvqGlobal: return sw::Shader::PARAMETER_TEMP;
2451 case EvqConstExpr: return sw::Shader::PARAMETER_FLOAT4LITERAL; // All converted to float
2452 case EvqAttribute: return sw::Shader::PARAMETER_INPUT;
2453 case EvqVaryingIn: return sw::Shader::PARAMETER_INPUT;
2454 case EvqVaryingOut: return sw::Shader::PARAMETER_OUTPUT;
2455 case EvqVertexIn: return sw::Shader::PARAMETER_INPUT;
2456 case EvqFragmentOut: return sw::Shader::PARAMETER_COLOROUT;
2457 case EvqVertexOut: return sw::Shader::PARAMETER_OUTPUT;
2458 case EvqFragmentIn: return sw::Shader::PARAMETER_INPUT;
2459 case EvqInvariantVaryingIn: return sw::Shader::PARAMETER_INPUT; // FIXME: Guarantee invariance at the backend
2460 case EvqInvariantVaryingOut: return sw::Shader::PARAMETER_OUTPUT; // FIXME: Guarantee invariance at the backend
2461 case EvqSmooth: return sw::Shader::PARAMETER_OUTPUT;
2462 case EvqFlat: return sw::Shader::PARAMETER_OUTPUT;
2463 case EvqCentroidOut: return sw::Shader::PARAMETER_OUTPUT;
2464 case EvqSmoothIn: return sw::Shader::PARAMETER_INPUT;
2465 case EvqFlatIn: return sw::Shader::PARAMETER_INPUT;
2466 case EvqCentroidIn: return sw::Shader::PARAMETER_INPUT;
2467 case EvqUniform: return sw::Shader::PARAMETER_CONST;
2468 case EvqIn: return sw::Shader::PARAMETER_TEMP;
2469 case EvqOut: return sw::Shader::PARAMETER_TEMP;
2470 case EvqInOut: return sw::Shader::PARAMETER_TEMP;
2471 case EvqConstReadOnly: return sw::Shader::PARAMETER_TEMP;
2472 case EvqPosition: return sw::Shader::PARAMETER_OUTPUT;
2473 case EvqPointSize: return sw::Shader::PARAMETER_OUTPUT;
2474 case EvqInstanceID: return sw::Shader::PARAMETER_MISCTYPE;
2475 case EvqFragCoord: return sw::Shader::PARAMETER_MISCTYPE;
2476 case EvqFrontFacing: return sw::Shader::PARAMETER_MISCTYPE;
2477 case EvqPointCoord: return sw::Shader::PARAMETER_INPUT;
2478 case EvqFragColor: return sw::Shader::PARAMETER_COLOROUT;
2479 case EvqFragData: return sw::Shader::PARAMETER_COLOROUT;
2480 case EvqFragDepth: return sw::Shader::PARAMETER_DEPTHOUT;
2481 default: UNREACHABLE(qualifier);
2482 }
2483
2484 return sw::Shader::PARAMETER_VOID;
2485 }
2486
2487 unsigned int OutputASM::registerIndex(TIntermTyped *operand)
2488 {
2489 if(isSamplerRegister(operand))
2490 {
2491 return samplerRegister(operand);
2492 }
2493
2494 switch(operand->getQualifier())
2495 {
2496 case EvqTemporary: return temporaryRegister(operand);
2497 case EvqGlobal: return temporaryRegister(operand);
2498 case EvqConstExpr: return temporaryRegister(operand); // Unevaluated constant expression
2499 case EvqAttribute: return attributeRegister(operand);
2500 case EvqVaryingIn: return varyingRegister(operand);
2501 case EvqVaryingOut: return varyingRegister(operand);
2502 case EvqVertexIn: return attributeRegister(operand);
2503 case EvqFragmentOut: return fragmentOutputRegister(operand);
2504 case EvqVertexOut: return varyingRegister(operand);
2505 case EvqFragmentIn: return varyingRegister(operand);
2506 case EvqInvariantVaryingIn: return varyingRegister(operand);
2507 case EvqInvariantVaryingOut: return varyingRegister(operand);
2508 case EvqSmooth: return varyingRegister(operand);
2509 case EvqFlat: return varyingRegister(operand);
2510 case EvqCentroidOut: return varyingRegister(operand);
2511 case EvqSmoothIn: return varyingRegister(operand);
2512 case EvqFlatIn: return varyingRegister(operand);
2513 case EvqCentroidIn: return varyingRegister(operand);
2514 case EvqUniform: return uniformRegister(operand);
2515 case EvqIn: return temporaryRegister(operand);
2516 case EvqOut: return temporaryRegister(operand);
2517 case EvqInOut: return temporaryRegister(operand);
2518 case EvqConstReadOnly: return temporaryRegister(operand);
2519 case EvqPosition: return varyingRegister(operand);
2520 case EvqPointSize: return varyingRegister(operand);
2521 case EvqInstanceID: vertexShader->instanceIdDeclared = true; return 0;
2522 case EvqFragCoord: pixelShader->vPosDeclared = true; return 0;
2523 case EvqFrontFacing: pixelShader->vFaceDeclared = true; return 1;
2524 case EvqPointCoord: return varyingRegister(operand);
2525 case EvqFragColor: return 0;
2526 case EvqFragData: return fragmentOutputRegister(operand);
2527 case EvqFragDepth: return 0;
2528 default: UNREACHABLE(operand->getQualifier());
2529 }
2530
2531 return 0;
2532 }
2533
2534 int OutputASM::writeMask(TIntermTyped *destination, int index)
2535 {
2536 if(destination->getQualifier() == EvqPointSize)
2537 {
2538 return 0x2; // Point size stored in the y component
2539 }
2540
2541 return 0xF >> (4 - registerSize(destination->getType(), index));
2542 }
2543
2544 int OutputASM::readSwizzle(TIntermTyped *argument, int size)
2545 {
2546 if(argument->getQualifier() == EvqPointSize)
2547 {
2548 return 0x55; // Point size stored in the y component
2549 }
2550
2551 static const unsigned char swizzleSize[5] = {0x00, 0x00, 0x54, 0xA4, 0xE4}; // (void), xxxx, xyyy, xyzz, xyzw
2552
2553 return swizzleSize[size];
2554 }
2555
2556 // Conservatively checks whether an expression is fast to compute and has no side effects
2557 bool OutputASM::trivial(TIntermTyped *expression, int budget)
2558 {
2559 if(!expression->isRegister())
2560 {
2561 return false;
2562 }
2563
2564 return cost(expression, budget) >= 0;
2565 }
2566
2567 // Returns the remaining computing budget (if < 0 the expression is too expensive or has side effects)
2568 int OutputASM::cost(TIntermNode *expression, int budget)
2569 {
2570 if(budget < 0)
2571 {
2572 return budget;
2573 }
2574
2575 if(expression->getAsSymbolNode())
2576 {
2577 return budget;
2578 }
2579 else if(expression->getAsConstantUnion())
2580 {
2581 return budget;
2582 }
2583 else if(expression->getAsBinaryNode())
2584 {
2585 TIntermBinary *binary = expression->getAsBinaryNode();
2586
2587 switch(binary->getOp())
2588 {
2589 case EOpVectorSwizzle:
2590 case EOpIndexDirect:
2591 case EOpIndexDirectStruct:
2592 case EOpIndexDirectInterfaceBlock:
2593 return cost(binary->getLeft(), budget - 0);
2594 case EOpAdd:
2595 case EOpSub:
2596 case EOpMul:
2597 return cost(binary->getLeft(), cost(binary->getRight(), budget - 1));
2598 default:
2599 return -1;
2600 }
2601 }
2602 else if(expression->getAsUnaryNode())
2603 {
2604 TIntermUnary *unary = expression->getAsUnaryNode();
2605
2606 switch(unary->getOp())
2607 {
2608 case EOpAbs:
2609 case EOpNegative:
2610 return cost(unary->getOperand(), budget - 1);
2611 default:
2612 return -1;
2613 }
2614 }
2615 else if(expression->getAsSelectionNode())
2616 {
2617 TIntermSelection *selection = expression->getAsSelectionNode();
2618
2619 if(selection->usesTernaryOperator())
2620 {
2621 TIntermTyped *condition = selection->getCondition();
2622 TIntermNode *trueBlock = selection->getTrueBlock();
2623 TIntermNode *falseBlock = selection->getFalseBlock();
2624 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
2625
2626 if(constantCondition)
2627 {
2628 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
2629
2630 if(trueCondition)
2631 {
2632 return cost(trueBlock, budget - 0);
2633 }
2634 else
2635 {
2636 return cost(falseBlock, budget - 0);
2637 }
2638 }
2639 else
2640 {
2641 return cost(trueBlock, cost(falseBlock, budget - 2));
2642 }
2643 }
2644 }
2645
2646 return -1;
2647 }
2648
2649 const Function *OutputASM::findFunction(const TString &name)
2650 {
2651 for(unsigned int f = 0; f < functionArray.size(); f++)
2652 {
2653 if(functionArray[f].name == name)
2654 {
2655 return &functionArray[f];
2656 }
2657 }
2658
2659 return 0;
2660 }
2661
2662 int OutputASM::temporaryRegister(TIntermTyped *temporary)
2663 {
2664 return allocate(temporaries, temporary);
2665 }
2666
2667 int OutputASM::varyingRegister(TIntermTyped *varying)
2668 {
2669 int var = lookup(varyings, varying);
2670
2671 if(var == -1)
2672 {
2673 var = allocate(varyings, varying);
2674 int componentCount = varying->registerSize();
2675 int registerCount = varying->totalRegisterCount();
2676
2677 if(pixelShader)
2678 {
2679 if((var + registerCount) > sw::PixelShader::MAX_INPUT_VARYINGS)
2680 {
2681 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "fragment shader");
2682 return 0;
2683 }
2684
2685 if(varying->getQualifier() == EvqPointCoord)
2686 {
2687 ASSERT(varying->isRegister());
2688 if(componentCount >= 1) pixelShader->semantic[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2689 if(componentCount >= 2) pixelShader->semantic[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2690 if(componentCount >= 3) pixelShader->semantic[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2691 if(componentCount >= 4) pixelShader->semantic[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var);
2692 }
2693 else
2694 {
2695 for(int i = 0; i < varying->totalRegisterCount(); i++)
2696 {
2697 if(componentCount >= 1) pixelShader->semantic[var + i][0] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2698 if(componentCount >= 2) pixelShader->semantic[var + i][1] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2699 if(componentCount >= 3) pixelShader->semantic[var + i][2] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2700 if(componentCount >= 4) pixelShader->semantic[var + i][3] = sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i);
2701 }
2702 }
2703 }
2704 else if(vertexShader)
2705 {
2706 if((var + registerCount) > sw::VertexShader::MAX_OUTPUT_VARYINGS)
2707 {
2708 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "vertex shader");
2709 return 0;
2710 }
2711
2712 if(varying->getQualifier() == EvqPosition)
2713 {
2714 ASSERT(varying->isRegister());
2715 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2716 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2717 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2718 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_POSITION, 0);
2719 vertexShader->positionRegister = var;
2720 }
2721 else if(varying->getQualifier() == EvqPointSize)
2722 {
2723 ASSERT(varying->isRegister());
2724 vertexShader->output[var][0] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2725 vertexShader->output[var][1] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2726 vertexShader->output[var][2] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2727 vertexShader->output[var][3] = sw::Shader::Semantic(sw::Shader::USAGE_PSIZE, 0);
2728 vertexShader->pointSizeRegister = var;
2729 }
2730 else
2731 {
2732 // Semantic indexes for user varyings will be assigned during program link to match the pixel shader
2733 }
2734 }
2735 else UNREACHABLE(0);
2736
2737 declareVarying(varying, var);
2738 }
2739
2740 return var;
2741 }
2742
2743 void OutputASM::declareVarying(TIntermTyped *varying, int reg)
2744 {
2745 if(varying->getQualifier() != EvqPointCoord) // gl_PointCoord does not need linking
2746 {
2747 const TType &type = varying->getType();
2748 const char *name = varying->getAsSymbolNode()->getSymbol().c_str();
2749 VaryingList &activeVaryings = shaderObject->varyings;
2750
2751 // Check if this varying has been declared before without having a register assigned
2752 for(VaryingList::iterator v = activeVaryings.begin(); v != activeVaryings.end(); v++)
2753 {
2754 if(v->name == name)
2755 {
2756 if(reg >= 0)
2757 {
2758 ASSERT(v->reg < 0 || v->reg == reg);
2759 v->reg = reg;
2760 }
2761
2762 return;
2763 }
2764 }
2765
2766 activeVaryings.push_back(glsl::Varying(glVariableType(type), name, varying->getArraySize(), reg, 0));
2767 }
2768 }
2769
2770 int OutputASM::uniformRegister(TIntermTyped *uniform)
2771 {
2772 const TType &type = uniform->getType();
2773 ASSERT(!IsSampler(type.getBasicType()));
2774 TInterfaceBlock *block = type.getAsInterfaceBlock();
2775 TIntermSymbol *symbol = uniform->getAsSymbolNode();
2776 ASSERT(symbol || block);
2777
2778 if(symbol || block)
2779 {
2780 TInterfaceBlock* parentBlock = type.getInterfaceBlock();
2781 bool isBlockMember = (!block && parentBlock);
2782 int index = isBlockMember ? lookup(uniforms, parentBlock) : lookup(uniforms, uniform);
2783
2784 if(index == -1 || isBlockMember)
2785 {
2786 if(index == -1)
2787 {
2788 index = allocate(uniforms, uniform);
2789 }
2790
2791 // Verify if the current uniform is a member of an already declared block
2792 const TString &name = symbol ? symbol->getSymbol() : block->name();
2793 int blockMemberIndex = blockMemberLookup(type, name, index);
2794 if(blockMemberIndex == -1)
2795 {
2796 declareUniform(type, name, index);
2797 }
2798 else
2799 {
2800 index = blockMemberIndex;
2801 }
2802 }
2803
2804 return index;
2805 }
2806
2807 return 0;
2808 }
2809
2810 int OutputASM::attributeRegister(TIntermTyped *attribute)
2811 {
2812 ASSERT(!attribute->isArray());
2813
2814 int index = lookup(attributes, attribute);
2815
2816 if(index == -1)
2817 {
2818 TIntermSymbol *symbol = attribute->getAsSymbolNode();
2819 ASSERT(symbol);
2820
2821 if(symbol)
2822 {
2823 index = allocate(attributes, attribute);
2824 const TType &type = attribute->getType();
2825 int registerCount = attribute->totalRegisterCount();
2826
2827 if(vertexShader && (index + registerCount) <= sw::VertexShader::MAX_INPUT_ATTRIBUTES)
2828 {
2829 for(int i = 0; i < registerCount; i++)
2830 {
2831 vertexShader->input[index + i] = sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, index + i);
2832 }
2833 }
2834
2835 ActiveAttributes &activeAttributes = shaderObject->activeAttributes;
2836
2837 const char *name = symbol->getSymbol().c_str();
2838 activeAttributes.push_back(Attribute(glVariableType(type), name, type.getArraySize(), type.getLayoutQualifier().location, index));
2839 }
2840 }
2841
2842 return index;
2843 }
2844
2845 int OutputASM::fragmentOutputRegister(TIntermTyped *fragmentOutput)
2846 {
2847 return allocate(fragmentOutputs, fragmentOutput);
2848 }
2849
2850 int OutputASM::samplerRegister(TIntermTyped *sampler)
2851 {
2852 const TType &type = sampler->getType();
2853 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
2854
2855 TIntermSymbol *symbol = sampler->getAsSymbolNode();
2856 TIntermBinary *binary = sampler->getAsBinaryNode();
2857
2858 if(symbol && type.getQualifier() == EvqUniform)
2859 {
2860 return samplerRegister(symbol);
2861 }
2862 else if(binary)
2863 {
2864 TIntermTyped *left = binary->getLeft();
2865 TIntermTyped *right = binary->getRight();
2866 const TType &leftType = left->getType();
2867 int index = right->getAsConstantUnion() ? right->getAsConstantUnion()->getIConst(0) : 0;
2868 int offset = 0;
2869
2870 switch(binary->getOp())
2871 {
2872 case EOpIndexDirect:
2873 ASSERT(left->isArray());
2874 offset = index * leftType.elementRegisterCount();
2875 break;
2876 case EOpIndexDirectStruct:
2877 ASSERT(leftType.isStruct());
2878 {
2879 const TFieldList &fields = leftType.getStruct()->fields();
2880
2881 for(int i = 0; i < index; i++)
2882 {
2883 offset += fields[i]->type()->totalRegisterCount();
2884 }
2885 }
2886 break;
2887 case EOpIndexIndirect: // Indirect indexing produces a temporary, not a sampler register
2888 return -1;
2889 case EOpIndexDirectInterfaceBlock: // Interface blocks can't contain samplers
2890 default:
2891 UNREACHABLE(binary->getOp());
2892 return -1;
2893 }
2894
2895 int base = samplerRegister(left);
2896
2897 if(base < 0)
2898 {
2899 return -1;
2900 }
2901
2902 return base + offset;
2903 }
2904
2905 UNREACHABLE(0);
2906 return -1; // Not a sampler register
2907 }
2908
2909 int OutputASM::samplerRegister(TIntermSymbol *sampler)
2910 {
2911 const TType &type = sampler->getType();
2912 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
2913
2914 int index = lookup(samplers, sampler);
2915
2916 if(index == -1)
2917 {
2918 index = allocate(samplers, sampler);
2919
2920 if(sampler->getQualifier() == EvqUniform)
2921 {
2922 const char *name = sampler->getSymbol().c_str();
2923 declareUniform(type, name, index);
2924 }
2925 }
2926
2927 return index;
2928 }
2929
2930 bool OutputASM::isSamplerRegister(TIntermTyped *operand)
2931 {
2932 return operand && IsSampler(operand->getBasicType()) && samplerRegister(operand) >= 0;
2933 }
2934
2935 int OutputASM::lookup(VariableArray &list, TIntermTyped *variable)
2936 {
2937 for(unsigned int i = 0; i < list.size(); i++)
2938 {
2939 if(list[i] == variable)
2940 {
2941 return i; // Pointer match
2942 }
2943 }
2944
2945 TIntermSymbol *varSymbol = variable->getAsSymbolNode();
2946 TInterfaceBlock *varBlock = variable->getType().getAsInterfaceBlock();
2947
2948 if(varBlock)
2949 {
2950 for(unsigned int i = 0; i < list.size(); i++)
2951 {
2952 if(list[i])
2953 {
2954 TInterfaceBlock *listBlock = list[i]->getType().getAsInterfaceBlock();
2955
2956 if(listBlock)
2957 {
2958 if(listBlock->name() == varBlock->name())
2959 {
2960 ASSERT(listBlock->arraySize() == varBlock->arraySize());
2961 ASSERT(listBlock->fields() == varBlock->fields());
2962 ASSERT(listBlock->blockStorage() == varBlock->blockStorage());
2963 ASSERT(listBlock->matrixPacking() == varBlock->matrixPacking());
2964
2965 return i;
2966 }
2967 }
2968 }
2969 }
2970 }
2971 else if(varSymbol)
2972 {
2973 for(unsigned int i = 0; i < list.size(); i++)
2974 {
2975 if(list[i])
2976 {
2977 TIntermSymbol *listSymbol = list[i]->getAsSymbolNode();
2978
2979 if(listSymbol)
2980 {
2981 if(listSymbol->getId() == varSymbol->getId())
2982 {
2983 ASSERT(listSymbol->getSymbol() == varSymbol->getSymbol());
2984 ASSERT(listSymbol->getType() == varSymbol->getType());
2985 ASSERT(listSymbol->getQualifier() == varSymbol->getQualifier());
2986
2987 return i;
2988 }
2989 }
2990 }
2991 }
2992 }
2993
2994 return -1;
2995 }
2996
2997 int OutputASM::lookup(VariableArray &list, TInterfaceBlock *block)
2998 {
2999 for(unsigned int i = 0; i < list.size(); i++)
3000 {
3001 if(list[i] && (list[i]->getType().getInterfaceBlock() == block))
3002 {
3003 return i; // Pointer match
3004 }
3005 }
3006 return -1;
3007 }
3008
3009 int OutputASM::allocate(VariableArray &list, TIntermTyped *variable)
3010 {
3011 int index = lookup(list, variable);
3012
3013 if(index == -1)
3014 {
3015 unsigned int registerCount = variable->blockRegisterCount();
3016
3017 for(unsigned int i = 0; i < list.size(); i++)
3018 {
3019 if(list[i] == 0)
3020 {
3021 unsigned int j = 1;
3022 for( ; j < registerCount && (i + j) < list.size(); j++)
3023 {
3024 if(list[i + j] != 0)
3025 {
3026 break;
3027 }
3028 }
3029
3030 if(j == registerCount) // Found free slots
3031 {
3032 for(unsigned int j = 0; j < registerCount; j++)
3033 {
3034 list[i + j] = variable;
3035 }
3036
3037 return i;
3038 }
3039 }
3040 }
3041
3042 index = list.size();
3043
3044 for(unsigned int i = 0; i < registerCount; i++)
3045 {
3046 list.push_back(variable);
3047 }
3048 }
3049
3050 return index;
3051 }
3052
3053 void OutputASM::free(VariableArray &list, TIntermTyped *variable)
3054 {
3055 int index = lookup(list, variable);
3056
3057 if(index >= 0)
3058 {
3059 list[index] = 0;
3060 }
3061 }
3062
3063 int OutputASM::blockMemberLookup(const TType &type, const TString &name, int registerIndex)
3064 {
3065 const TInterfaceBlock *block = type.getInterfaceBlock();
3066
3067 if(block)
3068 {
3069 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3070 const TFieldList& fields = block->fields();
3071 const TString &blockName = block->name();
3072 int fieldRegisterIndex = registerIndex;
3073
3074 if(!type.isInterfaceBlock())
3075 {
3076 // This is a uniform that's part of a block, let's see if the block is already defined
3077 for(size_t i = 0; i < activeUniformBlocks.size(); ++i)
3078 {
3079 if(activeUniformBlocks[i].name == blockName.c_str())
3080 {
3081 // The block is already defined, find the register for the current uniform and return it
3082 for(size_t j = 0; j < fields.size(); j++)
3083 {
3084 const TString &fieldName = fields[j]->name();
3085 if(fieldName == name)
3086 {
3087 return fieldRegisterIndex;
3088 }
3089
3090 fieldRegisterIndex += fields[j]->type()->totalRegisterCount();
3091 }
3092
3093 ASSERT(false);
3094 return fieldRegisterIndex;
3095 }
3096 }
3097 }
3098 }
3099
3100 return -1;
3101 }
3102
3103 void OutputASM::declareUniform(const TType &type, const TString &name, int registerIndex, int blockId, BlockLayoutEncoder* encoder)
3104 {
3105 const TStructure *structure = type.getStruct();
3106 const TInterfaceBlock *block = (type.isInterfaceBlock() || (blockId == -1)) ? type.getInterfaceBlock() : nullptr;
3107
3108 if(!structure && !block)
3109 {
3110 ActiveUniforms &activeUniforms = shaderObject->activeUniforms;
3111 const BlockMemberInfo blockInfo = encoder ? encoder->encodeType(type) : BlockMemberInfo::getDefaultBlockInfo();
3112 if(blockId >= 0)
3113 {
3114 blockDefinitions[blockId][registerIndex] = TypedMemberInfo(blockInfo, type);
3115 shaderObject->activeUniformBlocks[blockId].fields.push_back(activeUniforms.size());
3116 }
3117 int fieldRegisterIndex = encoder ? shaderObject->activeUniformBlocks[blockId].registerIndex + BlockLayoutEncoder::getBlockRegister(blockInfo) : registerIndex;
3118 activeUniforms.push_back(Uniform(glVariableType(type), glVariablePrecision(type), name.c_str(), type.getArraySize(),
3119 fieldRegisterIndex, blockId, blockInfo));
3120 if(IsSampler(type.getBasicType()))
3121 {
3122 for(int i = 0; i < type.totalRegisterCount(); i++)
3123 {
3124 shader->declareSampler(fieldRegisterIndex + i);
3125 }
3126 }
3127 }
3128 else if(block)
3129 {
3130 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3131 const TFieldList& fields = block->fields();
3132 const TString &blockName = block->name();
3133 int fieldRegisterIndex = registerIndex;
3134 bool isUniformBlockMember = !type.isInterfaceBlock() && (blockId == -1);
3135
3136 blockId = activeUniformBlocks.size();
3137 bool isRowMajor = block->matrixPacking() == EmpRowMajor;
3138 activeUniformBlocks.push_back(UniformBlock(blockName.c_str(), 0, block->arraySize(),
3139 block->blockStorage(), isRowMajor, registerIndex, blockId));
3140 blockDefinitions.push_back(BlockDefinitionIndexMap());
3141
3142 Std140BlockEncoder currentBlockEncoder(isRowMajor);
3143 currentBlockEncoder.enterAggregateType();
3144 for(size_t i = 0; i < fields.size(); i++)
3145 {
3146 const TType &fieldType = *(fields[i]->type());
3147 const TString &fieldName = fields[i]->name();
3148 if(isUniformBlockMember && (fieldName == name))
3149 {
3150 registerIndex = fieldRegisterIndex;
3151 }
3152
3153 const TString uniformName = block->hasInstanceName() ? blockName + "." + fieldName : fieldName;
3154
3155 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, &currentBlockEncoder);
3156 fieldRegisterIndex += fieldType.totalRegisterCount();
3157 }
3158 currentBlockEncoder.exitAggregateType();
3159 activeUniformBlocks[blockId].dataSize = currentBlockEncoder.getBlockSize();
3160 }
3161 else
3162 {
3163 int fieldRegisterIndex = registerIndex;
3164
3165 const TFieldList& fields = structure->fields();
3166 if(type.isArray() && (structure || type.isInterfaceBlock()))
3167 {
3168 for(int i = 0; i < type.getArraySize(); i++)
3169 {
3170 if(encoder)
3171 {
3172 encoder->enterAggregateType();
3173 }
3174 for(size_t j = 0; j < fields.size(); j++)
3175 {
3176 const TType &fieldType = *(fields[j]->type());
3177 const TString &fieldName = fields[j]->name();
3178 const TString uniformName = name + "[" + str(i) + "]." + fieldName;
3179
3180 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3181 fieldRegisterIndex += fieldType.totalRegisterCount();
3182 }
3183 if(encoder)
3184 {
3185 encoder->exitAggregateType();
3186 }
3187 }
3188 }
3189 else
3190 {
3191 if(encoder)
3192 {
3193 encoder->enterAggregateType();
3194 }
3195 for(size_t i = 0; i < fields.size(); i++)
3196 {
3197 const TType &fieldType = *(fields[i]->type());
3198 const TString &fieldName = fields[i]->name();
3199 const TString uniformName = name + "." + fieldName;
3200
3201 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3202 fieldRegisterIndex += fieldType.totalRegisterCount();
3203 }
3204 if(encoder)
3205 {
3206 encoder->exitAggregateType();
3207 }
3208 }
3209 }
3210 }
3211
3212 GLenum OutputASM::glVariableType(const TType &type)
3213 {
3214 switch(type.getBasicType())
3215 {
3216 case EbtFloat:
3217 if(type.isScalar())
3218 {
3219 return GL_FLOAT;
3220 }
3221 else if(type.isVector())
3222 {
3223 switch(type.getNominalSize())
3224 {
3225 case 2: return GL_FLOAT_VEC2;
3226 case 3: return GL_FLOAT_VEC3;
3227 case 4: return GL_FLOAT_VEC4;
3228 default: UNREACHABLE(type.getNominalSize());
3229 }
3230 }
3231 else if(type.isMatrix())
3232 {
3233 switch(type.getNominalSize())
3234 {
3235 case 2:
3236 switch(type.getSecondarySize())
3237 {
3238 case 2: return GL_FLOAT_MAT2;
3239 case 3: return GL_FLOAT_MAT2x3;
3240 case 4: return GL_FLOAT_MAT2x4;
3241 default: UNREACHABLE(type.getSecondarySize());
3242 }
3243 case 3:
3244 switch(type.getSecondarySize())
3245 {
3246 case 2: return GL_FLOAT_MAT3x2;
3247 case 3: return GL_FLOAT_MAT3;
3248 case 4: return GL_FLOAT_MAT3x4;
3249 default: UNREACHABLE(type.getSecondarySize());
3250 }
3251 case 4:
3252 switch(type.getSecondarySize())
3253 {
3254 case 2: return GL_FLOAT_MAT4x2;
3255 case 3: return GL_FLOAT_MAT4x3;
3256 case 4: return GL_FLOAT_MAT4;
3257 default: UNREACHABLE(type.getSecondarySize());
3258 }
3259 default: UNREACHABLE(type.getNominalSize());
3260 }
3261 }
3262 else UNREACHABLE(0);
3263 break;
3264 case EbtInt:
3265 if(type.isScalar())
3266 {
3267 return GL_INT;
3268 }
3269 else if(type.isVector())
3270 {
3271 switch(type.getNominalSize())
3272 {
3273 case 2: return GL_INT_VEC2;
3274 case 3: return GL_INT_VEC3;
3275 case 4: return GL_INT_VEC4;
3276 default: UNREACHABLE(type.getNominalSize());
3277 }
3278 }
3279 else UNREACHABLE(0);
3280 break;
3281 case EbtUInt:
3282 if(type.isScalar())
3283 {
3284 return GL_UNSIGNED_INT;
3285 }
3286 else if(type.isVector())
3287 {
3288 switch(type.getNominalSize())
3289 {
3290 case 2: return GL_UNSIGNED_INT_VEC2;
3291 case 3: return GL_UNSIGNED_INT_VEC3;
3292 case 4: return GL_UNSIGNED_INT_VEC4;
3293 default: UNREACHABLE(type.getNominalSize());
3294 }
3295 }
3296 else UNREACHABLE(0);
3297 break;
3298 case EbtBool:
3299 if(type.isScalar())
3300 {
3301 return GL_BOOL;
3302 }
3303 else if(type.isVector())
3304 {
3305 switch(type.getNominalSize())
3306 {
3307 case 2: return GL_BOOL_VEC2;
3308 case 3: return GL_BOOL_VEC3;
3309 case 4: return GL_BOOL_VEC4;
3310 default: UNREACHABLE(type.getNominalSize());
3311 }
3312 }
3313 else UNREACHABLE(0);
3314 break;
3315 case EbtSampler2D:
3316 return GL_SAMPLER_2D;
3317 case EbtISampler2D:
3318 return GL_INT_SAMPLER_2D;
3319 case EbtUSampler2D:
3320 return GL_UNSIGNED_INT_SAMPLER_2D;
3321 case EbtSamplerCube:
3322 return GL_SAMPLER_CUBE;
3323 case EbtISamplerCube:
3324 return GL_INT_SAMPLER_CUBE;
3325 case EbtUSamplerCube:
3326 return GL_UNSIGNED_INT_SAMPLER_CUBE;
3327 case EbtSamplerExternalOES:
3328 return GL_SAMPLER_EXTERNAL_OES;
3329 case EbtSampler3D:
3330 return GL_SAMPLER_3D_OES;
3331 case EbtISampler3D:
3332 return GL_INT_SAMPLER_3D;
3333 case EbtUSampler3D:
3334 return GL_UNSIGNED_INT_SAMPLER_3D;
3335 case EbtSampler2DArray:
3336 return GL_SAMPLER_2D_ARRAY;
3337 case EbtISampler2DArray:
3338 return GL_INT_SAMPLER_2D_ARRAY;
3339 case EbtUSampler2DArray:
3340 return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
3341 case EbtSampler2DShadow:
3342 return GL_SAMPLER_2D_SHADOW;
3343 case EbtSamplerCubeShadow:
3344 return GL_SAMPLER_CUBE_SHADOW;
3345 case EbtSampler2DArrayShadow:
3346 return GL_SAMPLER_2D_ARRAY_SHADOW;
3347 default:
3348 UNREACHABLE(type.getBasicType());
3349 break;
3350 }
3351
3352 return GL_NONE;
3353 }
3354
3355 GLenum OutputASM::glVariablePrecision(const TType &type)
3356 {
3357 if(type.getBasicType() == EbtFloat)
3358 {
3359 switch(type.getPrecision())
3360 {
3361 case EbpHigh: return GL_HIGH_FLOAT;
3362 case EbpMedium: return GL_MEDIUM_FLOAT;
3363 case EbpLow: return GL_LOW_FLOAT;
3364 case EbpUndefined:
3365 // Should be defined as the default precision by the parser
3366 default: UNREACHABLE(type.getPrecision());
3367 }
3368 }
3369 else if(type.getBasicType() == EbtInt)
3370 {
3371 switch(type.getPrecision())
3372 {
3373 case EbpHigh: return GL_HIGH_INT;
3374 case EbpMedium: return GL_MEDIUM_INT;
3375 case EbpLow: return GL_LOW_INT;
3376 case EbpUndefined:
3377 // Should be defined as the default precision by the parser
3378 default: UNREACHABLE(type.getPrecision());
3379 }
3380 }
3381
3382 // Other types (boolean, sampler) don't have a precision
3383 return GL_NONE;
3384 }
3385
3386 int OutputASM::dim(TIntermNode *v)
3387 {
3388 TIntermTyped *vector = v->getAsTyped();
3389 ASSERT(vector && vector->isRegister());
3390 return vector->getNominalSize();
3391 }
3392
3393 int OutputASM::dim2(TIntermNode *m)
3394 {
3395 TIntermTyped *matrix = m->getAsTyped();
3396 ASSERT(matrix && matrix->isMatrix() && !matrix->isArray());
3397 return matrix->getSecondarySize();
3398 }
3399
3400 // Returns ~0u if no loop count could be determined
3401 unsigned int OutputASM::loopCount(TIntermLoop *node)
3402 {
3403 // Parse loops of the form:
3404 // for(int index = initial; index [comparator] limit; index += increment)
3405 TIntermSymbol *index = 0;
3406 TOperator comparator = EOpNull;
3407 int initial = 0;
3408 int limit = 0;
3409 int increment = 0;
3410
3411 // Parse index name and intial value
3412 if(node->getInit())
3413 {
3414 TIntermAggregate *init = node->getInit()->getAsAggregate();
3415
3416 if(init)
3417 {
3418 TIntermSequence &sequence = init->getSequence();
3419 TIntermTyped *variable = sequence[0]->getAsTyped();
3420
3421 if(variable && variable->getQualifier() == EvqTemporary)
3422 {
3423 TIntermBinary *assign = variable->getAsBinaryNode();
3424
3425 if(assign->getOp() == EOpInitialize)
3426 {
3427 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3428 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3429
3430 if(symbol && constant)
3431 {
3432 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3433 {
3434 index = symbol;
3435 initial = constant->getUnionArrayPointer()[0].getIConst();
3436 }
3437 }
3438 }
3439 }
3440 }
3441 }
3442
3443 // Parse comparator and limit value
3444 if(index && node->getCondition())
3445 {
3446 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
3447
3448 if(test && test->getLeft()->getAsSymbolNode()->getId() == index->getId())
3449 {
3450 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3451
3452 if(constant)
3453 {
3454 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3455 {
3456 comparator = test->getOp();
3457 limit = constant->getUnionArrayPointer()[0].getIConst();
3458 }
3459 }
3460 }
3461 }
3462
3463 // Parse increment
3464 if(index && comparator != EOpNull && node->getExpression())
3465 {
3466 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3467 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3468
3469 if(binaryTerminal)
3470 {
3471 TOperator op = binaryTerminal->getOp();
3472 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3473
3474 if(constant)
3475 {
3476 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3477 {
3478 int value = constant->getUnionArrayPointer()[0].getIConst();
3479
3480 switch(op)
3481 {
3482 case EOpAddAssign: increment = value; break;
3483 case EOpSubAssign: increment = -value; break;
3484 default: UNIMPLEMENTED();
3485 }
3486 }
3487 }
3488 }
3489 else if(unaryTerminal)
3490 {
3491 TOperator op = unaryTerminal->getOp();
3492
3493 switch(op)
3494 {
3495 case EOpPostIncrement: increment = 1; break;
3496 case EOpPostDecrement: increment = -1; break;
3497 case EOpPreIncrement: increment = 1; break;
3498 case EOpPreDecrement: increment = -1; break;
3499 default: UNIMPLEMENTED();
3500 }
3501 }
3502 }
3503
3504 if(index && comparator != EOpNull && increment != 0)
3505 {
3506 if(comparator == EOpLessThanEqual)
3507 {
3508 comparator = EOpLessThan;
3509 limit += 1;
3510 }
3511
3512 if(comparator == EOpLessThan)
3513 {
3514 int iterations = (limit - initial) / increment;
3515
3516 if(iterations <= 0)
3517 {
3518 iterations = 0;
3519 }
3520
3521 return iterations;
3522 }
3523 else UNIMPLEMENTED(); // Falls through
3524 }
3525
3526 return ~0u;
3527 }
3528
3529 bool LoopUnrollable::traverse(TIntermNode *node)
3530 {
3531 loopDepth = 0;
3532 loopUnrollable = true;
3533
3534 node->traverse(this);
3535
3536 return loopUnrollable;
3537 }
3538
3539 bool LoopUnrollable::visitLoop(Visit visit, TIntermLoop *loop)
3540 {
3541 if(visit == PreVisit)
3542 {
3543 loopDepth++;
3544 }
3545 else if(visit == PostVisit)
3546 {
3547 loopDepth++;
3548 }
3549
3550 return true;
3551 }
3552
3553 bool LoopUnrollable::visitBranch(Visit visit, TIntermBranch *node)
3554 {
3555 if(!loopUnrollable)
3556 {
3557 return false;
3558 }
3559
3560 if(!loopDepth)
3561 {
3562 return true;
3563 }
3564
3565 switch(node->getFlowOp())
3566 {
3567 case EOpKill:
3568 case EOpReturn:
3569 break;
3570 case EOpBreak:
3571 case EOpContinue:
3572 loopUnrollable = false;
3573 break;
3574 default: UNREACHABLE(node->getFlowOp());
3575 }
3576
3577 return loopUnrollable;
3578 }
3579
3580 bool LoopUnrollable::visitAggregate(Visit visit, TIntermAggregate *node)
3581 {
3582 return loopUnrollable;
3583 }
3584}