blob: d3a0184620398f80fdf250c498a399ddcd2eccbc [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
Nicolas Capens930b7002017-01-06 17:22:13 -050027#include <stdlib.h>
28
Nicolas Capens0bac2852016-05-07 06:09:58 -040029namespace glsl
30{
31 // Integer to TString conversion
32 TString str(int i)
33 {
34 char buffer[20];
35 sprintf(buffer, "%d", i);
36 return buffer;
37 }
38
39 class Temporary : public TIntermSymbol
40 {
41 public:
42 Temporary(OutputASM *assembler) : TIntermSymbol(TSymbolTableLevel::nextUniqueId(), "tmp", TType(EbtFloat, EbpHigh, EvqTemporary, 4, 1, false)), assembler(assembler)
43 {
44 }
45
46 ~Temporary()
47 {
48 assembler->freeTemporary(this);
49 }
50
51 private:
52 OutputASM *const assembler;
53 };
54
55 class Constant : public TIntermConstantUnion
56 {
57 public:
58 Constant(float x, float y, float z, float w) : TIntermConstantUnion(constants, TType(EbtFloat, EbpHigh, EvqConstExpr, 4, 1, false))
59 {
60 constants[0].setFConst(x);
61 constants[1].setFConst(y);
62 constants[2].setFConst(z);
63 constants[3].setFConst(w);
64 }
65
66 Constant(bool b) : TIntermConstantUnion(constants, TType(EbtBool, EbpHigh, EvqConstExpr, 1, 1, false))
67 {
68 constants[0].setBConst(b);
69 }
70
71 Constant(int i) : TIntermConstantUnion(constants, TType(EbtInt, EbpHigh, EvqConstExpr, 1, 1, false))
72 {
73 constants[0].setIConst(i);
74 }
75
76 ~Constant()
77 {
78 }
79
80 private:
81 ConstantUnion constants[4];
82 };
83
84 Uniform::Uniform(GLenum type, GLenum precision, const std::string &name, int arraySize, int registerIndex, int blockId, const BlockMemberInfo& blockMemberInfo) :
85 type(type), precision(precision), name(name), arraySize(arraySize), registerIndex(registerIndex), blockId(blockId), blockInfo(blockMemberInfo)
86 {
87 }
88
89 UniformBlock::UniformBlock(const std::string& name, unsigned int dataSize, unsigned int arraySize,
90 TLayoutBlockStorage layout, bool isRowMajorLayout, int registerIndex, int blockId) :
91 name(name), dataSize(dataSize), arraySize(arraySize), layout(layout),
92 isRowMajorLayout(isRowMajorLayout), registerIndex(registerIndex), blockId(blockId)
93 {
94 }
95
96 BlockLayoutEncoder::BlockLayoutEncoder(bool rowMajor)
97 : mCurrentOffset(0), isRowMajor(rowMajor)
98 {
99 }
100
101 BlockMemberInfo BlockLayoutEncoder::encodeType(const TType &type)
102 {
103 int arrayStride;
104 int matrixStride;
105
106 getBlockLayoutInfo(type, type.getArraySize(), isRowMajor, &arrayStride, &matrixStride);
107
108 const BlockMemberInfo memberInfo(static_cast<int>(mCurrentOffset * BytesPerComponent),
109 static_cast<int>(arrayStride * BytesPerComponent),
110 static_cast<int>(matrixStride * BytesPerComponent),
111 (matrixStride > 0) && isRowMajor);
112
113 advanceOffset(type, type.getArraySize(), isRowMajor, arrayStride, matrixStride);
114
115 return memberInfo;
116 }
117
118 // static
119 size_t BlockLayoutEncoder::getBlockRegister(const BlockMemberInfo &info)
120 {
121 return (info.offset / BytesPerComponent) / ComponentsPerRegister;
122 }
123
124 // static
125 size_t BlockLayoutEncoder::getBlockRegisterElement(const BlockMemberInfo &info)
126 {
127 return (info.offset / BytesPerComponent) % ComponentsPerRegister;
128 }
129
130 void BlockLayoutEncoder::nextRegister()
131 {
132 mCurrentOffset = sw::align(mCurrentOffset, ComponentsPerRegister);
133 }
134
135 Std140BlockEncoder::Std140BlockEncoder(bool rowMajor) : BlockLayoutEncoder(rowMajor)
136 {
137 }
138
139 void Std140BlockEncoder::enterAggregateType()
140 {
141 nextRegister();
142 }
143
144 void Std140BlockEncoder::exitAggregateType()
145 {
146 nextRegister();
147 }
148
149 void Std140BlockEncoder::getBlockLayoutInfo(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
150 {
151 size_t baseAlignment = 0;
152 int matrixStride = 0;
153 int arrayStride = 0;
154
155 if(type.isMatrix())
156 {
157 baseAlignment = ComponentsPerRegister;
158 matrixStride = ComponentsPerRegister;
159
160 if(arraySize > 0)
161 {
162 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
163 arrayStride = ComponentsPerRegister * numRegisters;
164 }
165 }
166 else if(arraySize > 0)
167 {
168 baseAlignment = ComponentsPerRegister;
169 arrayStride = ComponentsPerRegister;
170 }
171 else
172 {
173 const size_t numComponents = type.getElementSize();
174 baseAlignment = (numComponents == 3 ? 4u : numComponents);
175 }
176
177 mCurrentOffset = sw::align(mCurrentOffset, baseAlignment);
178
179 *matrixStrideOut = matrixStride;
180 *arrayStrideOut = arrayStride;
181 }
182
183 void Std140BlockEncoder::advanceOffset(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
184 {
185 if(arraySize > 0)
186 {
187 mCurrentOffset += arrayStride * arraySize;
188 }
189 else if(type.isMatrix())
190 {
191 ASSERT(matrixStride == ComponentsPerRegister);
192 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
193 mCurrentOffset += ComponentsPerRegister * numRegisters;
194 }
195 else
196 {
197 mCurrentOffset += type.getElementSize();
198 }
199 }
200
201 Attribute::Attribute()
202 {
203 type = GL_NONE;
204 arraySize = 0;
205 registerIndex = 0;
206 }
207
208 Attribute::Attribute(GLenum type, const std::string &name, int arraySize, int location, int registerIndex)
209 {
210 this->type = type;
211 this->name = name;
212 this->arraySize = arraySize;
213 this->location = location;
214 this->registerIndex = registerIndex;
215 }
216
217 sw::PixelShader *Shader::getPixelShader() const
218 {
219 return 0;
220 }
221
222 sw::VertexShader *Shader::getVertexShader() const
223 {
224 return 0;
225 }
226
227 OutputASM::TextureFunction::TextureFunction(const TString& nodeName) : method(IMPLICIT), proj(false), offset(false)
228 {
229 TString name = TFunction::unmangleName(nodeName);
230
231 if(name == "texture2D" || name == "textureCube" || name == "texture" || name == "texture3D")
232 {
233 method = IMPLICIT;
234 }
235 else if(name == "texture2DProj" || name == "textureProj")
236 {
237 method = IMPLICIT;
238 proj = true;
239 }
240 else if(name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod")
241 {
242 method = LOD;
243 }
244 else if(name == "texture2DProjLod" || name == "textureProjLod")
245 {
246 method = LOD;
247 proj = true;
248 }
249 else if(name == "textureSize")
250 {
251 method = SIZE;
252 }
253 else if(name == "textureOffset")
254 {
255 method = IMPLICIT;
256 offset = true;
257 }
258 else if(name == "textureProjOffset")
259 {
260 method = IMPLICIT;
261 offset = true;
262 proj = true;
263 }
264 else if(name == "textureLodOffset")
265 {
266 method = LOD;
267 offset = true;
268 }
269 else if(name == "textureProjLodOffset")
270 {
271 method = LOD;
272 proj = true;
273 offset = true;
274 }
275 else if(name == "texelFetch")
276 {
277 method = FETCH;
278 }
279 else if(name == "texelFetchOffset")
280 {
281 method = FETCH;
282 offset = true;
283 }
284 else if(name == "textureGrad")
285 {
286 method = GRAD;
287 }
288 else if(name == "textureGradOffset")
289 {
290 method = GRAD;
291 offset = true;
292 }
293 else if(name == "textureProjGrad")
294 {
295 method = GRAD;
296 proj = true;
297 }
298 else if(name == "textureProjGradOffset")
299 {
300 method = GRAD;
301 proj = true;
302 offset = true;
303 }
304 else UNREACHABLE(0);
305 }
306
307 OutputASM::OutputASM(TParseContext &context, Shader *shaderObject) : TIntermTraverser(true, true, true), shaderObject(shaderObject), mContext(context)
308 {
309 shader = 0;
310 pixelShader = 0;
311 vertexShader = 0;
312
313 if(shaderObject)
314 {
315 shader = shaderObject->getShader();
316 pixelShader = shaderObject->getPixelShader();
317 vertexShader = shaderObject->getVertexShader();
318 }
319
320 functionArray.push_back(Function(0, "main(", 0, 0));
321 currentFunction = 0;
322 outputQualifier = EvqOutput; // Set outputQualifier to any value other than EvqFragColor or EvqFragData
323 }
324
325 OutputASM::~OutputASM()
326 {
327 }
328
329 void OutputASM::output()
330 {
331 if(shader)
332 {
333 emitShader(GLOBAL);
334
335 if(functionArray.size() > 1) // Only call main() when there are other functions
336 {
337 Instruction *callMain = emit(sw::Shader::OPCODE_CALL);
338 callMain->dst.type = sw::Shader::PARAMETER_LABEL;
339 callMain->dst.index = 0; // main()
340
341 emit(sw::Shader::OPCODE_RET);
342 }
343
344 emitShader(FUNCTION);
345 }
346 }
347
348 void OutputASM::emitShader(Scope scope)
349 {
350 emitScope = scope;
351 currentScope = GLOBAL;
352 mContext.getTreeRoot()->traverse(this);
353 }
354
355 void OutputASM::freeTemporary(Temporary *temporary)
356 {
357 free(temporaries, temporary);
358 }
359
360 sw::Shader::Opcode OutputASM::getOpcode(sw::Shader::Opcode op, TIntermTyped *in) const
361 {
362 TBasicType baseType = in->getType().getBasicType();
363
364 switch(op)
365 {
366 case sw::Shader::OPCODE_NEG:
367 switch(baseType)
368 {
369 case EbtInt:
370 case EbtUInt:
371 return sw::Shader::OPCODE_INEG;
372 case EbtFloat:
373 default:
374 return op;
375 }
376 case sw::Shader::OPCODE_ABS:
377 switch(baseType)
378 {
379 case EbtInt:
380 return sw::Shader::OPCODE_IABS;
381 case EbtFloat:
382 default:
383 return op;
384 }
385 case sw::Shader::OPCODE_SGN:
386 switch(baseType)
387 {
388 case EbtInt:
389 return sw::Shader::OPCODE_ISGN;
390 case EbtFloat:
391 default:
392 return op;
393 }
394 case sw::Shader::OPCODE_ADD:
395 switch(baseType)
396 {
397 case EbtInt:
398 case EbtUInt:
399 return sw::Shader::OPCODE_IADD;
400 case EbtFloat:
401 default:
402 return op;
403 }
404 case sw::Shader::OPCODE_SUB:
405 switch(baseType)
406 {
407 case EbtInt:
408 case EbtUInt:
409 return sw::Shader::OPCODE_ISUB;
410 case EbtFloat:
411 default:
412 return op;
413 }
414 case sw::Shader::OPCODE_MUL:
415 switch(baseType)
416 {
417 case EbtInt:
418 case EbtUInt:
419 return sw::Shader::OPCODE_IMUL;
420 case EbtFloat:
421 default:
422 return op;
423 }
424 case sw::Shader::OPCODE_DIV:
425 switch(baseType)
426 {
427 case EbtInt:
428 return sw::Shader::OPCODE_IDIV;
429 case EbtUInt:
430 return sw::Shader::OPCODE_UDIV;
431 case EbtFloat:
432 default:
433 return op;
434 }
435 case sw::Shader::OPCODE_IMOD:
436 return baseType == EbtUInt ? sw::Shader::OPCODE_UMOD : op;
437 case sw::Shader::OPCODE_ISHR:
438 return baseType == EbtUInt ? sw::Shader::OPCODE_USHR : op;
439 case sw::Shader::OPCODE_MIN:
440 switch(baseType)
441 {
442 case EbtInt:
443 return sw::Shader::OPCODE_IMIN;
444 case EbtUInt:
445 return sw::Shader::OPCODE_UMIN;
446 case EbtFloat:
447 default:
448 return op;
449 }
450 case sw::Shader::OPCODE_MAX:
451 switch(baseType)
452 {
453 case EbtInt:
454 return sw::Shader::OPCODE_IMAX;
455 case EbtUInt:
456 return sw::Shader::OPCODE_UMAX;
457 case EbtFloat:
458 default:
459 return op;
460 }
461 default:
462 return op;
463 }
464 }
465
466 void OutputASM::visitSymbol(TIntermSymbol *symbol)
467 {
468 // Vertex varyings don't have to be actively used to successfully link
469 // against pixel shaders that use them. So make sure they're declared.
470 if(symbol->getQualifier() == EvqVaryingOut || symbol->getQualifier() == EvqInvariantVaryingOut || symbol->getQualifier() == EvqVertexOut)
471 {
472 if(symbol->getBasicType() != EbtInvariant) // Typeless declarations are not new varyings
473 {
474 declareVarying(symbol, -1);
475 }
476 }
477
478 TInterfaceBlock* block = symbol->getType().getInterfaceBlock();
479 // OpenGL ES 3.0.4 spec, section 2.12.6 Uniform Variables:
480 // "All members of a named uniform block declared with a shared or std140 layout qualifier
481 // are considered active, even if they are not referenced in any shader in the program.
482 // The uniform block itself is also considered active, even if no member of the block is referenced."
483 if(block && ((block->blockStorage() == EbsShared) || (block->blockStorage() == EbsStd140)))
484 {
485 uniformRegister(symbol);
486 }
487 }
488
489 bool OutputASM::visitBinary(Visit visit, TIntermBinary *node)
490 {
491 if(currentScope != emitScope)
492 {
493 return false;
494 }
495
496 TIntermTyped *result = node;
497 TIntermTyped *left = node->getLeft();
498 TIntermTyped *right = node->getRight();
499 const TType &leftType = left->getType();
500 const TType &rightType = right->getType();
Nicolas Capens0bac2852016-05-07 06:09:58 -0400501
502 if(isSamplerRegister(result))
503 {
504 return false; // Don't traverse, the register index is determined statically
505 }
506
507 switch(node->getOp())
508 {
509 case EOpAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500510 assert(visit == PreVisit);
511 right->traverse(this);
512 assignLvalue(left, right);
513 copy(result, right);
514 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400515 case EOpInitialize:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500516 assert(visit == PreVisit);
517 right->traverse(this);
518 copy(left, right);
519 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400520 case EOpMatrixTimesScalarAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500521 assert(visit == PreVisit);
522 right->traverse(this);
523 for(int i = 0; i < leftType.getNominalSize(); i++)
Nicolas Capens0bac2852016-05-07 06:09:58 -0400524 {
Nicolas Capens84249fd2017-11-09 11:20:51 -0500525 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400526 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500527
528 assignLvalue(left, result);
529 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400530 case EOpVectorTimesMatrixAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500531 assert(visit == PreVisit);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400532 {
Nicolas Capens84249fd2017-11-09 11:20:51 -0500533 right->traverse(this);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400534 int size = leftType.getNominalSize();
535
536 for(int i = 0; i < size; i++)
537 {
538 Instruction *dot = emit(sw::Shader::OPCODE_DP(size), result, 0, left, 0, right, i);
539 dot->dst.mask = 1 << i;
540 }
541
542 assignLvalue(left, result);
543 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500544 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400545 case EOpMatrixTimesMatrixAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500546 assert(visit == PreVisit);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400547 {
Nicolas Capens84249fd2017-11-09 11:20:51 -0500548 right->traverse(this);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400549 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 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500565 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400566 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;
Nicolas Capens0530b452017-11-15 16:39:47 -0500617 source(relativeRegister, right);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400618
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;
Alexis Hetu18e2a972017-07-28 13:43:25 -0400952 case EOpBitwiseNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400953 case EOpPostIncrement:
954 if(visit == PostVisit)
955 {
956 copy(result, arg);
957
958 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
959 for(int index = 0; index < arg->totalRegisterCount(); index++)
960 {
961 emit(addOpcode, arg, index, arg, index, &one);
962 }
963
964 assignLvalue(arg, arg);
965 }
966 break;
967 case EOpPostDecrement:
968 if(visit == PostVisit)
969 {
970 copy(result, arg);
971
972 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
973 for(int index = 0; index < arg->totalRegisterCount(); index++)
974 {
975 emit(subOpcode, arg, index, arg, index, &one);
976 }
977
978 assignLvalue(arg, arg);
979 }
980 break;
981 case EOpPreIncrement:
982 if(visit == PostVisit)
983 {
984 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
985 for(int index = 0; index < arg->totalRegisterCount(); index++)
986 {
987 emit(addOpcode, result, index, arg, index, &one);
988 }
989
990 assignLvalue(arg, result);
991 }
992 break;
993 case EOpPreDecrement:
994 if(visit == PostVisit)
995 {
996 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
997 for(int index = 0; index < arg->totalRegisterCount(); index++)
998 {
999 emit(subOpcode, result, index, arg, index, &one);
1000 }
1001
1002 assignLvalue(arg, result);
1003 }
1004 break;
1005 case EOpRadians: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &rad); break;
1006 case EOpDegrees: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &deg); break;
1007 case EOpSin: if(visit == PostVisit) emit(sw::Shader::OPCODE_SIN, result, arg); break;
1008 case EOpCos: if(visit == PostVisit) emit(sw::Shader::OPCODE_COS, result, arg); break;
1009 case EOpTan: if(visit == PostVisit) emit(sw::Shader::OPCODE_TAN, result, arg); break;
1010 case EOpAsin: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASIN, result, arg); break;
1011 case EOpAcos: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOS, result, arg); break;
1012 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN, result, arg); break;
1013 case EOpSinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_SINH, result, arg); break;
1014 case EOpCosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_COSH, result, arg); break;
1015 case EOpTanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_TANH, result, arg); break;
1016 case EOpAsinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASINH, result, arg); break;
1017 case EOpAcosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOSH, result, arg); break;
1018 case EOpAtanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATANH, result, arg); break;
1019 case EOpExp: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP, result, arg); break;
1020 case EOpLog: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG, result, arg); break;
1021 case EOpExp2: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP2, result, arg); break;
1022 case EOpLog2: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG2, result, arg); break;
1023 case EOpSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_SQRT, result, arg); break;
1024 case EOpInverseSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_RSQ, result, arg); break;
1025 case EOpAbs: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_ABS, result), result, arg); break;
1026 case EOpSign: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_SGN, result), result, arg); break;
1027 case EOpFloor: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOOR, result, arg); break;
1028 case EOpTrunc: if(visit == PostVisit) emit(sw::Shader::OPCODE_TRUNC, result, arg); break;
1029 case EOpRound: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUND, result, arg); break;
1030 case EOpRoundEven: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUNDEVEN, result, arg); break;
1031 case EOpCeil: if(visit == PostVisit) emit(sw::Shader::OPCODE_CEIL, result, arg, result); break;
1032 case EOpFract: if(visit == PostVisit) emit(sw::Shader::OPCODE_FRC, result, arg); break;
1033 case EOpIsNan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISNAN, result, arg); break;
1034 case EOpIsInf: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISINF, result, arg); break;
1035 case EOpLength: if(visit == PostVisit) emit(sw::Shader::OPCODE_LEN(dim(arg)), result, arg); break;
1036 case EOpNormalize: if(visit == PostVisit) emit(sw::Shader::OPCODE_NRM(dim(arg)), result, arg); break;
1037 case EOpDFdx: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDX, result, arg); break;
1038 case EOpDFdy: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDY, result, arg); break;
1039 case EOpFwidth: if(visit == PostVisit) emit(sw::Shader::OPCODE_FWIDTH, result, arg); break;
1040 case EOpAny: if(visit == PostVisit) emit(sw::Shader::OPCODE_ANY, result, arg); break;
1041 case EOpAll: if(visit == PostVisit) emit(sw::Shader::OPCODE_ALL, result, arg); break;
1042 case EOpFloatBitsToInt: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOINT, result, arg); break;
1043 case EOpFloatBitsToUint: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOUINT, result, arg); break;
1044 case EOpIntBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_INTBITSTOFLOAT, result, arg); break;
1045 case EOpUintBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_UINTBITSTOFLOAT, result, arg); break;
1046 case EOpPackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKSNORM2x16, result, arg); break;
1047 case EOpPackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKUNORM2x16, result, arg); break;
1048 case EOpPackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKHALF2x16, result, arg); break;
1049 case EOpUnpackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKSNORM2x16, result, arg); break;
1050 case EOpUnpackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKUNORM2x16, result, arg); break;
1051 case EOpUnpackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKHALF2x16, result, arg); break;
1052 case EOpTranspose:
1053 if(visit == PostVisit)
1054 {
1055 int numCols = arg->getNominalSize();
1056 int numRows = arg->getSecondarySize();
1057 for(int i = 0; i < numCols; ++i)
1058 {
1059 for(int j = 0; j < numRows; ++j)
1060 {
1061 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, j, arg, i);
1062 mov->src[0].swizzle = 0x55 * j;
1063 mov->dst.mask = 1 << i;
1064 }
1065 }
1066 }
1067 break;
1068 case EOpDeterminant:
1069 if(visit == PostVisit)
1070 {
1071 int size = arg->getNominalSize();
1072 ASSERT(size == arg->getSecondarySize());
1073
1074 emitDeterminant(result, arg, size);
1075 }
1076 break;
1077 case EOpInverse:
1078 if(visit == PostVisit)
1079 {
1080 int size = arg->getNominalSize();
1081 ASSERT(size == arg->getSecondarySize());
1082
1083 // Compute transposed matrix of cofactors
1084 for(int i = 0; i < size; ++i)
1085 {
1086 for(int j = 0; j < size; ++j)
1087 {
1088 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
1089 // For a 3x3 or 4x4 matrix, the cofactor is a transposed determinant
1090 emitDeterminant(result, arg, size - 1, j, i, i, j);
1091 }
1092 }
1093
1094 // Compute 1 / determinant
1095 Temporary invDet(this);
1096 emitDeterminant(&invDet, arg, size);
1097 Constant one(1.0f, 1.0f, 1.0f, 1.0f);
1098 Instruction *div = emit(sw::Shader::OPCODE_DIV, &invDet, &one, &invDet);
1099 div->src[1].swizzle = 0x00; // xxxx
1100
1101 // Divide transposed matrix of cofactors by determinant
1102 for(int i = 0; i < size; ++i)
1103 {
1104 emit(sw::Shader::OPCODE_MUL, result, i, result, i, &invDet);
1105 }
1106 }
1107 break;
1108 default: UNREACHABLE(node->getOp());
1109 }
1110
1111 return true;
1112 }
1113
1114 bool OutputASM::visitAggregate(Visit visit, TIntermAggregate *node)
1115 {
1116 if(currentScope != emitScope && node->getOp() != EOpFunction && node->getOp() != EOpSequence)
1117 {
1118 return false;
1119 }
1120
1121 Constant zero(0.0f, 0.0f, 0.0f, 0.0f);
1122
1123 TIntermTyped *result = node;
1124 const TType &resultType = node->getType();
1125 TIntermSequence &arg = node->getSequence();
1126 size_t argumentCount = arg.size();
1127
1128 switch(node->getOp())
1129 {
1130 case EOpSequence: break;
1131 case EOpDeclaration: break;
1132 case EOpInvariantDeclaration: break;
1133 case EOpPrototype: break;
1134 case EOpComma:
1135 if(visit == PostVisit)
1136 {
1137 copy(result, arg[1]);
1138 }
1139 break;
1140 case EOpFunction:
1141 if(visit == PreVisit)
1142 {
1143 const TString &name = node->getName();
1144
1145 if(emitScope == FUNCTION)
1146 {
1147 if(functionArray.size() > 1) // No need for a label when there's only main()
1148 {
1149 Instruction *label = emit(sw::Shader::OPCODE_LABEL);
1150 label->dst.type = sw::Shader::PARAMETER_LABEL;
1151
1152 const Function *function = findFunction(name);
1153 ASSERT(function); // Should have been added during global pass
1154 label->dst.index = function->label;
1155 currentFunction = function->label;
1156 }
1157 }
1158 else if(emitScope == GLOBAL)
1159 {
1160 if(name != "main(")
1161 {
1162 TIntermSequence &arguments = node->getSequence()[0]->getAsAggregate()->getSequence();
1163 functionArray.push_back(Function(functionArray.size(), name, &arguments, node));
1164 }
1165 }
1166 else UNREACHABLE(emitScope);
1167
1168 currentScope = FUNCTION;
1169 }
1170 else if(visit == PostVisit)
1171 {
1172 if(emitScope == FUNCTION)
1173 {
1174 if(functionArray.size() > 1) // No need to return when there's only main()
1175 {
1176 emit(sw::Shader::OPCODE_RET);
1177 }
1178 }
1179
1180 currentScope = GLOBAL;
1181 }
1182 break;
1183 case EOpFunctionCall:
1184 if(visit == PostVisit)
1185 {
1186 if(node->isUserDefined())
1187 {
1188 const TString &name = node->getName();
1189 const Function *function = findFunction(name);
1190
1191 if(!function)
1192 {
1193 mContext.error(node->getLine(), "function definition not found", name.c_str());
1194 return false;
1195 }
1196
1197 TIntermSequence &arguments = *function->arg;
1198
1199 for(size_t i = 0; i < argumentCount; i++)
1200 {
1201 TIntermTyped *in = arguments[i]->getAsTyped();
1202
1203 if(in->getQualifier() == EvqIn ||
1204 in->getQualifier() == EvqInOut ||
1205 in->getQualifier() == EvqConstReadOnly)
1206 {
1207 copy(in, arg[i]);
1208 }
1209 }
1210
1211 Instruction *call = emit(sw::Shader::OPCODE_CALL);
1212 call->dst.type = sw::Shader::PARAMETER_LABEL;
1213 call->dst.index = function->label;
1214
1215 if(function->ret && function->ret->getType().getBasicType() != EbtVoid)
1216 {
1217 copy(result, function->ret);
1218 }
1219
1220 for(size_t i = 0; i < argumentCount; i++)
1221 {
1222 TIntermTyped *argument = arguments[i]->getAsTyped();
1223 TIntermTyped *out = arg[i]->getAsTyped();
1224
1225 if(argument->getQualifier() == EvqOut ||
1226 argument->getQualifier() == EvqInOut)
1227 {
Nicolas Capens5da2d3f2016-06-11 00:41:49 -04001228 assignLvalue(out, argument);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001229 }
1230 }
1231 }
1232 else
1233 {
1234 const TextureFunction textureFunction(node->getName());
Nicolas Capensa0b57832017-11-07 13:07:53 -05001235 TIntermTyped *s = arg[0]->getAsTyped();
Nicolas Capens0bac2852016-05-07 06:09:58 -04001236 TIntermTyped *t = arg[1]->getAsTyped();
1237
1238 Temporary coord(this);
1239
1240 if(textureFunction.proj)
1241 {
Nicolas Capens0484c792016-06-13 22:02:36 -04001242 Instruction *rcp = emit(sw::Shader::OPCODE_RCPX, &coord, arg[1]);
1243 rcp->src[0].swizzle = 0x55 * (t->getNominalSize() - 1);
1244 rcp->dst.mask = 0x7;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001245
Nicolas Capens0484c792016-06-13 22:02:36 -04001246 Instruction *mul = emit(sw::Shader::OPCODE_MUL, &coord, arg[1], &coord);
1247 mul->dst.mask = 0x7;
Nicolas Capensa0b57832017-11-07 13:07:53 -05001248
1249 if(IsShadowSampler(s->getBasicType()))
1250 {
1251 ASSERT(s->getBasicType() == EbtSampler2DShadow);
1252 Instruction *mov = emit(sw::Shader::OPCODE_MOV, &coord, &coord);
1253 mov->src[0].swizzle = 0xA4;
1254 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001255 }
1256 else
1257 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001258 Instruction *mov = emit(sw::Shader::OPCODE_MOV, &coord, arg[1]);
1259
1260 if(IsShadowSampler(s->getBasicType()) && t->getNominalSize() == 3)
1261 {
1262 ASSERT(s->getBasicType() == EbtSampler2DShadow);
1263 mov->src[0].swizzle = 0xA4;
1264 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001265 }
1266
1267 switch(textureFunction.method)
1268 {
1269 case TextureFunction::IMPLICIT:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001270 if(!textureFunction.offset)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001271 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001272 if(argumentCount == 2)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001273 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001274 emit(sw::Shader::OPCODE_TEX, result, &coord, s);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001275 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001276 else if(argumentCount == 3) // Bias
Nicolas Capens0bac2852016-05-07 06:09:58 -04001277 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001278 emit(sw::Shader::OPCODE_TEXBIAS, result, &coord, s, arg[2]);
1279 }
1280 else UNREACHABLE(argumentCount);
1281 }
1282 else // Offset
1283 {
1284 if(argumentCount == 3)
1285 {
1286 emit(sw::Shader::OPCODE_TEXOFFSET, result, &coord, s, arg[2]);
1287 }
1288 else if(argumentCount == 4) // Bias
1289 {
1290 emit(sw::Shader::OPCODE_TEXOFFSETBIAS, result, &coord, s, arg[2], arg[3]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001291 }
1292 else UNREACHABLE(argumentCount);
1293 }
1294 break;
1295 case TextureFunction::LOD:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001296 if(!textureFunction.offset && argumentCount == 3)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001297 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001298 emit(sw::Shader::OPCODE_TEXLOD, result, &coord, s, arg[2]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001299 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001300 else if(argumentCount == 4) // Offset
1301 {
1302 emit(sw::Shader::OPCODE_TEXLODOFFSET, result, &coord, s, arg[3], arg[2]);
1303 }
1304 else UNREACHABLE(argumentCount);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001305 break;
1306 case TextureFunction::FETCH:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001307 if(!textureFunction.offset && argumentCount == 3)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001308 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001309 emit(sw::Shader::OPCODE_TEXELFETCH, result, &coord, s, arg[2]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001310 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001311 else if(argumentCount == 4) // Offset
1312 {
1313 emit(sw::Shader::OPCODE_TEXELFETCHOFFSET, result, &coord, s, arg[3], arg[2]);
1314 }
1315 else UNREACHABLE(argumentCount);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001316 break;
1317 case TextureFunction::GRAD:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001318 if(!textureFunction.offset && argumentCount == 4)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001319 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001320 emit(sw::Shader::OPCODE_TEXGRAD, result, &coord, s, arg[2], arg[3]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001321 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001322 else if(argumentCount == 5) // Offset
1323 {
1324 emit(sw::Shader::OPCODE_TEXGRADOFFSET, result, &coord, s, arg[2], arg[3], arg[4]);
1325 }
1326 else UNREACHABLE(argumentCount);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001327 break;
1328 case TextureFunction::SIZE:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001329 emit(sw::Shader::OPCODE_TEXSIZE, result, arg[1], s);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001330 break;
1331 default:
1332 UNREACHABLE(textureFunction.method);
1333 }
1334 }
1335 }
1336 break;
1337 case EOpParameters:
1338 break;
1339 case EOpConstructFloat:
1340 case EOpConstructVec2:
1341 case EOpConstructVec3:
1342 case EOpConstructVec4:
1343 case EOpConstructBool:
1344 case EOpConstructBVec2:
1345 case EOpConstructBVec3:
1346 case EOpConstructBVec4:
1347 case EOpConstructInt:
1348 case EOpConstructIVec2:
1349 case EOpConstructIVec3:
1350 case EOpConstructIVec4:
1351 case EOpConstructUInt:
1352 case EOpConstructUVec2:
1353 case EOpConstructUVec3:
1354 case EOpConstructUVec4:
1355 if(visit == PostVisit)
1356 {
1357 int component = 0;
Alexis Hetu2a198552016-09-27 20:50:45 -04001358 int arrayMaxIndex = result->isArray() ? result->getArraySize() - 1 : 0;
1359 int arrayComponents = result->getType().getElementSize();
Nicolas Capens0bac2852016-05-07 06:09:58 -04001360 for(size_t i = 0; i < argumentCount; i++)
1361 {
1362 TIntermTyped *argi = arg[i]->getAsTyped();
1363 int size = argi->getNominalSize();
Alexis Hetu2a198552016-09-27 20:50:45 -04001364 int arrayIndex = std::min(component / arrayComponents, arrayMaxIndex);
1365 int swizzle = component - (arrayIndex * arrayComponents);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001366
1367 if(!argi->isMatrix())
1368 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001369 Instruction *mov = emitCast(result, arrayIndex, argi, 0);
1370 mov->dst.mask = (0xF << swizzle) & 0xF;
1371 mov->src[0].swizzle = readSwizzle(argi, size) << (swizzle * 2);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001372
1373 component += size;
1374 }
1375 else // Matrix
1376 {
1377 int column = 0;
1378
1379 while(component < resultType.getNominalSize())
1380 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001381 Instruction *mov = emitCast(result, arrayIndex, argi, column);
1382 mov->dst.mask = (0xF << swizzle) & 0xF;
1383 mov->src[0].swizzle = readSwizzle(argi, size) << (swizzle * 2);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001384
1385 column++;
1386 component += size;
1387 }
1388 }
1389 }
1390 }
1391 break;
1392 case EOpConstructMat2:
1393 case EOpConstructMat2x3:
1394 case EOpConstructMat2x4:
1395 case EOpConstructMat3x2:
1396 case EOpConstructMat3:
1397 case EOpConstructMat3x4:
1398 case EOpConstructMat4x2:
1399 case EOpConstructMat4x3:
1400 case EOpConstructMat4:
1401 if(visit == PostVisit)
1402 {
1403 TIntermTyped *arg0 = arg[0]->getAsTyped();
1404 const int outCols = result->getNominalSize();
1405 const int outRows = result->getSecondarySize();
1406
1407 if(arg0->isScalar() && arg.size() == 1) // Construct scale matrix
1408 {
1409 for(int i = 0; i < outCols; i++)
1410 {
Alexis Hetu7208e932016-06-02 11:19:24 -04001411 emit(sw::Shader::OPCODE_MOV, result, i, &zero);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001412 Instruction *mov = emitCast(result, i, arg0, 0);
1413 mov->dst.mask = 1 << i;
1414 ASSERT(mov->src[0].swizzle == 0x00);
1415 }
1416 }
1417 else if(arg0->isMatrix())
1418 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001419 int arraySize = result->isArray() ? result->getArraySize() : 1;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001420
Alexis Hetu2a198552016-09-27 20:50:45 -04001421 for(int n = 0; n < arraySize; n++)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001422 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001423 TIntermTyped *argi = arg[n]->getAsTyped();
1424 const int inCols = argi->getNominalSize();
1425 const int inRows = argi->getSecondarySize();
Nicolas Capens0bac2852016-05-07 06:09:58 -04001426
Alexis Hetu2a198552016-09-27 20:50:45 -04001427 for(int i = 0; i < outCols; i++)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001428 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001429 if(i >= inCols || outRows > inRows)
1430 {
1431 // Initialize to identity matrix
1432 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));
1433 emitCast(result, i + n * outCols, &col, 0);
1434 }
1435
1436 if(i < inCols)
1437 {
1438 Instruction *mov = emitCast(result, i + n * outCols, argi, i);
1439 mov->dst.mask = 0xF >> (4 - inRows);
1440 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001441 }
1442 }
1443 }
1444 else
1445 {
1446 int column = 0;
1447 int row = 0;
1448
1449 for(size_t i = 0; i < argumentCount; i++)
1450 {
1451 TIntermTyped *argi = arg[i]->getAsTyped();
1452 int size = argi->getNominalSize();
1453 int element = 0;
1454
1455 while(element < size)
1456 {
1457 Instruction *mov = emitCast(result, column, argi, 0);
1458 mov->dst.mask = (0xF << row) & 0xF;
1459 mov->src[0].swizzle = (readSwizzle(argi, size) << (row * 2)) + 0x55 * element;
1460
1461 int end = row + size - element;
1462 column = end >= outRows ? column + 1 : column;
1463 element = element + outRows - row;
1464 row = end >= outRows ? 0 : end;
1465 }
1466 }
1467 }
1468 }
1469 break;
1470 case EOpConstructStruct:
1471 if(visit == PostVisit)
1472 {
1473 int offset = 0;
1474 for(size_t i = 0; i < argumentCount; i++)
1475 {
1476 TIntermTyped *argi = arg[i]->getAsTyped();
1477 int size = argi->totalRegisterCount();
1478
1479 for(int index = 0; index < size; index++)
1480 {
1481 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index + offset, argi, index);
1482 mov->dst.mask = writeMask(result, offset + index);
1483 }
1484
1485 offset += size;
1486 }
1487 }
1488 break;
1489 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, arg[0], arg[1]); break;
1490 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, arg[0], arg[1]); break;
1491 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, arg[0], arg[1]); break;
1492 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, arg[0], arg[1]); break;
1493 case EOpVectorEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_EQ, result, arg[0], arg[1]); break;
1494 case EOpVectorNotEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_NE, result, arg[0], arg[1]); break;
1495 case EOpMod: if(visit == PostVisit) emit(sw::Shader::OPCODE_MOD, result, arg[0], arg[1]); break;
1496 case EOpModf:
1497 if(visit == PostVisit)
1498 {
1499 TIntermTyped* arg1 = arg[1]->getAsTyped();
1500 emit(sw::Shader::OPCODE_TRUNC, arg1, arg[0]);
1501 assignLvalue(arg1, arg1);
1502 emitBinary(sw::Shader::OPCODE_SUB, result, arg[0], arg1);
1503 }
1504 break;
1505 case EOpPow: if(visit == PostVisit) emit(sw::Shader::OPCODE_POW, result, arg[0], arg[1]); break;
1506 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN2, result, arg[0], arg[1]); break;
1507 case EOpMin: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, arg[0], arg[1]); break;
1508 case EOpMax: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]); break;
1509 case EOpClamp:
1510 if(visit == PostVisit)
1511 {
1512 emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]);
1513 emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, result, arg[2]);
1514 }
1515 break;
1516 case EOpMix: if(visit == PostVisit) emit(sw::Shader::OPCODE_LRP, result, arg[2], arg[1], arg[0]); break;
1517 case EOpStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_STEP, result, arg[0], arg[1]); break;
1518 case EOpSmoothStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_SMOOTH, result, arg[0], arg[1], arg[2]); break;
1519 case EOpDistance: if(visit == PostVisit) emit(sw::Shader::OPCODE_DIST(dim(arg[0])), result, arg[0], arg[1]); break;
1520 case EOpDot: if(visit == PostVisit) emit(sw::Shader::OPCODE_DP(dim(arg[0])), result, arg[0], arg[1]); break;
1521 case EOpCross: if(visit == PostVisit) emit(sw::Shader::OPCODE_CRS, result, arg[0], arg[1]); break;
1522 case EOpFaceForward: if(visit == PostVisit) emit(sw::Shader::OPCODE_FORWARD(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1523 case EOpReflect: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFLECT(dim(arg[0])), result, arg[0], arg[1]); break;
1524 case EOpRefract: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFRACT(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1525 case EOpMul:
1526 if(visit == PostVisit)
1527 {
1528 TIntermTyped *arg0 = arg[0]->getAsTyped();
Alexis Hetue97a31e2016-11-14 14:10:47 -05001529 ASSERT((arg0->getNominalSize() == arg[1]->getAsTyped()->getNominalSize()) &&
1530 (arg0->getSecondarySize() == arg[1]->getAsTyped()->getSecondarySize()));
Nicolas Capens0bac2852016-05-07 06:09:58 -04001531
1532 int size = arg0->getNominalSize();
1533 for(int i = 0; i < size; i++)
1534 {
1535 emit(sw::Shader::OPCODE_MUL, result, i, arg[0], i, arg[1], i);
1536 }
1537 }
1538 break;
1539 case EOpOuterProduct:
1540 if(visit == PostVisit)
1541 {
1542 for(int i = 0; i < dim(arg[1]); i++)
1543 {
1544 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, arg[0], 0, arg[1]);
1545 mul->src[1].swizzle = 0x55 * i;
1546 }
1547 }
1548 break;
1549 default: UNREACHABLE(node->getOp());
1550 }
1551
1552 return true;
1553 }
1554
1555 bool OutputASM::visitSelection(Visit visit, TIntermSelection *node)
1556 {
1557 if(currentScope != emitScope)
1558 {
1559 return false;
1560 }
1561
1562 TIntermTyped *condition = node->getCondition();
1563 TIntermNode *trueBlock = node->getTrueBlock();
1564 TIntermNode *falseBlock = node->getFalseBlock();
1565 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
1566
1567 condition->traverse(this);
1568
1569 if(node->usesTernaryOperator())
1570 {
1571 if(constantCondition)
1572 {
1573 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1574
1575 if(trueCondition)
1576 {
1577 trueBlock->traverse(this);
1578 copy(node, trueBlock);
1579 }
1580 else
1581 {
1582 falseBlock->traverse(this);
1583 copy(node, falseBlock);
1584 }
1585 }
1586 else if(trivial(node, 6)) // Fast to compute both potential results and no side effects
1587 {
1588 trueBlock->traverse(this);
1589 falseBlock->traverse(this);
1590 emit(sw::Shader::OPCODE_SELECT, node, condition, trueBlock, falseBlock);
1591 }
1592 else
1593 {
1594 emit(sw::Shader::OPCODE_IF, 0, condition);
1595
1596 if(trueBlock)
1597 {
1598 trueBlock->traverse(this);
1599 copy(node, trueBlock);
1600 }
1601
1602 if(falseBlock)
1603 {
1604 emit(sw::Shader::OPCODE_ELSE);
1605 falseBlock->traverse(this);
1606 copy(node, falseBlock);
1607 }
1608
1609 emit(sw::Shader::OPCODE_ENDIF);
1610 }
1611 }
1612 else // if/else statement
1613 {
1614 if(constantCondition)
1615 {
1616 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1617
1618 if(trueCondition)
1619 {
1620 if(trueBlock)
1621 {
1622 trueBlock->traverse(this);
1623 }
1624 }
1625 else
1626 {
1627 if(falseBlock)
1628 {
1629 falseBlock->traverse(this);
1630 }
1631 }
1632 }
1633 else
1634 {
1635 emit(sw::Shader::OPCODE_IF, 0, condition);
1636
1637 if(trueBlock)
1638 {
1639 trueBlock->traverse(this);
1640 }
1641
1642 if(falseBlock)
1643 {
1644 emit(sw::Shader::OPCODE_ELSE);
1645 falseBlock->traverse(this);
1646 }
1647
1648 emit(sw::Shader::OPCODE_ENDIF);
1649 }
1650 }
1651
1652 return false;
1653 }
1654
1655 bool OutputASM::visitLoop(Visit visit, TIntermLoop *node)
1656 {
1657 if(currentScope != emitScope)
1658 {
1659 return false;
1660 }
1661
1662 unsigned int iterations = loopCount(node);
1663
1664 if(iterations == 0)
1665 {
1666 return false;
1667 }
1668
1669 bool unroll = (iterations <= 4);
1670
1671 if(unroll)
1672 {
1673 LoopUnrollable loopUnrollable;
1674 unroll = loopUnrollable.traverse(node);
1675 }
1676
1677 TIntermNode *init = node->getInit();
1678 TIntermTyped *condition = node->getCondition();
1679 TIntermTyped *expression = node->getExpression();
1680 TIntermNode *body = node->getBody();
1681 Constant True(true);
1682
1683 if(node->getType() == ELoopDoWhile)
1684 {
1685 Temporary iterate(this);
1686 emit(sw::Shader::OPCODE_MOV, &iterate, &True);
1687
1688 emit(sw::Shader::OPCODE_WHILE, 0, &iterate); // FIXME: Implement real do-while
1689
1690 if(body)
1691 {
1692 body->traverse(this);
1693 }
1694
1695 emit(sw::Shader::OPCODE_TEST);
1696
1697 condition->traverse(this);
1698 emit(sw::Shader::OPCODE_MOV, &iterate, condition);
1699
1700 emit(sw::Shader::OPCODE_ENDWHILE);
1701 }
1702 else
1703 {
1704 if(init)
1705 {
1706 init->traverse(this);
1707 }
1708
1709 if(unroll)
1710 {
1711 for(unsigned int i = 0; i < iterations; i++)
1712 {
1713 // condition->traverse(this); // Condition could contain statements, but not in an unrollable loop
1714
1715 if(body)
1716 {
1717 body->traverse(this);
1718 }
1719
1720 if(expression)
1721 {
1722 expression->traverse(this);
1723 }
1724 }
1725 }
1726 else
1727 {
1728 if(condition)
1729 {
1730 condition->traverse(this);
1731 }
1732 else
1733 {
1734 condition = &True;
1735 }
1736
1737 emit(sw::Shader::OPCODE_WHILE, 0, condition);
1738
1739 if(body)
1740 {
1741 body->traverse(this);
1742 }
1743
1744 emit(sw::Shader::OPCODE_TEST);
1745
1746 if(expression)
1747 {
1748 expression->traverse(this);
1749 }
1750
1751 if(condition)
1752 {
1753 condition->traverse(this);
1754 }
1755
1756 emit(sw::Shader::OPCODE_ENDWHILE);
1757 }
1758 }
1759
1760 return false;
1761 }
1762
1763 bool OutputASM::visitBranch(Visit visit, TIntermBranch *node)
1764 {
1765 if(currentScope != emitScope)
1766 {
1767 return false;
1768 }
1769
1770 switch(node->getFlowOp())
1771 {
1772 case EOpKill: if(visit == PostVisit) emit(sw::Shader::OPCODE_DISCARD); break;
1773 case EOpBreak: if(visit == PostVisit) emit(sw::Shader::OPCODE_BREAK); break;
1774 case EOpContinue: if(visit == PostVisit) emit(sw::Shader::OPCODE_CONTINUE); break;
1775 case EOpReturn:
1776 if(visit == PostVisit)
1777 {
1778 TIntermTyped *value = node->getExpression();
1779
1780 if(value)
1781 {
1782 copy(functionArray[currentFunction].ret, value);
1783 }
1784
1785 emit(sw::Shader::OPCODE_LEAVE);
1786 }
1787 break;
1788 default: UNREACHABLE(node->getFlowOp());
1789 }
1790
1791 return true;
1792 }
1793
Alexis Hetu9aa83a92016-05-02 17:34:46 -04001794 bool OutputASM::visitSwitch(Visit visit, TIntermSwitch *node)
1795 {
1796 if(currentScope != emitScope)
1797 {
1798 return false;
1799 }
1800
1801 TIntermTyped* switchValue = node->getInit();
1802 TIntermAggregate* opList = node->getStatementList();
1803
1804 if(!switchValue || !opList)
1805 {
1806 return false;
1807 }
1808
1809 switchValue->traverse(this);
1810
1811 emit(sw::Shader::OPCODE_SWITCH);
1812
1813 TIntermSequence& sequence = opList->getSequence();
1814 TIntermSequence::iterator it = sequence.begin();
1815 TIntermSequence::iterator defaultIt = sequence.end();
1816 int nbCases = 0;
1817 for(; it != sequence.end(); ++it)
1818 {
1819 TIntermCase* currentCase = (*it)->getAsCaseNode();
1820 if(currentCase)
1821 {
1822 TIntermSequence::iterator caseIt = it;
1823
1824 TIntermTyped* condition = currentCase->getCondition();
1825 if(condition) // non default case
1826 {
1827 if(nbCases != 0)
1828 {
1829 emit(sw::Shader::OPCODE_ELSE);
1830 }
1831
1832 condition->traverse(this);
1833 Temporary result(this);
1834 emitBinary(sw::Shader::OPCODE_EQ, &result, switchValue, condition);
1835 emit(sw::Shader::OPCODE_IF, 0, &result);
1836 nbCases++;
1837
1838 for(++caseIt; caseIt != sequence.end(); ++caseIt)
1839 {
1840 (*caseIt)->traverse(this);
1841 if((*caseIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1842 {
1843 break;
1844 }
1845 }
1846 }
1847 else
1848 {
1849 defaultIt = it; // The default case might not be the last case, keep it for last
1850 }
1851 }
1852 }
1853
1854 // If there's a default case, traverse it here
1855 if(defaultIt != sequence.end())
1856 {
1857 emit(sw::Shader::OPCODE_ELSE);
1858 for(++defaultIt; defaultIt != sequence.end(); ++defaultIt)
1859 {
1860 (*defaultIt)->traverse(this);
1861 if((*defaultIt)->getAsBranchNode()) // Kill, Break, Continue or Return
1862 {
1863 break;
1864 }
1865 }
1866 }
1867
1868 for(int i = 0; i < nbCases; ++i)
1869 {
1870 emit(sw::Shader::OPCODE_ENDIF);
1871 }
1872
1873 emit(sw::Shader::OPCODE_ENDSWITCH);
1874
1875 return false;
1876 }
1877
Nicolas Capens0bac2852016-05-07 06:09:58 -04001878 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2, TIntermNode *src3, TIntermNode *src4)
1879 {
1880 return emit(op, dst, 0, src0, 0, src1, 0, src2, 0, src3, 0, src4, 0);
1881 }
1882
1883 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, int dstIndex, TIntermNode *src0, int index0, TIntermNode *src1, int index1,
1884 TIntermNode *src2, int index2, TIntermNode *src3, int index3, TIntermNode *src4, int index4)
1885 {
1886 Instruction *instruction = new Instruction(op);
1887
1888 if(dst)
1889 {
Nicolas Capens0530b452017-11-15 16:39:47 -05001890 destination(instruction->dst, dst, dstIndex);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001891 }
1892
Alexis Hetu929c6b02017-11-07 16:04:25 -05001893 if(src0)
1894 {
1895 TIntermTyped* src = src0->getAsTyped();
1896 instruction->dst.partialPrecision = src && (src->getPrecision() <= EbpLow);
1897 }
1898
Nicolas Capens0530b452017-11-15 16:39:47 -05001899 source(instruction->src[0], src0, index0);
1900 source(instruction->src[1], src1, index1);
1901 source(instruction->src[2], src2, index2);
1902 source(instruction->src[3], src3, index3);
1903 source(instruction->src[4], src4, index4);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001904
1905 shader->append(instruction);
1906
1907 return instruction;
1908 }
1909
1910 Instruction *OutputASM::emitCast(TIntermTyped *dst, TIntermTyped *src)
1911 {
1912 return emitCast(dst, 0, src, 0);
1913 }
1914
1915 Instruction *OutputASM::emitCast(TIntermTyped *dst, int dstIndex, TIntermTyped *src, int srcIndex)
1916 {
1917 switch(src->getBasicType())
1918 {
1919 case EbtBool:
1920 switch(dst->getBasicType())
1921 {
1922 case EbtInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1923 case EbtUInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
1924 case EbtFloat: return emit(sw::Shader::OPCODE_B2F, dst, dstIndex, src, srcIndex);
1925 default: break;
1926 }
1927 break;
1928 case EbtInt:
1929 switch(dst->getBasicType())
1930 {
1931 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1932 case EbtFloat: return emit(sw::Shader::OPCODE_I2F, dst, dstIndex, src, srcIndex);
1933 default: break;
1934 }
1935 break;
1936 case EbtUInt:
1937 switch(dst->getBasicType())
1938 {
1939 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
1940 case EbtFloat: return emit(sw::Shader::OPCODE_U2F, dst, dstIndex, src, srcIndex);
1941 default: break;
1942 }
1943 break;
1944 case EbtFloat:
1945 switch(dst->getBasicType())
1946 {
1947 case EbtBool: return emit(sw::Shader::OPCODE_F2B, dst, dstIndex, src, srcIndex);
1948 case EbtInt: return emit(sw::Shader::OPCODE_F2I, dst, dstIndex, src, srcIndex);
1949 case EbtUInt: return emit(sw::Shader::OPCODE_F2U, dst, dstIndex, src, srcIndex);
1950 default: break;
1951 }
1952 break;
1953 default:
1954 break;
1955 }
1956
1957 ASSERT((src->getBasicType() == dst->getBasicType()) ||
1958 ((src->getBasicType() == EbtInt) && (dst->getBasicType() == EbtUInt)) ||
1959 ((src->getBasicType() == EbtUInt) && (dst->getBasicType() == EbtInt)));
1960
1961 return emit(sw::Shader::OPCODE_MOV, dst, dstIndex, src, srcIndex);
1962 }
1963
1964 void OutputASM::emitBinary(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2)
1965 {
1966 for(int index = 0; index < dst->elementRegisterCount(); index++)
1967 {
1968 emit(op, dst, index, src0, index, src1, index, src2, index);
1969 }
1970 }
1971
1972 void OutputASM::emitAssign(sw::Shader::Opcode op, TIntermTyped *result, TIntermTyped *lhs, TIntermTyped *src0, TIntermTyped *src1)
1973 {
1974 emitBinary(op, result, src0, src1);
1975 assignLvalue(lhs, result);
1976 }
1977
1978 void OutputASM::emitCmp(sw::Shader::Control cmpOp, TIntermTyped *dst, TIntermNode *left, TIntermNode *right, int index)
1979 {
1980 sw::Shader::Opcode opcode;
1981 switch(left->getAsTyped()->getBasicType())
1982 {
1983 case EbtBool:
1984 case EbtInt:
1985 opcode = sw::Shader::OPCODE_ICMP;
1986 break;
1987 case EbtUInt:
1988 opcode = sw::Shader::OPCODE_UCMP;
1989 break;
1990 default:
1991 opcode = sw::Shader::OPCODE_CMP;
1992 break;
1993 }
1994
1995 Instruction *cmp = emit(opcode, dst, 0, left, index, right, index);
1996 cmp->control = cmpOp;
1997 }
1998
1999 int componentCount(const TType &type, int registers)
2000 {
2001 if(registers == 0)
2002 {
2003 return 0;
2004 }
2005
2006 if(type.isArray() && registers >= type.elementRegisterCount())
2007 {
2008 int index = registers / type.elementRegisterCount();
2009 registers -= index * type.elementRegisterCount();
2010 return index * type.getElementSize() + componentCount(type, registers);
2011 }
2012
2013 if(type.isStruct() || type.isInterfaceBlock())
2014 {
2015 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2016 int elements = 0;
2017
2018 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2019 {
2020 const TType &fieldType = *((*field)->type());
2021
2022 if(fieldType.totalRegisterCount() <= registers)
2023 {
2024 registers -= fieldType.totalRegisterCount();
2025 elements += fieldType.getObjectSize();
2026 }
2027 else // Register within this field
2028 {
2029 return elements + componentCount(fieldType, registers);
2030 }
2031 }
2032 }
2033 else if(type.isMatrix())
2034 {
2035 return registers * type.registerSize();
2036 }
2037
2038 UNREACHABLE(0);
2039 return 0;
2040 }
2041
2042 int registerSize(const TType &type, int registers)
2043 {
2044 if(registers == 0)
2045 {
2046 if(type.isStruct())
2047 {
2048 return registerSize(*((*(type.getStruct()->fields().begin()))->type()), 0);
2049 }
2050 else if(type.isInterfaceBlock())
2051 {
2052 return registerSize(*((*(type.getInterfaceBlock()->fields().begin()))->type()), 0);
2053 }
2054
2055 return type.registerSize();
2056 }
2057
2058 if(type.isArray() && registers >= type.elementRegisterCount())
2059 {
2060 int index = registers / type.elementRegisterCount();
2061 registers -= index * type.elementRegisterCount();
2062 return registerSize(type, registers);
2063 }
2064
2065 if(type.isStruct() || type.isInterfaceBlock())
2066 {
2067 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2068 int elements = 0;
2069
2070 for(TFieldList::const_iterator field = fields.begin(); field != fields.end(); field++)
2071 {
2072 const TType &fieldType = *((*field)->type());
2073
2074 if(fieldType.totalRegisterCount() <= registers)
2075 {
2076 registers -= fieldType.totalRegisterCount();
2077 elements += fieldType.getObjectSize();
2078 }
2079 else // Register within this field
2080 {
2081 return registerSize(fieldType, registers);
2082 }
2083 }
2084 }
2085 else if(type.isMatrix())
2086 {
2087 return registerSize(type, 0);
2088 }
2089
2090 UNREACHABLE(0);
2091 return 0;
2092 }
2093
2094 int OutputASM::getBlockId(TIntermTyped *arg)
2095 {
2096 if(arg)
2097 {
2098 const TType &type = arg->getType();
2099 TInterfaceBlock* block = type.getInterfaceBlock();
2100 if(block && (type.getQualifier() == EvqUniform))
2101 {
2102 // Make sure the uniform block is declared
2103 uniformRegister(arg);
2104
2105 const char* blockName = block->name().c_str();
2106
2107 // Fetch uniform block index from array of blocks
2108 for(ActiveUniformBlocks::const_iterator it = shaderObject->activeUniformBlocks.begin(); it != shaderObject->activeUniformBlocks.end(); ++it)
2109 {
2110 if(blockName == it->name)
2111 {
2112 return it->blockId;
2113 }
2114 }
2115
2116 ASSERT(false);
2117 }
2118 }
2119
2120 return -1;
2121 }
2122
2123 OutputASM::ArgumentInfo OutputASM::getArgumentInfo(TIntermTyped *arg, int index)
2124 {
2125 const TType &type = arg->getType();
2126 int blockId = getBlockId(arg);
2127 ArgumentInfo argumentInfo(BlockMemberInfo::getDefaultBlockInfo(), type, -1, -1);
2128 if(blockId != -1)
2129 {
2130 argumentInfo.bufferIndex = 0;
2131 for(int i = 0; i < blockId; ++i)
2132 {
2133 int blockArraySize = shaderObject->activeUniformBlocks[i].arraySize;
2134 argumentInfo.bufferIndex += blockArraySize > 0 ? blockArraySize : 1;
2135 }
2136
2137 const BlockDefinitionIndexMap& blockDefinition = blockDefinitions[blockId];
2138
2139 BlockDefinitionIndexMap::const_iterator itEnd = blockDefinition.end();
2140 BlockDefinitionIndexMap::const_iterator it = itEnd;
2141
2142 argumentInfo.clampedIndex = index;
2143 if(type.isInterfaceBlock())
2144 {
2145 // Offset index to the beginning of the selected instance
2146 int blockRegisters = type.elementRegisterCount();
2147 int bufferOffset = argumentInfo.clampedIndex / blockRegisters;
2148 argumentInfo.bufferIndex += bufferOffset;
2149 argumentInfo.clampedIndex -= bufferOffset * blockRegisters;
2150 }
2151
2152 int regIndex = registerIndex(arg);
2153 for(int i = regIndex + argumentInfo.clampedIndex; i >= regIndex; --i)
2154 {
2155 it = blockDefinition.find(i);
2156 if(it != itEnd)
2157 {
2158 argumentInfo.clampedIndex -= (i - regIndex);
2159 break;
2160 }
2161 }
2162 ASSERT(it != itEnd);
2163
2164 argumentInfo.typedMemberInfo = it->second;
2165
2166 int registerCount = argumentInfo.typedMemberInfo.type.totalRegisterCount();
2167 argumentInfo.clampedIndex = (argumentInfo.clampedIndex >= registerCount) ? registerCount - 1 : argumentInfo.clampedIndex;
2168 }
2169 else
2170 {
2171 argumentInfo.clampedIndex = (index >= arg->totalRegisterCount()) ? arg->totalRegisterCount() - 1 : index;
2172 }
2173
2174 return argumentInfo;
2175 }
2176
Nicolas Capens0530b452017-11-15 16:39:47 -05002177 void OutputASM::source(sw::Shader::SourceParameter &parameter, TIntermNode *argument, int index)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002178 {
2179 if(argument)
2180 {
2181 TIntermTyped *arg = argument->getAsTyped();
2182 Temporary unpackedUniform(this);
2183
2184 const TType& srcType = arg->getType();
2185 TInterfaceBlock* srcBlock = srcType.getInterfaceBlock();
2186 if(srcBlock && (srcType.getQualifier() == EvqUniform))
2187 {
2188 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2189 const TType &memberType = argumentInfo.typedMemberInfo.type;
2190
2191 if(memberType.getBasicType() == EbtBool)
2192 {
Alexis Hetue97a31e2016-11-14 14:10:47 -05002193 ASSERT(argumentInfo.clampedIndex < (memberType.isArray() ? memberType.getArraySize() : 1)); // index < arraySize
Nicolas Capens0bac2852016-05-07 06:09:58 -04002194
2195 // Convert the packed bool, which is currently an int, to a true bool
2196 Instruction *instruction = new Instruction(sw::Shader::OPCODE_I2B);
2197 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2198 instruction->dst.index = registerIndex(&unpackedUniform);
2199 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2200 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2201 instruction->src[0].index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * argumentInfo.typedMemberInfo.arrayStride;
2202
2203 shader->append(instruction);
2204
2205 arg = &unpackedUniform;
2206 index = 0;
2207 }
2208 else if((srcBlock->matrixPacking() == EmpRowMajor) && memberType.isMatrix())
2209 {
2210 int numCols = memberType.getNominalSize();
2211 int numRows = memberType.getSecondarySize();
Nicolas Capens0bac2852016-05-07 06:09:58 -04002212
Alexis Hetue97a31e2016-11-14 14:10:47 -05002213 ASSERT(argumentInfo.clampedIndex < (numCols * (memberType.isArray() ? memberType.getArraySize() : 1))); // index < cols * arraySize
Nicolas Capens0bac2852016-05-07 06:09:58 -04002214
2215 unsigned int dstIndex = registerIndex(&unpackedUniform);
2216 unsigned int srcSwizzle = (argumentInfo.clampedIndex % numCols) * 0x55;
2217 int arrayIndex = argumentInfo.clampedIndex / numCols;
2218 int matrixStartOffset = argumentInfo.typedMemberInfo.offset + arrayIndex * argumentInfo.typedMemberInfo.arrayStride;
2219
2220 for(int j = 0; j < numRows; ++j)
2221 {
2222 // Transpose the row major matrix
2223 Instruction *instruction = new Instruction(sw::Shader::OPCODE_MOV);
2224 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2225 instruction->dst.index = dstIndex;
2226 instruction->dst.mask = 1 << j;
2227 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2228 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2229 instruction->src[0].index = matrixStartOffset + j * argumentInfo.typedMemberInfo.matrixStride;
2230 instruction->src[0].swizzle = srcSwizzle;
2231
2232 shader->append(instruction);
2233 }
2234
2235 arg = &unpackedUniform;
2236 index = 0;
2237 }
2238 }
2239
2240 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2241 const TType &type = argumentInfo.typedMemberInfo.type;
2242
2243 int size = registerSize(type, argumentInfo.clampedIndex);
2244
2245 parameter.type = registerType(arg);
2246 parameter.bufferIndex = argumentInfo.bufferIndex;
2247
2248 if(arg->getAsConstantUnion() && arg->getAsConstantUnion()->getUnionArrayPointer())
2249 {
2250 int component = componentCount(type, argumentInfo.clampedIndex);
2251 ConstantUnion *constants = arg->getAsConstantUnion()->getUnionArrayPointer();
2252
2253 for(int i = 0; i < 4; i++)
2254 {
2255 if(size == 1) // Replicate
2256 {
2257 parameter.value[i] = constants[component + 0].getAsFloat();
2258 }
2259 else if(i < size)
2260 {
2261 parameter.value[i] = constants[component + i].getAsFloat();
2262 }
2263 else
2264 {
2265 parameter.value[i] = 0.0f;
2266 }
2267 }
2268 }
2269 else
2270 {
2271 parameter.index = registerIndex(arg) + argumentInfo.clampedIndex;
2272
2273 if(parameter.bufferIndex != -1)
2274 {
2275 int stride = (argumentInfo.typedMemberInfo.matrixStride > 0) ? argumentInfo.typedMemberInfo.matrixStride : argumentInfo.typedMemberInfo.arrayStride;
2276 parameter.index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * stride;
2277 }
2278 }
2279
2280 if(!IsSampler(arg->getBasicType()))
2281 {
2282 parameter.swizzle = readSwizzle(arg, size);
2283 }
2284 }
2285 }
2286
Nicolas Capens0530b452017-11-15 16:39:47 -05002287 void OutputASM::destination(sw::Shader::DestinationParameter &parameter, TIntermTyped *arg, int index)
2288 {
2289 parameter.type = registerType(arg);
2290 parameter.index = registerIndex(arg) + index;
2291 parameter.mask = writeMask(arg);
2292 }
2293
Nicolas Capens0bac2852016-05-07 06:09:58 -04002294 void OutputASM::copy(TIntermTyped *dst, TIntermNode *src, int offset)
2295 {
2296 for(int index = 0; index < dst->totalRegisterCount(); index++)
2297 {
2298 Instruction *mov = emit(sw::Shader::OPCODE_MOV, dst, index, src, offset + index);
2299 mov->dst.mask = writeMask(dst, index);
2300 }
2301 }
2302
2303 int swizzleElement(int swizzle, int index)
2304 {
2305 return (swizzle >> (index * 2)) & 0x03;
2306 }
2307
2308 int swizzleSwizzle(int leftSwizzle, int rightSwizzle)
2309 {
2310 return (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 0)) << 0) |
2311 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 1)) << 2) |
2312 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 2)) << 4) |
2313 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 3)) << 6);
2314 }
2315
2316 void OutputASM::assignLvalue(TIntermTyped *dst, TIntermTyped *src)
2317 {
Nicolas Capens84249fd2017-11-09 11:20:51 -05002318 if((src->isVector() && (!dst->isVector() || (src->getNominalSize() != dst->getNominalSize()))) ||
2319 (src->isMatrix() && (!dst->isMatrix() || (src->getNominalSize() != dst->getNominalSize()) || (src->getSecondarySize() != dst->getSecondarySize()))))
Nicolas Capens0bac2852016-05-07 06:09:58 -04002320 {
2321 return mContext.error(src->getLine(), "Result type should match the l-value type in compound assignment", src->isVector() ? "vector" : "matrix");
2322 }
2323
2324 TIntermBinary *binary = dst->getAsBinaryNode();
2325
2326 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && dst->isScalar())
2327 {
2328 Instruction *insert = new Instruction(sw::Shader::OPCODE_INSERT);
2329
2330 Temporary address(this);
2331 lvalue(insert->dst, address, dst);
2332
2333 insert->src[0].type = insert->dst.type;
2334 insert->src[0].index = insert->dst.index;
2335 insert->src[0].rel = insert->dst.rel;
Nicolas Capens0530b452017-11-15 16:39:47 -05002336 source(insert->src[1], src);
2337 source(insert->src[2], binary->getRight());
Nicolas Capens0bac2852016-05-07 06:09:58 -04002338
2339 shader->append(insert);
2340 }
2341 else
2342 {
Nicolas Capens84249fd2017-11-09 11:20:51 -05002343 Instruction *mov1 = new Instruction(sw::Shader::OPCODE_MOV);
2344
2345 Temporary address(this);
2346 int swizzle = lvalue(mov1->dst, address, dst);
2347
Nicolas Capens0530b452017-11-15 16:39:47 -05002348 source(mov1->src[0], src);
Nicolas Capens84249fd2017-11-09 11:20:51 -05002349 mov1->src[0].swizzle = swizzleSwizzle(mov1->src[0].swizzle, swizzle);
2350
2351 shader->append(mov1);
2352
2353 for(int offset = 1; offset < dst->totalRegisterCount(); offset++)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002354 {
2355 Instruction *mov = new Instruction(sw::Shader::OPCODE_MOV);
2356
Nicolas Capens84249fd2017-11-09 11:20:51 -05002357 mov->dst = mov1->dst;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002358 mov->dst.index += offset;
Nicolas Capens84249fd2017-11-09 11:20:51 -05002359 mov->dst.mask = writeMask(dst, offset);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002360
Nicolas Capens0530b452017-11-15 16:39:47 -05002361 source(mov->src[0], src, offset);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002362
2363 shader->append(mov);
2364 }
2365 }
2366 }
2367
2368 int OutputASM::lvalue(sw::Shader::DestinationParameter &dst, Temporary &address, TIntermTyped *node)
2369 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002370 TIntermTyped *root = nullptr;
2371 unsigned int offset = 0;
2372 unsigned char mask = 0xF;
2373 int swizzle = lvalue(root, offset, dst.rel, mask, address, node);
2374
2375 dst.type = registerType(root);
2376 dst.index = registerIndex(root) + offset;
2377 dst.mask = mask;
2378
2379 return swizzle;
2380 }
2381
2382 int OutputASM::lvalue(TIntermTyped *&root, unsigned int &offset, sw::Shader::Relative &rel, unsigned char &mask, Temporary &address, TIntermTyped *node)
2383 {
Nicolas Capens0bac2852016-05-07 06:09:58 -04002384 TIntermTyped *result = node;
2385 TIntermBinary *binary = node->getAsBinaryNode();
2386 TIntermSymbol *symbol = node->getAsSymbolNode();
2387
2388 if(binary)
2389 {
2390 TIntermTyped *left = binary->getLeft();
2391 TIntermTyped *right = binary->getRight();
2392
Nicolas Capens0530b452017-11-15 16:39:47 -05002393 int leftSwizzle = lvalue(root, offset, rel, mask, address, left); // Resolve the l-value of the left side
Nicolas Capens0bac2852016-05-07 06:09:58 -04002394
2395 switch(binary->getOp())
2396 {
2397 case EOpIndexDirect:
2398 {
2399 int rightIndex = right->getAsConstantUnion()->getIConst(0);
2400
2401 if(left->isRegister())
2402 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002403 int leftMask = mask;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002404
Nicolas Capens0530b452017-11-15 16:39:47 -05002405 mask = 1;
2406 while((leftMask & mask) == 0)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002407 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002408 mask = mask << 1;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002409 }
2410
2411 int element = swizzleElement(leftSwizzle, rightIndex);
Nicolas Capens0530b452017-11-15 16:39:47 -05002412 mask = 1 << element;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002413
2414 return element;
2415 }
2416 else if(left->isArray() || left->isMatrix())
2417 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002418 offset += rightIndex * result->totalRegisterCount();
Nicolas Capens0bac2852016-05-07 06:09:58 -04002419 return 0xE4;
2420 }
2421 else UNREACHABLE(0);
2422 }
2423 break;
2424 case EOpIndexIndirect:
2425 {
Nicolas Capens84249fd2017-11-09 11:20:51 -05002426 right->traverse(this);
2427
Nicolas Capens0bac2852016-05-07 06:09:58 -04002428 if(left->isRegister())
2429 {
2430 // Requires INSERT instruction (handled by calling function)
2431 }
2432 else if(left->isArray() || left->isMatrix())
2433 {
2434 int scale = result->totalRegisterCount();
2435
Nicolas Capens0530b452017-11-15 16:39:47 -05002436 if(rel.type == sw::Shader::PARAMETER_VOID) // Use the index register as the relative address directly
Nicolas Capens0bac2852016-05-07 06:09:58 -04002437 {
2438 if(left->totalRegisterCount() > 1)
2439 {
2440 sw::Shader::SourceParameter relativeRegister;
Nicolas Capens0530b452017-11-15 16:39:47 -05002441 source(relativeRegister, right);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002442
Nicolas Capens0530b452017-11-15 16:39:47 -05002443 rel.index = relativeRegister.index;
2444 rel.type = relativeRegister.type;
2445 rel.scale = scale;
2446 rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002447 }
2448 }
Nicolas Capens0530b452017-11-15 16:39:47 -05002449 else if(rel.index != registerIndex(&address)) // Move the previous index register to the address register
Nicolas Capens0bac2852016-05-07 06:09:58 -04002450 {
2451 if(scale == 1)
2452 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002453 Constant oldScale((int)rel.scale);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002454 Instruction *mad = emit(sw::Shader::OPCODE_IMAD, &address, &address, &oldScale, right);
Nicolas Capens0530b452017-11-15 16:39:47 -05002455 mad->src[0].index = rel.index;
2456 mad->src[0].type = rel.type;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002457 }
2458 else
2459 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002460 Constant oldScale((int)rel.scale);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002461 Instruction *mul = emit(sw::Shader::OPCODE_IMUL, &address, &address, &oldScale);
Nicolas Capens0530b452017-11-15 16:39:47 -05002462 mul->src[0].index = rel.index;
2463 mul->src[0].type = rel.type;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002464
2465 Constant newScale(scale);
2466 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2467 }
2468
Nicolas Capens0530b452017-11-15 16:39:47 -05002469 rel.type = sw::Shader::PARAMETER_TEMP;
2470 rel.index = registerIndex(&address);
2471 rel.scale = 1;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002472 }
2473 else // Just add the new index to the address register
2474 {
2475 if(scale == 1)
2476 {
2477 emit(sw::Shader::OPCODE_IADD, &address, &address, right);
2478 }
2479 else
2480 {
2481 Constant newScale(scale);
2482 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2483 }
2484 }
2485 }
2486 else UNREACHABLE(0);
2487 }
2488 break;
2489 case EOpIndexDirectStruct:
2490 case EOpIndexDirectInterfaceBlock:
2491 {
2492 const TFieldList& fields = (binary->getOp() == EOpIndexDirectStruct) ?
2493 left->getType().getStruct()->fields() :
2494 left->getType().getInterfaceBlock()->fields();
2495 int index = right->getAsConstantUnion()->getIConst(0);
2496 int fieldOffset = 0;
2497
2498 for(int i = 0; i < index; i++)
2499 {
2500 fieldOffset += fields[i]->type()->totalRegisterCount();
2501 }
2502
Nicolas Capens0530b452017-11-15 16:39:47 -05002503 offset += fieldOffset;
2504 mask = writeMask(result);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002505
2506 return 0xE4;
2507 }
2508 break;
2509 case EOpVectorSwizzle:
2510 {
2511 ASSERT(left->isRegister());
2512
Nicolas Capens0530b452017-11-15 16:39:47 -05002513 int leftMask = mask;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002514
2515 int swizzle = 0;
2516 int rightMask = 0;
2517
2518 TIntermSequence &sequence = right->getAsAggregate()->getSequence();
2519
2520 for(unsigned int i = 0; i < sequence.size(); i++)
2521 {
2522 int index = sequence[i]->getAsConstantUnion()->getIConst(0);
2523
2524 int element = swizzleElement(leftSwizzle, index);
2525 rightMask = rightMask | (1 << element);
2526 swizzle = swizzle | swizzleElement(leftSwizzle, i) << (element * 2);
2527 }
2528
Nicolas Capens0530b452017-11-15 16:39:47 -05002529 mask = leftMask & rightMask;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002530
2531 return swizzle;
2532 }
2533 break;
2534 default:
2535 UNREACHABLE(binary->getOp()); // Not an l-value operator
2536 break;
2537 }
2538 }
2539 else if(symbol)
2540 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002541 root = symbol;
2542 offset = 0;
2543 mask = writeMask(symbol);
2544
2545 return 0xE4;
2546 }
2547 else
2548 {
2549 node->traverse(this);
2550
2551 root = node;
2552 offset = 0;
2553 mask = writeMask(node);
2554
Nicolas Capens0bac2852016-05-07 06:09:58 -04002555 return 0xE4;
2556 }
2557
2558 return 0xE4;
2559 }
2560
2561 sw::Shader::ParameterType OutputASM::registerType(TIntermTyped *operand)
2562 {
2563 if(isSamplerRegister(operand))
2564 {
2565 return sw::Shader::PARAMETER_SAMPLER;
2566 }
2567
2568 const TQualifier qualifier = operand->getQualifier();
Nicolas Capens0530b452017-11-15 16:39:47 -05002569 if((qualifier == EvqFragColor) || (qualifier == EvqFragData))
Nicolas Capens0bac2852016-05-07 06:09:58 -04002570 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002571 if(((qualifier == EvqFragData) && (outputQualifier == EvqFragColor)) ||
2572 ((qualifier == EvqFragColor) && (outputQualifier == EvqFragData)))
Nicolas Capens0bac2852016-05-07 06:09:58 -04002573 {
2574 mContext.error(operand->getLine(), "static assignment to both gl_FragData and gl_FragColor", "");
2575 }
2576 outputQualifier = qualifier;
2577 }
2578
2579 if(qualifier == EvqConstExpr && (!operand->getAsConstantUnion() || !operand->getAsConstantUnion()->getUnionArrayPointer()))
2580 {
2581 return sw::Shader::PARAMETER_TEMP;
2582 }
2583
2584 switch(qualifier)
2585 {
2586 case EvqTemporary: return sw::Shader::PARAMETER_TEMP;
2587 case EvqGlobal: return sw::Shader::PARAMETER_TEMP;
2588 case EvqConstExpr: return sw::Shader::PARAMETER_FLOAT4LITERAL; // All converted to float
2589 case EvqAttribute: return sw::Shader::PARAMETER_INPUT;
2590 case EvqVaryingIn: return sw::Shader::PARAMETER_INPUT;
2591 case EvqVaryingOut: return sw::Shader::PARAMETER_OUTPUT;
2592 case EvqVertexIn: return sw::Shader::PARAMETER_INPUT;
2593 case EvqFragmentOut: return sw::Shader::PARAMETER_COLOROUT;
2594 case EvqVertexOut: return sw::Shader::PARAMETER_OUTPUT;
2595 case EvqFragmentIn: return sw::Shader::PARAMETER_INPUT;
2596 case EvqInvariantVaryingIn: return sw::Shader::PARAMETER_INPUT; // FIXME: Guarantee invariance at the backend
2597 case EvqInvariantVaryingOut: return sw::Shader::PARAMETER_OUTPUT; // FIXME: Guarantee invariance at the backend
2598 case EvqSmooth: return sw::Shader::PARAMETER_OUTPUT;
2599 case EvqFlat: return sw::Shader::PARAMETER_OUTPUT;
2600 case EvqCentroidOut: return sw::Shader::PARAMETER_OUTPUT;
2601 case EvqSmoothIn: return sw::Shader::PARAMETER_INPUT;
2602 case EvqFlatIn: return sw::Shader::PARAMETER_INPUT;
2603 case EvqCentroidIn: return sw::Shader::PARAMETER_INPUT;
2604 case EvqUniform: return sw::Shader::PARAMETER_CONST;
2605 case EvqIn: return sw::Shader::PARAMETER_TEMP;
2606 case EvqOut: return sw::Shader::PARAMETER_TEMP;
2607 case EvqInOut: return sw::Shader::PARAMETER_TEMP;
2608 case EvqConstReadOnly: return sw::Shader::PARAMETER_TEMP;
2609 case EvqPosition: return sw::Shader::PARAMETER_OUTPUT;
2610 case EvqPointSize: return sw::Shader::PARAMETER_OUTPUT;
2611 case EvqInstanceID: return sw::Shader::PARAMETER_MISCTYPE;
Alexis Hetu877ddfc2017-07-25 17:48:00 -04002612 case EvqVertexID: return sw::Shader::PARAMETER_MISCTYPE;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002613 case EvqFragCoord: return sw::Shader::PARAMETER_MISCTYPE;
2614 case EvqFrontFacing: return sw::Shader::PARAMETER_MISCTYPE;
2615 case EvqPointCoord: return sw::Shader::PARAMETER_INPUT;
2616 case EvqFragColor: return sw::Shader::PARAMETER_COLOROUT;
2617 case EvqFragData: return sw::Shader::PARAMETER_COLOROUT;
2618 case EvqFragDepth: return sw::Shader::PARAMETER_DEPTHOUT;
2619 default: UNREACHABLE(qualifier);
2620 }
2621
2622 return sw::Shader::PARAMETER_VOID;
2623 }
2624
Alexis Hetu12b00502016-05-20 13:01:11 -04002625 bool OutputASM::hasFlatQualifier(TIntermTyped *operand)
2626 {
2627 const TQualifier qualifier = operand->getQualifier();
2628 return qualifier == EvqFlat || qualifier == EvqFlatOut || qualifier == EvqFlatIn;
2629 }
2630
Nicolas Capens0bac2852016-05-07 06:09:58 -04002631 unsigned int OutputASM::registerIndex(TIntermTyped *operand)
2632 {
2633 if(isSamplerRegister(operand))
2634 {
2635 return samplerRegister(operand);
2636 }
2637
2638 switch(operand->getQualifier())
2639 {
2640 case EvqTemporary: return temporaryRegister(operand);
2641 case EvqGlobal: return temporaryRegister(operand);
2642 case EvqConstExpr: return temporaryRegister(operand); // Unevaluated constant expression
2643 case EvqAttribute: return attributeRegister(operand);
2644 case EvqVaryingIn: return varyingRegister(operand);
2645 case EvqVaryingOut: return varyingRegister(operand);
2646 case EvqVertexIn: return attributeRegister(operand);
2647 case EvqFragmentOut: return fragmentOutputRegister(operand);
2648 case EvqVertexOut: return varyingRegister(operand);
2649 case EvqFragmentIn: return varyingRegister(operand);
2650 case EvqInvariantVaryingIn: return varyingRegister(operand);
2651 case EvqInvariantVaryingOut: return varyingRegister(operand);
2652 case EvqSmooth: return varyingRegister(operand);
2653 case EvqFlat: return varyingRegister(operand);
2654 case EvqCentroidOut: return varyingRegister(operand);
2655 case EvqSmoothIn: return varyingRegister(operand);
2656 case EvqFlatIn: return varyingRegister(operand);
2657 case EvqCentroidIn: return varyingRegister(operand);
2658 case EvqUniform: return uniformRegister(operand);
2659 case EvqIn: return temporaryRegister(operand);
2660 case EvqOut: return temporaryRegister(operand);
2661 case EvqInOut: return temporaryRegister(operand);
2662 case EvqConstReadOnly: return temporaryRegister(operand);
2663 case EvqPosition: return varyingRegister(operand);
2664 case EvqPointSize: return varyingRegister(operand);
Alexis Hetu877ddfc2017-07-25 17:48:00 -04002665 case EvqInstanceID: vertexShader->declareInstanceId(); return sw::Shader::InstanceIDIndex;
2666 case EvqVertexID: vertexShader->declareVertexId(); return sw::Shader::VertexIDIndex;
2667 case EvqFragCoord: pixelShader->declareVPos(); return sw::Shader::VPosIndex;
2668 case EvqFrontFacing: pixelShader->declareVFace(); return sw::Shader::VFaceIndex;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002669 case EvqPointCoord: return varyingRegister(operand);
2670 case EvqFragColor: return 0;
2671 case EvqFragData: return fragmentOutputRegister(operand);
2672 case EvqFragDepth: return 0;
2673 default: UNREACHABLE(operand->getQualifier());
2674 }
2675
2676 return 0;
2677 }
2678
2679 int OutputASM::writeMask(TIntermTyped *destination, int index)
2680 {
2681 if(destination->getQualifier() == EvqPointSize)
2682 {
2683 return 0x2; // Point size stored in the y component
2684 }
2685
2686 return 0xF >> (4 - registerSize(destination->getType(), index));
2687 }
2688
2689 int OutputASM::readSwizzle(TIntermTyped *argument, int size)
2690 {
2691 if(argument->getQualifier() == EvqPointSize)
2692 {
2693 return 0x55; // Point size stored in the y component
2694 }
2695
2696 static const unsigned char swizzleSize[5] = {0x00, 0x00, 0x54, 0xA4, 0xE4}; // (void), xxxx, xyyy, xyzz, xyzw
2697
2698 return swizzleSize[size];
2699 }
2700
2701 // Conservatively checks whether an expression is fast to compute and has no side effects
2702 bool OutputASM::trivial(TIntermTyped *expression, int budget)
2703 {
2704 if(!expression->isRegister())
2705 {
2706 return false;
2707 }
2708
2709 return cost(expression, budget) >= 0;
2710 }
2711
2712 // Returns the remaining computing budget (if < 0 the expression is too expensive or has side effects)
2713 int OutputASM::cost(TIntermNode *expression, int budget)
2714 {
2715 if(budget < 0)
2716 {
2717 return budget;
2718 }
2719
2720 if(expression->getAsSymbolNode())
2721 {
2722 return budget;
2723 }
2724 else if(expression->getAsConstantUnion())
2725 {
2726 return budget;
2727 }
2728 else if(expression->getAsBinaryNode())
2729 {
2730 TIntermBinary *binary = expression->getAsBinaryNode();
2731
2732 switch(binary->getOp())
2733 {
2734 case EOpVectorSwizzle:
2735 case EOpIndexDirect:
2736 case EOpIndexDirectStruct:
2737 case EOpIndexDirectInterfaceBlock:
2738 return cost(binary->getLeft(), budget - 0);
2739 case EOpAdd:
2740 case EOpSub:
2741 case EOpMul:
2742 return cost(binary->getLeft(), cost(binary->getRight(), budget - 1));
2743 default:
2744 return -1;
2745 }
2746 }
2747 else if(expression->getAsUnaryNode())
2748 {
2749 TIntermUnary *unary = expression->getAsUnaryNode();
2750
2751 switch(unary->getOp())
2752 {
2753 case EOpAbs:
2754 case EOpNegative:
2755 return cost(unary->getOperand(), budget - 1);
2756 default:
2757 return -1;
2758 }
2759 }
2760 else if(expression->getAsSelectionNode())
2761 {
2762 TIntermSelection *selection = expression->getAsSelectionNode();
2763
2764 if(selection->usesTernaryOperator())
2765 {
2766 TIntermTyped *condition = selection->getCondition();
2767 TIntermNode *trueBlock = selection->getTrueBlock();
2768 TIntermNode *falseBlock = selection->getFalseBlock();
2769 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
2770
2771 if(constantCondition)
2772 {
2773 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
2774
2775 if(trueCondition)
2776 {
2777 return cost(trueBlock, budget - 0);
2778 }
2779 else
2780 {
2781 return cost(falseBlock, budget - 0);
2782 }
2783 }
2784 else
2785 {
2786 return cost(trueBlock, cost(falseBlock, budget - 2));
2787 }
2788 }
2789 }
2790
2791 return -1;
2792 }
2793
2794 const Function *OutputASM::findFunction(const TString &name)
2795 {
2796 for(unsigned int f = 0; f < functionArray.size(); f++)
2797 {
2798 if(functionArray[f].name == name)
2799 {
2800 return &functionArray[f];
2801 }
2802 }
2803
2804 return 0;
2805 }
2806
2807 int OutputASM::temporaryRegister(TIntermTyped *temporary)
2808 {
2809 return allocate(temporaries, temporary);
2810 }
2811
Alexis Hetu49351232017-11-02 16:00:32 -04002812 void OutputASM::setPixelShaderInputs(const TType& type, int var, bool flat)
2813 {
2814 if(type.isStruct())
2815 {
2816 const TFieldList &fields = type.getStruct()->fields();
2817 int fieldVar = var;
2818 for(size_t i = 0; i < fields.size(); i++)
2819 {
2820 const TType& fieldType = *(fields[i]->type());
2821 setPixelShaderInputs(fieldType, fieldVar, flat);
2822 fieldVar += fieldType.totalRegisterCount();
2823 }
2824 }
2825 else
2826 {
2827 for(int i = 0; i < type.totalRegisterCount(); i++)
2828 {
2829 pixelShader->setInput(var + i, type.registerSize(), sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat));
2830 }
2831 }
2832 }
2833
Nicolas Capens0bac2852016-05-07 06:09:58 -04002834 int OutputASM::varyingRegister(TIntermTyped *varying)
2835 {
2836 int var = lookup(varyings, varying);
2837
2838 if(var == -1)
2839 {
2840 var = allocate(varyings, varying);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002841 int registerCount = varying->totalRegisterCount();
2842
2843 if(pixelShader)
2844 {
Nicolas Capens3b4c93f2016-05-18 12:51:37 -04002845 if((var + registerCount) > sw::MAX_FRAGMENT_INPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002846 {
2847 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "fragment shader");
2848 return 0;
2849 }
2850
2851 if(varying->getQualifier() == EvqPointCoord)
2852 {
2853 ASSERT(varying->isRegister());
Alexis Hetu49351232017-11-02 16:00:32 -04002854 pixelShader->setInput(var, varying->registerSize(), sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var));
Nicolas Capens0bac2852016-05-07 06:09:58 -04002855 }
2856 else
2857 {
Alexis Hetu49351232017-11-02 16:00:32 -04002858 setPixelShaderInputs(varying->getType(), var, hasFlatQualifier(varying));
Nicolas Capens0bac2852016-05-07 06:09:58 -04002859 }
2860 }
2861 else if(vertexShader)
2862 {
Nicolas Capensec0936c2016-05-18 12:32:02 -04002863 if((var + registerCount) > sw::MAX_VERTEX_OUTPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002864 {
2865 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "vertex shader");
2866 return 0;
2867 }
2868
2869 if(varying->getQualifier() == EvqPosition)
2870 {
2871 ASSERT(varying->isRegister());
Alexis Hetu02ad0aa2016-08-02 11:18:14 -04002872 vertexShader->setPositionRegister(var);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002873 }
2874 else if(varying->getQualifier() == EvqPointSize)
2875 {
2876 ASSERT(varying->isRegister());
Alexis Hetu02ad0aa2016-08-02 11:18:14 -04002877 vertexShader->setPointSizeRegister(var);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002878 }
2879 else
2880 {
2881 // Semantic indexes for user varyings will be assigned during program link to match the pixel shader
2882 }
2883 }
2884 else UNREACHABLE(0);
2885
2886 declareVarying(varying, var);
2887 }
2888
2889 return var;
2890 }
2891
2892 void OutputASM::declareVarying(TIntermTyped *varying, int reg)
2893 {
2894 if(varying->getQualifier() != EvqPointCoord) // gl_PointCoord does not need linking
2895 {
Alexis Hetu49351232017-11-02 16:00:32 -04002896 TIntermSymbol *symbol = varying->getAsSymbolNode();
2897 declareVarying(varying->getType(), symbol->getSymbol(), reg);
2898 }
2899 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04002900
Alexis Hetu49351232017-11-02 16:00:32 -04002901 void OutputASM::declareVarying(const TType &type, const TString &varyingName, int registerIndex)
2902 {
2903 const char *name = varyingName.c_str();
2904 VaryingList &activeVaryings = shaderObject->varyings;
2905
2906 TStructure* structure = type.getStruct();
2907 if(structure)
2908 {
2909 int fieldRegisterIndex = registerIndex;
2910
2911 const TFieldList &fields = type.getStruct()->fields();
2912 for(size_t i = 0; i < fields.size(); i++)
2913 {
2914 const TType& fieldType = *(fields[i]->type());
2915 declareVarying(fieldType, varyingName + "." + fields[i]->name(), fieldRegisterIndex);
2916 if(fieldRegisterIndex >= 0)
2917 {
2918 fieldRegisterIndex += fieldType.totalRegisterCount();
2919 }
2920 }
2921 }
2922 else
2923 {
Nicolas Capens0bac2852016-05-07 06:09:58 -04002924 // Check if this varying has been declared before without having a register assigned
2925 for(VaryingList::iterator v = activeVaryings.begin(); v != activeVaryings.end(); v++)
2926 {
2927 if(v->name == name)
2928 {
Alexis Hetu49351232017-11-02 16:00:32 -04002929 if(registerIndex >= 0)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002930 {
Alexis Hetu49351232017-11-02 16:00:32 -04002931 ASSERT(v->reg < 0 || v->reg == registerIndex);
2932 v->reg = registerIndex;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002933 }
2934
2935 return;
2936 }
2937 }
2938
Alexis Hetu49351232017-11-02 16:00:32 -04002939 activeVaryings.push_back(glsl::Varying(glVariableType(type), name, type.getArraySize(), registerIndex, 0));
Nicolas Capens0bac2852016-05-07 06:09:58 -04002940 }
2941 }
2942
2943 int OutputASM::uniformRegister(TIntermTyped *uniform)
2944 {
2945 const TType &type = uniform->getType();
2946 ASSERT(!IsSampler(type.getBasicType()));
2947 TInterfaceBlock *block = type.getAsInterfaceBlock();
2948 TIntermSymbol *symbol = uniform->getAsSymbolNode();
2949 ASSERT(symbol || block);
2950
2951 if(symbol || block)
2952 {
2953 TInterfaceBlock* parentBlock = type.getInterfaceBlock();
2954 bool isBlockMember = (!block && parentBlock);
2955 int index = isBlockMember ? lookup(uniforms, parentBlock) : lookup(uniforms, uniform);
2956
2957 if(index == -1 || isBlockMember)
2958 {
2959 if(index == -1)
2960 {
2961 index = allocate(uniforms, uniform);
2962 }
2963
2964 // Verify if the current uniform is a member of an already declared block
2965 const TString &name = symbol ? symbol->getSymbol() : block->name();
2966 int blockMemberIndex = blockMemberLookup(type, name, index);
2967 if(blockMemberIndex == -1)
2968 {
2969 declareUniform(type, name, index);
2970 }
2971 else
2972 {
2973 index = blockMemberIndex;
2974 }
2975 }
2976
2977 return index;
2978 }
2979
2980 return 0;
2981 }
2982
2983 int OutputASM::attributeRegister(TIntermTyped *attribute)
2984 {
2985 ASSERT(!attribute->isArray());
2986
2987 int index = lookup(attributes, attribute);
2988
2989 if(index == -1)
2990 {
2991 TIntermSymbol *symbol = attribute->getAsSymbolNode();
2992 ASSERT(symbol);
2993
2994 if(symbol)
2995 {
2996 index = allocate(attributes, attribute);
2997 const TType &type = attribute->getType();
2998 int registerCount = attribute->totalRegisterCount();
Alexis Hetub7508b82016-09-22 15:36:45 -04002999 sw::VertexShader::AttribType attribType = sw::VertexShader::ATTRIBTYPE_FLOAT;
3000 switch(type.getBasicType())
3001 {
3002 case EbtInt:
3003 attribType = sw::VertexShader::ATTRIBTYPE_INT;
3004 break;
3005 case EbtUInt:
3006 attribType = sw::VertexShader::ATTRIBTYPE_UINT;
3007 break;
3008 case EbtFloat:
3009 default:
3010 break;
3011 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003012
Nicolas Capensf0aef1a2016-05-18 14:44:21 -04003013 if(vertexShader && (index + registerCount) <= sw::MAX_VERTEX_INPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003014 {
3015 for(int i = 0; i < registerCount; i++)
3016 {
Alexis Hetub7508b82016-09-22 15:36:45 -04003017 vertexShader->setInput(index + i, sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, index + i, false), attribType);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003018 }
3019 }
3020
3021 ActiveAttributes &activeAttributes = shaderObject->activeAttributes;
3022
3023 const char *name = symbol->getSymbol().c_str();
3024 activeAttributes.push_back(Attribute(glVariableType(type), name, type.getArraySize(), type.getLayoutQualifier().location, index));
3025 }
3026 }
3027
3028 return index;
3029 }
3030
3031 int OutputASM::fragmentOutputRegister(TIntermTyped *fragmentOutput)
3032 {
3033 return allocate(fragmentOutputs, fragmentOutput);
3034 }
3035
3036 int OutputASM::samplerRegister(TIntermTyped *sampler)
3037 {
3038 const TType &type = sampler->getType();
3039 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
3040
3041 TIntermSymbol *symbol = sampler->getAsSymbolNode();
3042 TIntermBinary *binary = sampler->getAsBinaryNode();
3043
Nicolas Capensfcb70fd2017-05-17 15:16:51 -04003044 if(symbol)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003045 {
Nicolas Capensfcb70fd2017-05-17 15:16:51 -04003046 switch(type.getQualifier())
3047 {
3048 case EvqUniform:
3049 return samplerRegister(symbol);
3050 case EvqIn:
3051 case EvqConstReadOnly:
3052 // Function arguments are not (uniform) sampler registers
3053 return -1;
3054 default:
3055 UNREACHABLE(type.getQualifier());
3056 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003057 }
3058 else if(binary)
3059 {
3060 TIntermTyped *left = binary->getLeft();
3061 TIntermTyped *right = binary->getRight();
3062 const TType &leftType = left->getType();
3063 int index = right->getAsConstantUnion() ? right->getAsConstantUnion()->getIConst(0) : 0;
3064 int offset = 0;
3065
3066 switch(binary->getOp())
3067 {
3068 case EOpIndexDirect:
3069 ASSERT(left->isArray());
3070 offset = index * leftType.elementRegisterCount();
3071 break;
3072 case EOpIndexDirectStruct:
3073 ASSERT(leftType.isStruct());
3074 {
3075 const TFieldList &fields = leftType.getStruct()->fields();
3076
3077 for(int i = 0; i < index; i++)
3078 {
3079 offset += fields[i]->type()->totalRegisterCount();
3080 }
3081 }
3082 break;
3083 case EOpIndexIndirect: // Indirect indexing produces a temporary, not a sampler register
3084 return -1;
3085 case EOpIndexDirectInterfaceBlock: // Interface blocks can't contain samplers
3086 default:
3087 UNREACHABLE(binary->getOp());
3088 return -1;
3089 }
3090
3091 int base = samplerRegister(left);
3092
3093 if(base < 0)
3094 {
3095 return -1;
3096 }
3097
3098 return base + offset;
3099 }
3100
3101 UNREACHABLE(0);
Nicolas Capensfcb70fd2017-05-17 15:16:51 -04003102 return -1; // Not a (uniform) sampler register
Nicolas Capens0bac2852016-05-07 06:09:58 -04003103 }
3104
3105 int OutputASM::samplerRegister(TIntermSymbol *sampler)
3106 {
3107 const TType &type = sampler->getType();
3108 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
3109
3110 int index = lookup(samplers, sampler);
3111
3112 if(index == -1)
3113 {
3114 index = allocate(samplers, sampler);
3115
3116 if(sampler->getQualifier() == EvqUniform)
3117 {
3118 const char *name = sampler->getSymbol().c_str();
3119 declareUniform(type, name, index);
3120 }
3121 }
3122
3123 return index;
3124 }
3125
3126 bool OutputASM::isSamplerRegister(TIntermTyped *operand)
3127 {
3128 return operand && IsSampler(operand->getBasicType()) && samplerRegister(operand) >= 0;
3129 }
3130
3131 int OutputASM::lookup(VariableArray &list, TIntermTyped *variable)
3132 {
3133 for(unsigned int i = 0; i < list.size(); i++)
3134 {
3135 if(list[i] == variable)
3136 {
3137 return i; // Pointer match
3138 }
3139 }
3140
3141 TIntermSymbol *varSymbol = variable->getAsSymbolNode();
3142 TInterfaceBlock *varBlock = variable->getType().getAsInterfaceBlock();
3143
3144 if(varBlock)
3145 {
3146 for(unsigned int i = 0; i < list.size(); i++)
3147 {
3148 if(list[i])
3149 {
3150 TInterfaceBlock *listBlock = list[i]->getType().getAsInterfaceBlock();
3151
3152 if(listBlock)
3153 {
3154 if(listBlock->name() == varBlock->name())
3155 {
3156 ASSERT(listBlock->arraySize() == varBlock->arraySize());
3157 ASSERT(listBlock->fields() == varBlock->fields());
3158 ASSERT(listBlock->blockStorage() == varBlock->blockStorage());
3159 ASSERT(listBlock->matrixPacking() == varBlock->matrixPacking());
3160
3161 return i;
3162 }
3163 }
3164 }
3165 }
3166 }
3167 else if(varSymbol)
3168 {
3169 for(unsigned int i = 0; i < list.size(); i++)
3170 {
3171 if(list[i])
3172 {
3173 TIntermSymbol *listSymbol = list[i]->getAsSymbolNode();
3174
3175 if(listSymbol)
3176 {
3177 if(listSymbol->getId() == varSymbol->getId())
3178 {
3179 ASSERT(listSymbol->getSymbol() == varSymbol->getSymbol());
3180 ASSERT(listSymbol->getType() == varSymbol->getType());
3181 ASSERT(listSymbol->getQualifier() == varSymbol->getQualifier());
3182
3183 return i;
3184 }
3185 }
3186 }
3187 }
3188 }
3189
3190 return -1;
3191 }
3192
3193 int OutputASM::lookup(VariableArray &list, TInterfaceBlock *block)
3194 {
3195 for(unsigned int i = 0; i < list.size(); i++)
3196 {
3197 if(list[i] && (list[i]->getType().getInterfaceBlock() == block))
3198 {
3199 return i; // Pointer match
3200 }
3201 }
3202 return -1;
3203 }
3204
3205 int OutputASM::allocate(VariableArray &list, TIntermTyped *variable)
3206 {
3207 int index = lookup(list, variable);
3208
3209 if(index == -1)
3210 {
3211 unsigned int registerCount = variable->blockRegisterCount();
3212
3213 for(unsigned int i = 0; i < list.size(); i++)
3214 {
3215 if(list[i] == 0)
3216 {
3217 unsigned int j = 1;
3218 for( ; j < registerCount && (i + j) < list.size(); j++)
3219 {
3220 if(list[i + j] != 0)
3221 {
3222 break;
3223 }
3224 }
3225
3226 if(j == registerCount) // Found free slots
3227 {
3228 for(unsigned int j = 0; j < registerCount; j++)
3229 {
3230 list[i + j] = variable;
3231 }
3232
3233 return i;
3234 }
3235 }
3236 }
3237
3238 index = list.size();
3239
3240 for(unsigned int i = 0; i < registerCount; i++)
3241 {
3242 list.push_back(variable);
3243 }
3244 }
3245
3246 return index;
3247 }
3248
3249 void OutputASM::free(VariableArray &list, TIntermTyped *variable)
3250 {
3251 int index = lookup(list, variable);
3252
3253 if(index >= 0)
3254 {
3255 list[index] = 0;
3256 }
3257 }
3258
3259 int OutputASM::blockMemberLookup(const TType &type, const TString &name, int registerIndex)
3260 {
3261 const TInterfaceBlock *block = type.getInterfaceBlock();
3262
3263 if(block)
3264 {
3265 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3266 const TFieldList& fields = block->fields();
3267 const TString &blockName = block->name();
3268 int fieldRegisterIndex = registerIndex;
3269
3270 if(!type.isInterfaceBlock())
3271 {
3272 // This is a uniform that's part of a block, let's see if the block is already defined
3273 for(size_t i = 0; i < activeUniformBlocks.size(); ++i)
3274 {
3275 if(activeUniformBlocks[i].name == blockName.c_str())
3276 {
3277 // The block is already defined, find the register for the current uniform and return it
3278 for(size_t j = 0; j < fields.size(); j++)
3279 {
3280 const TString &fieldName = fields[j]->name();
3281 if(fieldName == name)
3282 {
3283 return fieldRegisterIndex;
3284 }
3285
3286 fieldRegisterIndex += fields[j]->type()->totalRegisterCount();
3287 }
3288
3289 ASSERT(false);
3290 return fieldRegisterIndex;
3291 }
3292 }
3293 }
3294 }
3295
3296 return -1;
3297 }
3298
3299 void OutputASM::declareUniform(const TType &type, const TString &name, int registerIndex, int blockId, BlockLayoutEncoder* encoder)
3300 {
3301 const TStructure *structure = type.getStruct();
3302 const TInterfaceBlock *block = (type.isInterfaceBlock() || (blockId == -1)) ? type.getInterfaceBlock() : nullptr;
3303
3304 if(!structure && !block)
3305 {
3306 ActiveUniforms &activeUniforms = shaderObject->activeUniforms;
3307 const BlockMemberInfo blockInfo = encoder ? encoder->encodeType(type) : BlockMemberInfo::getDefaultBlockInfo();
3308 if(blockId >= 0)
3309 {
3310 blockDefinitions[blockId][registerIndex] = TypedMemberInfo(blockInfo, type);
3311 shaderObject->activeUniformBlocks[blockId].fields.push_back(activeUniforms.size());
3312 }
3313 int fieldRegisterIndex = encoder ? shaderObject->activeUniformBlocks[blockId].registerIndex + BlockLayoutEncoder::getBlockRegister(blockInfo) : registerIndex;
3314 activeUniforms.push_back(Uniform(glVariableType(type), glVariablePrecision(type), name.c_str(), type.getArraySize(),
3315 fieldRegisterIndex, blockId, blockInfo));
3316 if(IsSampler(type.getBasicType()))
3317 {
3318 for(int i = 0; i < type.totalRegisterCount(); i++)
3319 {
3320 shader->declareSampler(fieldRegisterIndex + i);
3321 }
3322 }
3323 }
3324 else if(block)
3325 {
3326 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3327 const TFieldList& fields = block->fields();
3328 const TString &blockName = block->name();
3329 int fieldRegisterIndex = registerIndex;
3330 bool isUniformBlockMember = !type.isInterfaceBlock() && (blockId == -1);
3331
3332 blockId = activeUniformBlocks.size();
3333 bool isRowMajor = block->matrixPacking() == EmpRowMajor;
3334 activeUniformBlocks.push_back(UniformBlock(blockName.c_str(), 0, block->arraySize(),
3335 block->blockStorage(), isRowMajor, registerIndex, blockId));
3336 blockDefinitions.push_back(BlockDefinitionIndexMap());
3337
3338 Std140BlockEncoder currentBlockEncoder(isRowMajor);
3339 currentBlockEncoder.enterAggregateType();
3340 for(size_t i = 0; i < fields.size(); i++)
3341 {
3342 const TType &fieldType = *(fields[i]->type());
3343 const TString &fieldName = fields[i]->name();
3344 if(isUniformBlockMember && (fieldName == name))
3345 {
3346 registerIndex = fieldRegisterIndex;
3347 }
3348
3349 const TString uniformName = block->hasInstanceName() ? blockName + "." + fieldName : fieldName;
3350
3351 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, &currentBlockEncoder);
3352 fieldRegisterIndex += fieldType.totalRegisterCount();
3353 }
3354 currentBlockEncoder.exitAggregateType();
3355 activeUniformBlocks[blockId].dataSize = currentBlockEncoder.getBlockSize();
3356 }
3357 else
3358 {
3359 int fieldRegisterIndex = registerIndex;
3360
3361 const TFieldList& fields = structure->fields();
3362 if(type.isArray() && (structure || type.isInterfaceBlock()))
3363 {
3364 for(int i = 0; i < type.getArraySize(); i++)
3365 {
3366 if(encoder)
3367 {
3368 encoder->enterAggregateType();
3369 }
3370 for(size_t j = 0; j < fields.size(); j++)
3371 {
3372 const TType &fieldType = *(fields[j]->type());
3373 const TString &fieldName = fields[j]->name();
3374 const TString uniformName = name + "[" + str(i) + "]." + fieldName;
3375
3376 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3377 fieldRegisterIndex += fieldType.totalRegisterCount();
3378 }
3379 if(encoder)
3380 {
3381 encoder->exitAggregateType();
3382 }
3383 }
3384 }
3385 else
3386 {
3387 if(encoder)
3388 {
3389 encoder->enterAggregateType();
3390 }
3391 for(size_t i = 0; i < fields.size(); i++)
3392 {
3393 const TType &fieldType = *(fields[i]->type());
3394 const TString &fieldName = fields[i]->name();
3395 const TString uniformName = name + "." + fieldName;
3396
3397 declareUniform(fieldType, uniformName, fieldRegisterIndex, blockId, encoder);
3398 fieldRegisterIndex += fieldType.totalRegisterCount();
3399 }
3400 if(encoder)
3401 {
3402 encoder->exitAggregateType();
3403 }
3404 }
3405 }
3406 }
3407
3408 GLenum OutputASM::glVariableType(const TType &type)
3409 {
3410 switch(type.getBasicType())
3411 {
3412 case EbtFloat:
3413 if(type.isScalar())
3414 {
3415 return GL_FLOAT;
3416 }
3417 else if(type.isVector())
3418 {
3419 switch(type.getNominalSize())
3420 {
3421 case 2: return GL_FLOAT_VEC2;
3422 case 3: return GL_FLOAT_VEC3;
3423 case 4: return GL_FLOAT_VEC4;
3424 default: UNREACHABLE(type.getNominalSize());
3425 }
3426 }
3427 else if(type.isMatrix())
3428 {
3429 switch(type.getNominalSize())
3430 {
3431 case 2:
3432 switch(type.getSecondarySize())
3433 {
3434 case 2: return GL_FLOAT_MAT2;
3435 case 3: return GL_FLOAT_MAT2x3;
3436 case 4: return GL_FLOAT_MAT2x4;
3437 default: UNREACHABLE(type.getSecondarySize());
3438 }
3439 case 3:
3440 switch(type.getSecondarySize())
3441 {
3442 case 2: return GL_FLOAT_MAT3x2;
3443 case 3: return GL_FLOAT_MAT3;
3444 case 4: return GL_FLOAT_MAT3x4;
3445 default: UNREACHABLE(type.getSecondarySize());
3446 }
3447 case 4:
3448 switch(type.getSecondarySize())
3449 {
3450 case 2: return GL_FLOAT_MAT4x2;
3451 case 3: return GL_FLOAT_MAT4x3;
3452 case 4: return GL_FLOAT_MAT4;
3453 default: UNREACHABLE(type.getSecondarySize());
3454 }
3455 default: UNREACHABLE(type.getNominalSize());
3456 }
3457 }
3458 else UNREACHABLE(0);
3459 break;
3460 case EbtInt:
3461 if(type.isScalar())
3462 {
3463 return GL_INT;
3464 }
3465 else if(type.isVector())
3466 {
3467 switch(type.getNominalSize())
3468 {
3469 case 2: return GL_INT_VEC2;
3470 case 3: return GL_INT_VEC3;
3471 case 4: return GL_INT_VEC4;
3472 default: UNREACHABLE(type.getNominalSize());
3473 }
3474 }
3475 else UNREACHABLE(0);
3476 break;
3477 case EbtUInt:
3478 if(type.isScalar())
3479 {
3480 return GL_UNSIGNED_INT;
3481 }
3482 else if(type.isVector())
3483 {
3484 switch(type.getNominalSize())
3485 {
3486 case 2: return GL_UNSIGNED_INT_VEC2;
3487 case 3: return GL_UNSIGNED_INT_VEC3;
3488 case 4: return GL_UNSIGNED_INT_VEC4;
3489 default: UNREACHABLE(type.getNominalSize());
3490 }
3491 }
3492 else UNREACHABLE(0);
3493 break;
3494 case EbtBool:
3495 if(type.isScalar())
3496 {
3497 return GL_BOOL;
3498 }
3499 else if(type.isVector())
3500 {
3501 switch(type.getNominalSize())
3502 {
3503 case 2: return GL_BOOL_VEC2;
3504 case 3: return GL_BOOL_VEC3;
3505 case 4: return GL_BOOL_VEC4;
3506 default: UNREACHABLE(type.getNominalSize());
3507 }
3508 }
3509 else UNREACHABLE(0);
3510 break;
3511 case EbtSampler2D:
3512 return GL_SAMPLER_2D;
3513 case EbtISampler2D:
3514 return GL_INT_SAMPLER_2D;
3515 case EbtUSampler2D:
3516 return GL_UNSIGNED_INT_SAMPLER_2D;
3517 case EbtSamplerCube:
3518 return GL_SAMPLER_CUBE;
3519 case EbtISamplerCube:
3520 return GL_INT_SAMPLER_CUBE;
3521 case EbtUSamplerCube:
3522 return GL_UNSIGNED_INT_SAMPLER_CUBE;
3523 case EbtSamplerExternalOES:
3524 return GL_SAMPLER_EXTERNAL_OES;
3525 case EbtSampler3D:
3526 return GL_SAMPLER_3D_OES;
3527 case EbtISampler3D:
3528 return GL_INT_SAMPLER_3D;
3529 case EbtUSampler3D:
3530 return GL_UNSIGNED_INT_SAMPLER_3D;
3531 case EbtSampler2DArray:
3532 return GL_SAMPLER_2D_ARRAY;
3533 case EbtISampler2DArray:
3534 return GL_INT_SAMPLER_2D_ARRAY;
3535 case EbtUSampler2DArray:
3536 return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
3537 case EbtSampler2DShadow:
3538 return GL_SAMPLER_2D_SHADOW;
3539 case EbtSamplerCubeShadow:
3540 return GL_SAMPLER_CUBE_SHADOW;
3541 case EbtSampler2DArrayShadow:
3542 return GL_SAMPLER_2D_ARRAY_SHADOW;
3543 default:
3544 UNREACHABLE(type.getBasicType());
3545 break;
3546 }
3547
3548 return GL_NONE;
3549 }
3550
3551 GLenum OutputASM::glVariablePrecision(const TType &type)
3552 {
3553 if(type.getBasicType() == EbtFloat)
3554 {
3555 switch(type.getPrecision())
3556 {
3557 case EbpHigh: return GL_HIGH_FLOAT;
3558 case EbpMedium: return GL_MEDIUM_FLOAT;
3559 case EbpLow: return GL_LOW_FLOAT;
3560 case EbpUndefined:
3561 // Should be defined as the default precision by the parser
3562 default: UNREACHABLE(type.getPrecision());
3563 }
3564 }
3565 else if(type.getBasicType() == EbtInt)
3566 {
3567 switch(type.getPrecision())
3568 {
3569 case EbpHigh: return GL_HIGH_INT;
3570 case EbpMedium: return GL_MEDIUM_INT;
3571 case EbpLow: return GL_LOW_INT;
3572 case EbpUndefined:
3573 // Should be defined as the default precision by the parser
3574 default: UNREACHABLE(type.getPrecision());
3575 }
3576 }
3577
3578 // Other types (boolean, sampler) don't have a precision
3579 return GL_NONE;
3580 }
3581
3582 int OutputASM::dim(TIntermNode *v)
3583 {
3584 TIntermTyped *vector = v->getAsTyped();
3585 ASSERT(vector && vector->isRegister());
3586 return vector->getNominalSize();
3587 }
3588
3589 int OutputASM::dim2(TIntermNode *m)
3590 {
3591 TIntermTyped *matrix = m->getAsTyped();
3592 ASSERT(matrix && matrix->isMatrix() && !matrix->isArray());
3593 return matrix->getSecondarySize();
3594 }
3595
3596 // Returns ~0u if no loop count could be determined
3597 unsigned int OutputASM::loopCount(TIntermLoop *node)
3598 {
3599 // Parse loops of the form:
3600 // for(int index = initial; index [comparator] limit; index += increment)
3601 TIntermSymbol *index = 0;
3602 TOperator comparator = EOpNull;
3603 int initial = 0;
3604 int limit = 0;
3605 int increment = 0;
3606
3607 // Parse index name and intial value
3608 if(node->getInit())
3609 {
3610 TIntermAggregate *init = node->getInit()->getAsAggregate();
3611
3612 if(init)
3613 {
3614 TIntermSequence &sequence = init->getSequence();
3615 TIntermTyped *variable = sequence[0]->getAsTyped();
3616
Nicolas Capense3f05552017-05-24 10:45:56 -04003617 if(variable && variable->getQualifier() == EvqTemporary && variable->getBasicType() == EbtInt)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003618 {
3619 TIntermBinary *assign = variable->getAsBinaryNode();
3620
Nicolas Capensd0bfd912017-05-24 10:20:24 -04003621 if(assign && assign->getOp() == EOpInitialize)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003622 {
3623 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3624 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3625
3626 if(symbol && constant)
3627 {
3628 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3629 {
3630 index = symbol;
3631 initial = constant->getUnionArrayPointer()[0].getIConst();
3632 }
3633 }
3634 }
3635 }
3636 }
3637 }
3638
3639 // Parse comparator and limit value
3640 if(index && node->getCondition())
3641 {
3642 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
Alexis Hetu7be70cf2016-05-11 10:56:43 -04003643 TIntermSymbol *left = test ? test->getLeft()->getAsSymbolNode() : nullptr;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003644
Alexis Hetu7be70cf2016-05-11 10:56:43 -04003645 if(left && (left->getId() == index->getId()))
Nicolas Capens0bac2852016-05-07 06:09:58 -04003646 {
3647 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3648
3649 if(constant)
3650 {
3651 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3652 {
3653 comparator = test->getOp();
3654 limit = constant->getUnionArrayPointer()[0].getIConst();
3655 }
3656 }
3657 }
3658 }
3659
3660 // Parse increment
3661 if(index && comparator != EOpNull && node->getExpression())
3662 {
3663 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3664 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3665
3666 if(binaryTerminal)
3667 {
3668 TOperator op = binaryTerminal->getOp();
3669 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3670
3671 if(constant)
3672 {
3673 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3674 {
3675 int value = constant->getUnionArrayPointer()[0].getIConst();
3676
3677 switch(op)
3678 {
3679 case EOpAddAssign: increment = value; break;
3680 case EOpSubAssign: increment = -value; break;
3681 default: UNIMPLEMENTED();
3682 }
3683 }
3684 }
3685 }
3686 else if(unaryTerminal)
3687 {
3688 TOperator op = unaryTerminal->getOp();
3689
3690 switch(op)
3691 {
3692 case EOpPostIncrement: increment = 1; break;
3693 case EOpPostDecrement: increment = -1; break;
3694 case EOpPreIncrement: increment = 1; break;
3695 case EOpPreDecrement: increment = -1; break;
3696 default: UNIMPLEMENTED();
3697 }
3698 }
3699 }
3700
3701 if(index && comparator != EOpNull && increment != 0)
3702 {
3703 if(comparator == EOpLessThanEqual)
3704 {
3705 comparator = EOpLessThan;
3706 limit += 1;
3707 }
Nicolas Capense3f05552017-05-24 10:45:56 -04003708 else if(comparator == EOpGreaterThanEqual)
3709 {
3710 comparator = EOpLessThan;
3711 limit -= 1;
3712 std::swap(initial, limit);
3713 increment = -increment;
3714 }
3715 else if(comparator == EOpGreaterThan)
3716 {
3717 comparator = EOpLessThan;
3718 std::swap(initial, limit);
3719 increment = -increment;
3720 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003721
3722 if(comparator == EOpLessThan)
3723 {
Nicolas Capens930b7002017-01-06 17:22:13 -05003724 if(!(initial < limit)) // Never loops
Nicolas Capens0bac2852016-05-07 06:09:58 -04003725 {
Nicolas Capens930b7002017-01-06 17:22:13 -05003726 return 0;
3727 }
3728
3729 int iterations = (limit - initial + abs(increment) - 1) / increment; // Ceiling division
3730
3731 if(iterations < 0)
3732 {
3733 return ~0u;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003734 }
3735
3736 return iterations;
3737 }
3738 else UNIMPLEMENTED(); // Falls through
3739 }
3740
3741 return ~0u;
3742 }
3743
3744 bool LoopUnrollable::traverse(TIntermNode *node)
3745 {
3746 loopDepth = 0;
3747 loopUnrollable = true;
3748
3749 node->traverse(this);
3750
3751 return loopUnrollable;
3752 }
3753
3754 bool LoopUnrollable::visitLoop(Visit visit, TIntermLoop *loop)
3755 {
3756 if(visit == PreVisit)
3757 {
3758 loopDepth++;
3759 }
3760 else if(visit == PostVisit)
3761 {
3762 loopDepth++;
3763 }
3764
3765 return true;
3766 }
3767
3768 bool LoopUnrollable::visitBranch(Visit visit, TIntermBranch *node)
3769 {
3770 if(!loopUnrollable)
3771 {
3772 return false;
3773 }
3774
3775 if(!loopDepth)
3776 {
3777 return true;
3778 }
3779
3780 switch(node->getFlowOp())
3781 {
3782 case EOpKill:
3783 case EOpReturn:
3784 break;
3785 case EOpBreak:
3786 case EOpContinue:
3787 loopUnrollable = false;
3788 break;
3789 default: UNREACHABLE(node->getFlowOp());
3790 }
3791
3792 return loopUnrollable;
3793 }
3794
3795 bool LoopUnrollable::visitAggregate(Visit visit, TIntermAggregate *node)
3796 {
3797 return loopUnrollable;
3798 }
3799}