blob: 81cac70d6c74524a1345eebefedd642d8fd7fad1 [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
Alexis Hetu924513c2018-01-05 15:48:12 -050029namespace
30{
31 GLenum glVariableType(const TType &type)
32 {
33 switch(type.getBasicType())
34 {
35 case EbtFloat:
36 if(type.isScalar())
37 {
38 return GL_FLOAT;
39 }
40 else if(type.isVector())
41 {
42 switch(type.getNominalSize())
43 {
44 case 2: return GL_FLOAT_VEC2;
45 case 3: return GL_FLOAT_VEC3;
46 case 4: return GL_FLOAT_VEC4;
47 default: UNREACHABLE(type.getNominalSize());
48 }
49 }
50 else if(type.isMatrix())
51 {
52 switch(type.getNominalSize())
53 {
54 case 2:
55 switch(type.getSecondarySize())
56 {
57 case 2: return GL_FLOAT_MAT2;
58 case 3: return GL_FLOAT_MAT2x3;
59 case 4: return GL_FLOAT_MAT2x4;
60 default: UNREACHABLE(type.getSecondarySize());
61 }
62 case 3:
63 switch(type.getSecondarySize())
64 {
65 case 2: return GL_FLOAT_MAT3x2;
66 case 3: return GL_FLOAT_MAT3;
67 case 4: return GL_FLOAT_MAT3x4;
68 default: UNREACHABLE(type.getSecondarySize());
69 }
70 case 4:
71 switch(type.getSecondarySize())
72 {
73 case 2: return GL_FLOAT_MAT4x2;
74 case 3: return GL_FLOAT_MAT4x3;
75 case 4: return GL_FLOAT_MAT4;
76 default: UNREACHABLE(type.getSecondarySize());
77 }
78 default: UNREACHABLE(type.getNominalSize());
79 }
80 }
81 else UNREACHABLE(0);
82 break;
83 case EbtInt:
84 if(type.isScalar())
85 {
86 return GL_INT;
87 }
88 else if(type.isVector())
89 {
90 switch(type.getNominalSize())
91 {
92 case 2: return GL_INT_VEC2;
93 case 3: return GL_INT_VEC3;
94 case 4: return GL_INT_VEC4;
95 default: UNREACHABLE(type.getNominalSize());
96 }
97 }
98 else UNREACHABLE(0);
99 break;
100 case EbtUInt:
101 if(type.isScalar())
102 {
103 return GL_UNSIGNED_INT;
104 }
105 else if(type.isVector())
106 {
107 switch(type.getNominalSize())
108 {
109 case 2: return GL_UNSIGNED_INT_VEC2;
110 case 3: return GL_UNSIGNED_INT_VEC3;
111 case 4: return GL_UNSIGNED_INT_VEC4;
112 default: UNREACHABLE(type.getNominalSize());
113 }
114 }
115 else UNREACHABLE(0);
116 break;
117 case EbtBool:
118 if(type.isScalar())
119 {
120 return GL_BOOL;
121 }
122 else if(type.isVector())
123 {
124 switch(type.getNominalSize())
125 {
126 case 2: return GL_BOOL_VEC2;
127 case 3: return GL_BOOL_VEC3;
128 case 4: return GL_BOOL_VEC4;
129 default: UNREACHABLE(type.getNominalSize());
130 }
131 }
132 else UNREACHABLE(0);
133 break;
134 case EbtSampler2D:
135 return GL_SAMPLER_2D;
136 case EbtISampler2D:
137 return GL_INT_SAMPLER_2D;
138 case EbtUSampler2D:
139 return GL_UNSIGNED_INT_SAMPLER_2D;
140 case EbtSamplerCube:
141 return GL_SAMPLER_CUBE;
Alexis Hetu46768622018-01-16 22:09:28 -0500142 case EbtSampler2DRect:
143 return GL_SAMPLER_2D_RECT_ARB;
Alexis Hetu924513c2018-01-05 15:48:12 -0500144 case EbtISamplerCube:
145 return GL_INT_SAMPLER_CUBE;
146 case EbtUSamplerCube:
147 return GL_UNSIGNED_INT_SAMPLER_CUBE;
148 case EbtSamplerExternalOES:
149 return GL_SAMPLER_EXTERNAL_OES;
150 case EbtSampler3D:
151 return GL_SAMPLER_3D_OES;
152 case EbtISampler3D:
153 return GL_INT_SAMPLER_3D;
154 case EbtUSampler3D:
155 return GL_UNSIGNED_INT_SAMPLER_3D;
156 case EbtSampler2DArray:
157 return GL_SAMPLER_2D_ARRAY;
158 case EbtISampler2DArray:
159 return GL_INT_SAMPLER_2D_ARRAY;
160 case EbtUSampler2DArray:
161 return GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
162 case EbtSampler2DShadow:
163 return GL_SAMPLER_2D_SHADOW;
164 case EbtSamplerCubeShadow:
165 return GL_SAMPLER_CUBE_SHADOW;
166 case EbtSampler2DArrayShadow:
167 return GL_SAMPLER_2D_ARRAY_SHADOW;
168 default:
169 UNREACHABLE(type.getBasicType());
170 break;
171 }
172
173 return GL_NONE;
174 }
175
176 GLenum glVariablePrecision(const TType &type)
177 {
178 if(type.getBasicType() == EbtFloat)
179 {
180 switch(type.getPrecision())
181 {
182 case EbpHigh: return GL_HIGH_FLOAT;
183 case EbpMedium: return GL_MEDIUM_FLOAT;
184 case EbpLow: return GL_LOW_FLOAT;
185 case EbpUndefined:
186 // Should be defined as the default precision by the parser
187 default: UNREACHABLE(type.getPrecision());
188 }
189 }
190 else if(type.getBasicType() == EbtInt)
191 {
192 switch(type.getPrecision())
193 {
194 case EbpHigh: return GL_HIGH_INT;
195 case EbpMedium: return GL_MEDIUM_INT;
196 case EbpLow: return GL_LOW_INT;
197 case EbpUndefined:
198 // Should be defined as the default precision by the parser
199 default: UNREACHABLE(type.getPrecision());
200 }
201 }
202
203 // Other types (boolean, sampler) don't have a precision
204 return GL_NONE;
205 }
206}
207
Nicolas Capens0bac2852016-05-07 06:09:58 -0400208namespace glsl
209{
210 // Integer to TString conversion
211 TString str(int i)
212 {
213 char buffer[20];
214 sprintf(buffer, "%d", i);
215 return buffer;
216 }
217
218 class Temporary : public TIntermSymbol
219 {
220 public:
221 Temporary(OutputASM *assembler) : TIntermSymbol(TSymbolTableLevel::nextUniqueId(), "tmp", TType(EbtFloat, EbpHigh, EvqTemporary, 4, 1, false)), assembler(assembler)
222 {
223 }
224
225 ~Temporary()
226 {
227 assembler->freeTemporary(this);
228 }
229
230 private:
231 OutputASM *const assembler;
232 };
233
234 class Constant : public TIntermConstantUnion
235 {
236 public:
237 Constant(float x, float y, float z, float w) : TIntermConstantUnion(constants, TType(EbtFloat, EbpHigh, EvqConstExpr, 4, 1, false))
238 {
239 constants[0].setFConst(x);
240 constants[1].setFConst(y);
241 constants[2].setFConst(z);
242 constants[3].setFConst(w);
243 }
244
245 Constant(bool b) : TIntermConstantUnion(constants, TType(EbtBool, EbpHigh, EvqConstExpr, 1, 1, false))
246 {
247 constants[0].setBConst(b);
248 }
249
250 Constant(int i) : TIntermConstantUnion(constants, TType(EbtInt, EbpHigh, EvqConstExpr, 1, 1, false))
251 {
252 constants[0].setIConst(i);
253 }
254
255 ~Constant()
256 {
257 }
258
259 private:
260 ConstantUnion constants[4];
261 };
262
Alexis Hetu924513c2018-01-05 15:48:12 -0500263 ShaderVariable::ShaderVariable(const TType& type, const std::string& name, int registerIndex) :
264 type(type.isStruct() ? GL_NONE : glVariableType(type)), precision(glVariablePrecision(type)),
265 name(name), arraySize(type.getArraySize()), registerIndex(registerIndex)
266 {
267 if(type.isStruct())
268 {
269 for(const auto& field : type.getStruct()->fields())
270 {
271 fields.push_back(ShaderVariable(*(field->type()), field->name().c_str(), -1));
272 }
273 }
274 }
275
276 Uniform::Uniform(const TType& type, const std::string &name, int registerIndex, int blockId, const BlockMemberInfo& blockMemberInfo) :
277 ShaderVariable(type, name, registerIndex), blockId(blockId), blockInfo(blockMemberInfo)
Nicolas Capens0bac2852016-05-07 06:09:58 -0400278 {
279 }
280
281 UniformBlock::UniformBlock(const std::string& name, unsigned int dataSize, unsigned int arraySize,
282 TLayoutBlockStorage layout, bool isRowMajorLayout, int registerIndex, int blockId) :
283 name(name), dataSize(dataSize), arraySize(arraySize), layout(layout),
284 isRowMajorLayout(isRowMajorLayout), registerIndex(registerIndex), blockId(blockId)
285 {
286 }
287
Alexis Hetud2742532018-01-23 16:53:41 -0500288 BlockLayoutEncoder::BlockLayoutEncoder()
289 : mCurrentOffset(0)
Nicolas Capens0bac2852016-05-07 06:09:58 -0400290 {
291 }
292
293 BlockMemberInfo BlockLayoutEncoder::encodeType(const TType &type)
294 {
295 int arrayStride;
296 int matrixStride;
297
Alexis Hetud2742532018-01-23 16:53:41 -0500298 bool isRowMajor = type.getLayoutQualifier().matrixPacking == EmpRowMajor;
299 getBlockLayoutInfo(type, type.getArraySize(), isRowMajor, &arrayStride, &matrixStride);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400300
301 const BlockMemberInfo memberInfo(static_cast<int>(mCurrentOffset * BytesPerComponent),
302 static_cast<int>(arrayStride * BytesPerComponent),
303 static_cast<int>(matrixStride * BytesPerComponent),
Alexis Hetud2742532018-01-23 16:53:41 -0500304 (matrixStride > 0) && isRowMajor);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400305
Alexis Hetud2742532018-01-23 16:53:41 -0500306 advanceOffset(type, type.getArraySize(), isRowMajor, arrayStride, matrixStride);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400307
308 return memberInfo;
309 }
310
311 // static
312 size_t BlockLayoutEncoder::getBlockRegister(const BlockMemberInfo &info)
313 {
314 return (info.offset / BytesPerComponent) / ComponentsPerRegister;
315 }
316
317 // static
318 size_t BlockLayoutEncoder::getBlockRegisterElement(const BlockMemberInfo &info)
319 {
320 return (info.offset / BytesPerComponent) % ComponentsPerRegister;
321 }
322
323 void BlockLayoutEncoder::nextRegister()
324 {
325 mCurrentOffset = sw::align(mCurrentOffset, ComponentsPerRegister);
326 }
327
Alexis Hetud2742532018-01-23 16:53:41 -0500328 Std140BlockEncoder::Std140BlockEncoder() : BlockLayoutEncoder()
Nicolas Capens0bac2852016-05-07 06:09:58 -0400329 {
330 }
331
332 void Std140BlockEncoder::enterAggregateType()
333 {
334 nextRegister();
335 }
336
337 void Std140BlockEncoder::exitAggregateType()
338 {
339 nextRegister();
340 }
341
342 void Std140BlockEncoder::getBlockLayoutInfo(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)
343 {
344 size_t baseAlignment = 0;
345 int matrixStride = 0;
346 int arrayStride = 0;
347
348 if(type.isMatrix())
349 {
350 baseAlignment = ComponentsPerRegister;
351 matrixStride = ComponentsPerRegister;
352
353 if(arraySize > 0)
354 {
355 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
356 arrayStride = ComponentsPerRegister * numRegisters;
357 }
358 }
359 else if(arraySize > 0)
360 {
361 baseAlignment = ComponentsPerRegister;
362 arrayStride = ComponentsPerRegister;
363 }
364 else
365 {
366 const size_t numComponents = type.getElementSize();
367 baseAlignment = (numComponents == 3 ? 4u : numComponents);
368 }
369
370 mCurrentOffset = sw::align(mCurrentOffset, baseAlignment);
371
372 *matrixStrideOut = matrixStride;
373 *arrayStrideOut = arrayStride;
374 }
375
376 void Std140BlockEncoder::advanceOffset(const TType &type, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)
377 {
378 if(arraySize > 0)
379 {
380 mCurrentOffset += arrayStride * arraySize;
381 }
382 else if(type.isMatrix())
383 {
384 ASSERT(matrixStride == ComponentsPerRegister);
385 const int numRegisters = isRowMajorMatrix ? type.getSecondarySize() : type.getNominalSize();
386 mCurrentOffset += ComponentsPerRegister * numRegisters;
387 }
388 else
389 {
390 mCurrentOffset += type.getElementSize();
391 }
392 }
393
394 Attribute::Attribute()
395 {
396 type = GL_NONE;
397 arraySize = 0;
398 registerIndex = 0;
399 }
400
401 Attribute::Attribute(GLenum type, const std::string &name, int arraySize, int location, int registerIndex)
402 {
403 this->type = type;
404 this->name = name;
405 this->arraySize = arraySize;
406 this->location = location;
407 this->registerIndex = registerIndex;
408 }
409
410 sw::PixelShader *Shader::getPixelShader() const
411 {
Nicolas Capens7cbb1de2017-12-22 08:54:18 -0500412 return nullptr;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400413 }
414
415 sw::VertexShader *Shader::getVertexShader() const
416 {
Nicolas Capens7cbb1de2017-12-22 08:54:18 -0500417 return nullptr;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400418 }
419
420 OutputASM::TextureFunction::TextureFunction(const TString& nodeName) : method(IMPLICIT), proj(false), offset(false)
421 {
422 TString name = TFunction::unmangleName(nodeName);
423
424 if(name == "texture2D" || name == "textureCube" || name == "texture" || name == "texture3D")
425 {
426 method = IMPLICIT;
427 }
428 else if(name == "texture2DProj" || name == "textureProj")
429 {
430 method = IMPLICIT;
431 proj = true;
432 }
433 else if(name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod")
434 {
435 method = LOD;
436 }
437 else if(name == "texture2DProjLod" || name == "textureProjLod")
438 {
439 method = LOD;
440 proj = true;
441 }
442 else if(name == "textureSize")
443 {
444 method = SIZE;
445 }
446 else if(name == "textureOffset")
447 {
448 method = IMPLICIT;
449 offset = true;
450 }
451 else if(name == "textureProjOffset")
452 {
453 method = IMPLICIT;
454 offset = true;
455 proj = true;
456 }
457 else if(name == "textureLodOffset")
458 {
459 method = LOD;
460 offset = true;
461 }
462 else if(name == "textureProjLodOffset")
463 {
464 method = LOD;
465 proj = true;
466 offset = true;
467 }
468 else if(name == "texelFetch")
469 {
470 method = FETCH;
471 }
472 else if(name == "texelFetchOffset")
473 {
474 method = FETCH;
475 offset = true;
476 }
477 else if(name == "textureGrad")
478 {
479 method = GRAD;
480 }
481 else if(name == "textureGradOffset")
482 {
483 method = GRAD;
484 offset = true;
485 }
486 else if(name == "textureProjGrad")
487 {
488 method = GRAD;
489 proj = true;
490 }
491 else if(name == "textureProjGradOffset")
492 {
493 method = GRAD;
494 proj = true;
495 offset = true;
496 }
Alexis Hetu46768622018-01-16 22:09:28 -0500497 else if(name == "texture2DRect")
498 {
499 method = RECT;
500 }
501 else if(name == "texture2DRectProj")
502 {
503 method = RECT;
504 proj = true;
505 }
Nicolas Capens0bac2852016-05-07 06:09:58 -0400506 else UNREACHABLE(0);
507 }
508
509 OutputASM::OutputASM(TParseContext &context, Shader *shaderObject) : TIntermTraverser(true, true, true), shaderObject(shaderObject), mContext(context)
510 {
Nicolas Capens7cbb1de2017-12-22 08:54:18 -0500511 shader = nullptr;
512 pixelShader = nullptr;
513 vertexShader = nullptr;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400514
515 if(shaderObject)
516 {
517 shader = shaderObject->getShader();
518 pixelShader = shaderObject->getPixelShader();
519 vertexShader = shaderObject->getVertexShader();
520 }
521
Nicolas Capens7cbb1de2017-12-22 08:54:18 -0500522 functionArray.push_back(Function(0, "main(", nullptr, nullptr));
Nicolas Capens0bac2852016-05-07 06:09:58 -0400523 currentFunction = 0;
Nicolas Capens7cbb1de2017-12-22 08:54:18 -0500524 outputQualifier = EvqOutput; // Initialize outputQualifier to any value other than EvqFragColor or EvqFragData
Nicolas Capens0bac2852016-05-07 06:09:58 -0400525 }
526
527 OutputASM::~OutputASM()
528 {
529 }
530
531 void OutputASM::output()
532 {
533 if(shader)
534 {
535 emitShader(GLOBAL);
536
537 if(functionArray.size() > 1) // Only call main() when there are other functions
538 {
539 Instruction *callMain = emit(sw::Shader::OPCODE_CALL);
540 callMain->dst.type = sw::Shader::PARAMETER_LABEL;
541 callMain->dst.index = 0; // main()
542
543 emit(sw::Shader::OPCODE_RET);
544 }
545
546 emitShader(FUNCTION);
547 }
548 }
549
550 void OutputASM::emitShader(Scope scope)
551 {
552 emitScope = scope;
553 currentScope = GLOBAL;
554 mContext.getTreeRoot()->traverse(this);
555 }
556
557 void OutputASM::freeTemporary(Temporary *temporary)
558 {
559 free(temporaries, temporary);
560 }
561
562 sw::Shader::Opcode OutputASM::getOpcode(sw::Shader::Opcode op, TIntermTyped *in) const
563 {
564 TBasicType baseType = in->getType().getBasicType();
565
566 switch(op)
567 {
568 case sw::Shader::OPCODE_NEG:
569 switch(baseType)
570 {
571 case EbtInt:
572 case EbtUInt:
573 return sw::Shader::OPCODE_INEG;
574 case EbtFloat:
575 default:
576 return op;
577 }
578 case sw::Shader::OPCODE_ABS:
579 switch(baseType)
580 {
581 case EbtInt:
582 return sw::Shader::OPCODE_IABS;
583 case EbtFloat:
584 default:
585 return op;
586 }
587 case sw::Shader::OPCODE_SGN:
588 switch(baseType)
589 {
590 case EbtInt:
591 return sw::Shader::OPCODE_ISGN;
592 case EbtFloat:
593 default:
594 return op;
595 }
596 case sw::Shader::OPCODE_ADD:
597 switch(baseType)
598 {
599 case EbtInt:
600 case EbtUInt:
601 return sw::Shader::OPCODE_IADD;
602 case EbtFloat:
603 default:
604 return op;
605 }
606 case sw::Shader::OPCODE_SUB:
607 switch(baseType)
608 {
609 case EbtInt:
610 case EbtUInt:
611 return sw::Shader::OPCODE_ISUB;
612 case EbtFloat:
613 default:
614 return op;
615 }
616 case sw::Shader::OPCODE_MUL:
617 switch(baseType)
618 {
619 case EbtInt:
620 case EbtUInt:
621 return sw::Shader::OPCODE_IMUL;
622 case EbtFloat:
623 default:
624 return op;
625 }
626 case sw::Shader::OPCODE_DIV:
627 switch(baseType)
628 {
629 case EbtInt:
630 return sw::Shader::OPCODE_IDIV;
631 case EbtUInt:
632 return sw::Shader::OPCODE_UDIV;
633 case EbtFloat:
634 default:
635 return op;
636 }
637 case sw::Shader::OPCODE_IMOD:
638 return baseType == EbtUInt ? sw::Shader::OPCODE_UMOD : op;
639 case sw::Shader::OPCODE_ISHR:
640 return baseType == EbtUInt ? sw::Shader::OPCODE_USHR : op;
641 case sw::Shader::OPCODE_MIN:
642 switch(baseType)
643 {
644 case EbtInt:
645 return sw::Shader::OPCODE_IMIN;
646 case EbtUInt:
647 return sw::Shader::OPCODE_UMIN;
648 case EbtFloat:
649 default:
650 return op;
651 }
652 case sw::Shader::OPCODE_MAX:
653 switch(baseType)
654 {
655 case EbtInt:
656 return sw::Shader::OPCODE_IMAX;
657 case EbtUInt:
658 return sw::Shader::OPCODE_UMAX;
659 case EbtFloat:
660 default:
661 return op;
662 }
663 default:
664 return op;
665 }
666 }
667
668 void OutputASM::visitSymbol(TIntermSymbol *symbol)
669 {
Nicolas Capens6896e352018-01-10 12:46:52 -0500670 // The type of vertex outputs and fragment inputs with the same name must match (validated at link time),
671 // so declare them but don't assign a register index yet (one will be assigned when referenced in reachable code).
672 switch(symbol->getQualifier())
Nicolas Capens0bac2852016-05-07 06:09:58 -0400673 {
Nicolas Capens6896e352018-01-10 12:46:52 -0500674 case EvqVaryingIn:
675 case EvqVaryingOut:
676 case EvqInvariantVaryingIn:
677 case EvqInvariantVaryingOut:
678 case EvqVertexOut:
679 case EvqFragmentIn:
Nicolas Capens0bac2852016-05-07 06:09:58 -0400680 if(symbol->getBasicType() != EbtInvariant) // Typeless declarations are not new varyings
681 {
682 declareVarying(symbol, -1);
683 }
Nicolas Capens6896e352018-01-10 12:46:52 -0500684 break;
Alexis Hetu930df972018-01-30 16:54:13 -0500685 case EvqFragmentOut:
686 declareFragmentOutput(symbol);
687 break;
Nicolas Capens6896e352018-01-10 12:46:52 -0500688 default:
689 break;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400690 }
691
692 TInterfaceBlock* block = symbol->getType().getInterfaceBlock();
693 // OpenGL ES 3.0.4 spec, section 2.12.6 Uniform Variables:
694 // "All members of a named uniform block declared with a shared or std140 layout qualifier
695 // are considered active, even if they are not referenced in any shader in the program.
696 // The uniform block itself is also considered active, even if no member of the block is referenced."
697 if(block && ((block->blockStorage() == EbsShared) || (block->blockStorage() == EbsStd140)))
698 {
699 uniformRegister(symbol);
700 }
701 }
702
703 bool OutputASM::visitBinary(Visit visit, TIntermBinary *node)
704 {
705 if(currentScope != emitScope)
706 {
707 return false;
708 }
709
710 TIntermTyped *result = node;
711 TIntermTyped *left = node->getLeft();
712 TIntermTyped *right = node->getRight();
713 const TType &leftType = left->getType();
714 const TType &rightType = right->getType();
Nicolas Capens0bac2852016-05-07 06:09:58 -0400715
716 if(isSamplerRegister(result))
717 {
718 return false; // Don't traverse, the register index is determined statically
719 }
720
721 switch(node->getOp())
722 {
723 case EOpAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500724 assert(visit == PreVisit);
725 right->traverse(this);
726 assignLvalue(left, right);
727 copy(result, right);
728 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400729 case EOpInitialize:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500730 assert(visit == PreVisit);
Nicolas Capens7cbb1de2017-12-22 08:54:18 -0500731 // Constant arrays go into the constant register file.
732 if(leftType.getQualifier() == EvqConstExpr && leftType.isArray() && leftType.getArraySize() > 1)
733 {
734 for(int i = 0; i < left->totalRegisterCount(); i++)
735 {
736 emit(sw::Shader::OPCODE_DEF, left, i, right, i);
737 }
738 }
739 else
740 {
741 right->traverse(this);
742 copy(left, right);
743 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500744 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400745 case EOpMatrixTimesScalarAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500746 assert(visit == PreVisit);
747 right->traverse(this);
748 for(int i = 0; i < leftType.getNominalSize(); i++)
Nicolas Capens0bac2852016-05-07 06:09:58 -0400749 {
Nicolas Capens84249fd2017-11-09 11:20:51 -0500750 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400751 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500752
753 assignLvalue(left, result);
754 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400755 case EOpVectorTimesMatrixAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500756 assert(visit == PreVisit);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400757 {
Nicolas Capens84249fd2017-11-09 11:20:51 -0500758 right->traverse(this);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400759 int size = leftType.getNominalSize();
760
761 for(int i = 0; i < size; i++)
762 {
763 Instruction *dot = emit(sw::Shader::OPCODE_DP(size), result, 0, left, 0, right, i);
764 dot->dst.mask = 1 << i;
765 }
766
767 assignLvalue(left, result);
768 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500769 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400770 case EOpMatrixTimesMatrixAssign:
Nicolas Capens84249fd2017-11-09 11:20:51 -0500771 assert(visit == PreVisit);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400772 {
Nicolas Capens84249fd2017-11-09 11:20:51 -0500773 right->traverse(this);
Nicolas Capens0bac2852016-05-07 06:09:58 -0400774 int dim = leftType.getNominalSize();
775
776 for(int i = 0; i < dim; i++)
777 {
778 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
779 mul->src[1].swizzle = 0x00;
780
781 for(int j = 1; j < dim; j++)
782 {
783 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
784 mad->src[1].swizzle = j * 0x55;
785 }
786 }
787
788 assignLvalue(left, result);
789 }
Nicolas Capens84249fd2017-11-09 11:20:51 -0500790 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400791 case EOpIndexDirect:
Nicolas Capens0bac2852016-05-07 06:09:58 -0400792 case EOpIndexIndirect:
Nicolas Capens0bac2852016-05-07 06:09:58 -0400793 case EOpIndexDirectStruct:
794 case EOpIndexDirectInterfaceBlock:
Nicolas Capensd469de22017-11-16 10:42:20 -0500795 assert(visit == PreVisit);
796 evaluateRvalue(node);
797 return false;
Nicolas Capens0bac2852016-05-07 06:09:58 -0400798 case EOpVectorSwizzle:
799 if(visit == PostVisit)
800 {
801 int swizzle = 0;
802 TIntermAggregate *components = right->getAsAggregate();
803
804 if(components)
805 {
806 TIntermSequence &sequence = components->getSequence();
807 int component = 0;
808
809 for(TIntermSequence::iterator sit = sequence.begin(); sit != sequence.end(); sit++)
810 {
811 TIntermConstantUnion *element = (*sit)->getAsConstantUnion();
812
813 if(element)
814 {
815 int i = element->getUnionArrayPointer()[0].getIConst();
816 swizzle |= i << (component * 2);
817 component++;
818 }
819 else UNREACHABLE(0);
820 }
821 }
822 else UNREACHABLE(0);
823
824 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, left);
825 mov->src[0].swizzle = swizzle;
826 }
827 break;
828 case EOpAddAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_ADD, result), result, left, left, right); break;
829 case EOpAdd: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_ADD, result), result, left, right); break;
830 case EOpSubAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_SUB, result), result, left, left, right); break;
831 case EOpSub: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_SUB, result), result, left, right); break;
832 case EOpMulAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_MUL, result), result, left, left, right); break;
833 case EOpMul: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_MUL, result), result, left, right); break;
834 case EOpDivAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_DIV, result), result, left, left, right); break;
835 case EOpDiv: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_DIV, result), result, left, right); break;
836 case EOpIModAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_IMOD, result), result, left, left, right); break;
837 case EOpIMod: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_IMOD, result), result, left, right); break;
838 case EOpBitShiftLeftAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_SHL, result, left, left, right); break;
839 case EOpBitShiftLeft: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_SHL, result, left, right); break;
840 case EOpBitShiftRightAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_ISHR, result), result, left, left, right); break;
841 case EOpBitShiftRight: if(visit == PostVisit) emitBinary(getOpcode(sw::Shader::OPCODE_ISHR, result), result, left, right); break;
842 case EOpBitwiseAndAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_AND, result, left, left, right); break;
843 case EOpBitwiseAnd: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_AND, result, left, right); break;
844 case EOpBitwiseXorAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_XOR, result, left, left, right); break;
845 case EOpBitwiseXor: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_XOR, result, left, right); break;
846 case EOpBitwiseOrAssign: if(visit == PostVisit) emitAssign(sw::Shader::OPCODE_OR, result, left, left, right); break;
847 case EOpBitwiseOr: if(visit == PostVisit) emitBinary(sw::Shader::OPCODE_OR, result, left, right); break;
848 case EOpEqual:
849 if(visit == PostVisit)
850 {
851 emitBinary(sw::Shader::OPCODE_EQ, result, left, right);
852
853 for(int index = 1; index < left->totalRegisterCount(); index++)
854 {
855 Temporary equal(this);
856 emit(sw::Shader::OPCODE_EQ, &equal, 0, left, index, right, index);
857 emit(sw::Shader::OPCODE_AND, result, result, &equal);
858 }
859 }
860 break;
861 case EOpNotEqual:
862 if(visit == PostVisit)
863 {
864 emitBinary(sw::Shader::OPCODE_NE, result, left, right);
865
866 for(int index = 1; index < left->totalRegisterCount(); index++)
867 {
868 Temporary notEqual(this);
869 emit(sw::Shader::OPCODE_NE, &notEqual, 0, left, index, right, index);
870 emit(sw::Shader::OPCODE_OR, result, result, &notEqual);
871 }
872 }
873 break;
874 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, left, right); break;
875 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, left, right); break;
876 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, left, right); break;
877 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, left, right); break;
878 case EOpVectorTimesScalarAssign: if(visit == PostVisit) emitAssign(getOpcode(sw::Shader::OPCODE_MUL, left), result, left, left, right); break;
879 case EOpVectorTimesScalar: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MUL, left), result, left, right); break;
880 case EOpMatrixTimesScalar:
881 if(visit == PostVisit)
882 {
883 if(left->isMatrix())
884 {
885 for(int i = 0; i < leftType.getNominalSize(); i++)
886 {
887 emit(sw::Shader::OPCODE_MUL, result, i, left, i, right, 0);
888 }
889 }
890 else if(right->isMatrix())
891 {
892 for(int i = 0; i < rightType.getNominalSize(); i++)
893 {
894 emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
895 }
896 }
897 else UNREACHABLE(0);
898 }
899 break;
900 case EOpVectorTimesMatrix:
901 if(visit == PostVisit)
902 {
903 sw::Shader::Opcode dpOpcode = sw::Shader::OPCODE_DP(leftType.getNominalSize());
904
905 int size = rightType.getNominalSize();
906 for(int i = 0; i < size; i++)
907 {
908 Instruction *dot = emit(dpOpcode, result, 0, left, 0, right, i);
909 dot->dst.mask = 1 << i;
910 }
911 }
912 break;
913 case EOpMatrixTimesVector:
914 if(visit == PostVisit)
915 {
916 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, left, right);
917 mul->src[1].swizzle = 0x00;
918
919 int size = rightType.getNominalSize();
920 for(int i = 1; i < size; i++)
921 {
922 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, 0, left, i, right, 0, result);
923 mad->src[1].swizzle = i * 0x55;
924 }
925 }
926 break;
927 case EOpMatrixTimesMatrix:
928 if(visit == PostVisit)
929 {
930 int dim = leftType.getNominalSize();
931
932 int size = rightType.getNominalSize();
933 for(int i = 0; i < size; i++)
934 {
935 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, left, 0, right, i);
936 mul->src[1].swizzle = 0x00;
937
938 for(int j = 1; j < dim; j++)
939 {
940 Instruction *mad = emit(sw::Shader::OPCODE_MAD, result, i, left, j, right, i, result, i);
941 mad->src[1].swizzle = j * 0x55;
942 }
943 }
944 }
945 break;
946 case EOpLogicalOr:
947 if(trivial(right, 6))
948 {
949 if(visit == PostVisit)
950 {
951 emit(sw::Shader::OPCODE_OR, result, left, right);
952 }
953 }
954 else // Short-circuit evaluation
955 {
956 if(visit == InVisit)
957 {
958 emit(sw::Shader::OPCODE_MOV, result, left);
959 Instruction *ifnot = emit(sw::Shader::OPCODE_IF, 0, result);
960 ifnot->src[0].modifier = sw::Shader::MODIFIER_NOT;
961 }
962 else if(visit == PostVisit)
963 {
964 emit(sw::Shader::OPCODE_MOV, result, right);
965 emit(sw::Shader::OPCODE_ENDIF);
966 }
967 }
968 break;
969 case EOpLogicalXor: if(visit == PostVisit) emit(sw::Shader::OPCODE_XOR, result, left, right); break;
970 case EOpLogicalAnd:
971 if(trivial(right, 6))
972 {
973 if(visit == PostVisit)
974 {
975 emit(sw::Shader::OPCODE_AND, result, left, right);
976 }
977 }
978 else // Short-circuit evaluation
979 {
980 if(visit == InVisit)
981 {
982 emit(sw::Shader::OPCODE_MOV, result, left);
983 emit(sw::Shader::OPCODE_IF, 0, result);
984 }
985 else if(visit == PostVisit)
986 {
987 emit(sw::Shader::OPCODE_MOV, result, right);
988 emit(sw::Shader::OPCODE_ENDIF);
989 }
990 }
991 break;
992 default: UNREACHABLE(node->getOp());
993 }
994
995 return true;
996 }
997
998 void OutputASM::emitDeterminant(TIntermTyped *result, TIntermTyped *arg, int size, int col, int row, int outCol, int outRow)
999 {
1000 switch(size)
1001 {
1002 case 1: // Used for cofactor computation only
1003 {
1004 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
1005 bool isMov = (row == col);
1006 sw::Shader::Opcode op = isMov ? sw::Shader::OPCODE_MOV : sw::Shader::OPCODE_NEG;
1007 Instruction *mov = emit(op, result, outCol, arg, isMov ? 1 - row : row);
1008 mov->src[0].swizzle = 0x55 * (isMov ? 1 - col : col);
1009 mov->dst.mask = 1 << outRow;
1010 }
1011 break;
1012 case 2:
1013 {
1014 static const unsigned int swizzle[3] = { 0x99, 0x88, 0x44 }; // xy?? : yzyz, xzxz, xyxy
1015
1016 bool isCofactor = (col >= 0) && (row >= 0);
1017 int col0 = (isCofactor && (col <= 0)) ? 1 : 0;
1018 int col1 = (isCofactor && (col <= 1)) ? 2 : 1;
1019 bool negate = isCofactor && ((col & 0x01) ^ (row & 0x01));
1020
1021 Instruction *det = emit(sw::Shader::OPCODE_DET2, result, outCol, arg, negate ? col1 : col0, arg, negate ? col0 : col1);
1022 det->src[0].swizzle = det->src[1].swizzle = swizzle[isCofactor ? row : 2];
1023 det->dst.mask = 1 << outRow;
1024 }
1025 break;
1026 case 3:
1027 {
1028 static const unsigned int swizzle[4] = { 0xF9, 0xF8, 0xF4, 0xE4 }; // xyz? : yzww, xzww, xyww, xyzw
1029
1030 bool isCofactor = (col >= 0) && (row >= 0);
1031 int col0 = (isCofactor && (col <= 0)) ? 1 : 0;
1032 int col1 = (isCofactor && (col <= 1)) ? 2 : 1;
1033 int col2 = (isCofactor && (col <= 2)) ? 3 : 2;
1034 bool negate = isCofactor && ((col & 0x01) ^ (row & 0x01));
1035
1036 Instruction *det = emit(sw::Shader::OPCODE_DET3, result, outCol, arg, col0, arg, negate ? col2 : col1, arg, negate ? col1 : col2);
1037 det->src[0].swizzle = det->src[1].swizzle = det->src[2].swizzle = swizzle[isCofactor ? row : 3];
1038 det->dst.mask = 1 << outRow;
1039 }
1040 break;
1041 case 4:
1042 {
1043 Instruction *det = emit(sw::Shader::OPCODE_DET4, result, outCol, arg, 0, arg, 1, arg, 2, arg, 3);
1044 det->dst.mask = 1 << outRow;
1045 }
1046 break;
1047 default:
1048 UNREACHABLE(size);
1049 break;
1050 }
1051 }
1052
1053 bool OutputASM::visitUnary(Visit visit, TIntermUnary *node)
1054 {
1055 if(currentScope != emitScope)
1056 {
1057 return false;
1058 }
1059
1060 TIntermTyped *result = node;
1061 TIntermTyped *arg = node->getOperand();
1062 TBasicType basicType = arg->getType().getBasicType();
1063
1064 union
1065 {
1066 float f;
1067 int i;
1068 } one_value;
1069
1070 if(basicType == EbtInt || basicType == EbtUInt)
1071 {
1072 one_value.i = 1;
1073 }
1074 else
1075 {
1076 one_value.f = 1.0f;
1077 }
1078
1079 Constant one(one_value.f, one_value.f, one_value.f, one_value.f);
1080 Constant rad(1.74532925e-2f, 1.74532925e-2f, 1.74532925e-2f, 1.74532925e-2f);
1081 Constant deg(5.72957795e+1f, 5.72957795e+1f, 5.72957795e+1f, 5.72957795e+1f);
1082
1083 switch(node->getOp())
1084 {
1085 case EOpNegative:
1086 if(visit == PostVisit)
1087 {
1088 sw::Shader::Opcode negOpcode = getOpcode(sw::Shader::OPCODE_NEG, arg);
1089 for(int index = 0; index < arg->totalRegisterCount(); index++)
1090 {
1091 emit(negOpcode, result, index, arg, index);
1092 }
1093 }
1094 break;
1095 case EOpVectorLogicalNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
1096 case EOpLogicalNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
Alexis Hetu18e2a972017-07-28 13:43:25 -04001097 case EOpBitwiseNot: if(visit == PostVisit) emit(sw::Shader::OPCODE_NOT, result, arg); break;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001098 case EOpPostIncrement:
1099 if(visit == PostVisit)
1100 {
1101 copy(result, arg);
1102
1103 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
1104 for(int index = 0; index < arg->totalRegisterCount(); index++)
1105 {
1106 emit(addOpcode, arg, index, arg, index, &one);
1107 }
1108
1109 assignLvalue(arg, arg);
1110 }
1111 break;
1112 case EOpPostDecrement:
1113 if(visit == PostVisit)
1114 {
1115 copy(result, arg);
1116
1117 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
1118 for(int index = 0; index < arg->totalRegisterCount(); index++)
1119 {
1120 emit(subOpcode, arg, index, arg, index, &one);
1121 }
1122
1123 assignLvalue(arg, arg);
1124 }
1125 break;
1126 case EOpPreIncrement:
1127 if(visit == PostVisit)
1128 {
1129 sw::Shader::Opcode addOpcode = getOpcode(sw::Shader::OPCODE_ADD, arg);
1130 for(int index = 0; index < arg->totalRegisterCount(); index++)
1131 {
1132 emit(addOpcode, result, index, arg, index, &one);
1133 }
1134
1135 assignLvalue(arg, result);
1136 }
1137 break;
1138 case EOpPreDecrement:
1139 if(visit == PostVisit)
1140 {
1141 sw::Shader::Opcode subOpcode = getOpcode(sw::Shader::OPCODE_SUB, arg);
1142 for(int index = 0; index < arg->totalRegisterCount(); index++)
1143 {
1144 emit(subOpcode, result, index, arg, index, &one);
1145 }
1146
1147 assignLvalue(arg, result);
1148 }
1149 break;
1150 case EOpRadians: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &rad); break;
1151 case EOpDegrees: if(visit == PostVisit) emit(sw::Shader::OPCODE_MUL, result, arg, &deg); break;
1152 case EOpSin: if(visit == PostVisit) emit(sw::Shader::OPCODE_SIN, result, arg); break;
1153 case EOpCos: if(visit == PostVisit) emit(sw::Shader::OPCODE_COS, result, arg); break;
1154 case EOpTan: if(visit == PostVisit) emit(sw::Shader::OPCODE_TAN, result, arg); break;
1155 case EOpAsin: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASIN, result, arg); break;
1156 case EOpAcos: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOS, result, arg); break;
1157 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN, result, arg); break;
1158 case EOpSinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_SINH, result, arg); break;
1159 case EOpCosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_COSH, result, arg); break;
1160 case EOpTanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_TANH, result, arg); break;
1161 case EOpAsinh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ASINH, result, arg); break;
1162 case EOpAcosh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ACOSH, result, arg); break;
1163 case EOpAtanh: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATANH, result, arg); break;
1164 case EOpExp: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP, result, arg); break;
1165 case EOpLog: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG, result, arg); break;
1166 case EOpExp2: if(visit == PostVisit) emit(sw::Shader::OPCODE_EXP2, result, arg); break;
1167 case EOpLog2: if(visit == PostVisit) emit(sw::Shader::OPCODE_LOG2, result, arg); break;
1168 case EOpSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_SQRT, result, arg); break;
1169 case EOpInverseSqrt: if(visit == PostVisit) emit(sw::Shader::OPCODE_RSQ, result, arg); break;
1170 case EOpAbs: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_ABS, result), result, arg); break;
1171 case EOpSign: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_SGN, result), result, arg); break;
1172 case EOpFloor: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOOR, result, arg); break;
1173 case EOpTrunc: if(visit == PostVisit) emit(sw::Shader::OPCODE_TRUNC, result, arg); break;
1174 case EOpRound: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUND, result, arg); break;
1175 case EOpRoundEven: if(visit == PostVisit) emit(sw::Shader::OPCODE_ROUNDEVEN, result, arg); break;
1176 case EOpCeil: if(visit == PostVisit) emit(sw::Shader::OPCODE_CEIL, result, arg, result); break;
1177 case EOpFract: if(visit == PostVisit) emit(sw::Shader::OPCODE_FRC, result, arg); break;
1178 case EOpIsNan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISNAN, result, arg); break;
1179 case EOpIsInf: if(visit == PostVisit) emit(sw::Shader::OPCODE_ISINF, result, arg); break;
1180 case EOpLength: if(visit == PostVisit) emit(sw::Shader::OPCODE_LEN(dim(arg)), result, arg); break;
1181 case EOpNormalize: if(visit == PostVisit) emit(sw::Shader::OPCODE_NRM(dim(arg)), result, arg); break;
1182 case EOpDFdx: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDX, result, arg); break;
1183 case EOpDFdy: if(visit == PostVisit) emit(sw::Shader::OPCODE_DFDY, result, arg); break;
1184 case EOpFwidth: if(visit == PostVisit) emit(sw::Shader::OPCODE_FWIDTH, result, arg); break;
1185 case EOpAny: if(visit == PostVisit) emit(sw::Shader::OPCODE_ANY, result, arg); break;
1186 case EOpAll: if(visit == PostVisit) emit(sw::Shader::OPCODE_ALL, result, arg); break;
1187 case EOpFloatBitsToInt: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOINT, result, arg); break;
1188 case EOpFloatBitsToUint: if(visit == PostVisit) emit(sw::Shader::OPCODE_FLOATBITSTOUINT, result, arg); break;
1189 case EOpIntBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_INTBITSTOFLOAT, result, arg); break;
1190 case EOpUintBitsToFloat: if(visit == PostVisit) emit(sw::Shader::OPCODE_UINTBITSTOFLOAT, result, arg); break;
1191 case EOpPackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKSNORM2x16, result, arg); break;
1192 case EOpPackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKUNORM2x16, result, arg); break;
1193 case EOpPackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_PACKHALF2x16, result, arg); break;
1194 case EOpUnpackSnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKSNORM2x16, result, arg); break;
1195 case EOpUnpackUnorm2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKUNORM2x16, result, arg); break;
1196 case EOpUnpackHalf2x16: if(visit == PostVisit) emit(sw::Shader::OPCODE_UNPACKHALF2x16, result, arg); break;
1197 case EOpTranspose:
1198 if(visit == PostVisit)
1199 {
1200 int numCols = arg->getNominalSize();
1201 int numRows = arg->getSecondarySize();
1202 for(int i = 0; i < numCols; ++i)
1203 {
1204 for(int j = 0; j < numRows; ++j)
1205 {
1206 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, j, arg, i);
1207 mov->src[0].swizzle = 0x55 * j;
1208 mov->dst.mask = 1 << i;
1209 }
1210 }
1211 }
1212 break;
1213 case EOpDeterminant:
1214 if(visit == PostVisit)
1215 {
1216 int size = arg->getNominalSize();
1217 ASSERT(size == arg->getSecondarySize());
1218
1219 emitDeterminant(result, arg, size);
1220 }
1221 break;
1222 case EOpInverse:
1223 if(visit == PostVisit)
1224 {
1225 int size = arg->getNominalSize();
1226 ASSERT(size == arg->getSecondarySize());
1227
1228 // Compute transposed matrix of cofactors
1229 for(int i = 0; i < size; ++i)
1230 {
1231 for(int j = 0; j < size; ++j)
1232 {
1233 // For a 2x2 matrix, the cofactor is simply a transposed move or negate
1234 // For a 3x3 or 4x4 matrix, the cofactor is a transposed determinant
1235 emitDeterminant(result, arg, size - 1, j, i, i, j);
1236 }
1237 }
1238
1239 // Compute 1 / determinant
1240 Temporary invDet(this);
1241 emitDeterminant(&invDet, arg, size);
1242 Constant one(1.0f, 1.0f, 1.0f, 1.0f);
1243 Instruction *div = emit(sw::Shader::OPCODE_DIV, &invDet, &one, &invDet);
1244 div->src[1].swizzle = 0x00; // xxxx
1245
1246 // Divide transposed matrix of cofactors by determinant
1247 for(int i = 0; i < size; ++i)
1248 {
1249 emit(sw::Shader::OPCODE_MUL, result, i, result, i, &invDet);
1250 }
1251 }
1252 break;
1253 default: UNREACHABLE(node->getOp());
1254 }
1255
1256 return true;
1257 }
1258
1259 bool OutputASM::visitAggregate(Visit visit, TIntermAggregate *node)
1260 {
1261 if(currentScope != emitScope && node->getOp() != EOpFunction && node->getOp() != EOpSequence)
1262 {
1263 return false;
1264 }
1265
1266 Constant zero(0.0f, 0.0f, 0.0f, 0.0f);
1267
1268 TIntermTyped *result = node;
1269 const TType &resultType = node->getType();
1270 TIntermSequence &arg = node->getSequence();
1271 size_t argumentCount = arg.size();
1272
1273 switch(node->getOp())
1274 {
1275 case EOpSequence: break;
1276 case EOpDeclaration: break;
1277 case EOpInvariantDeclaration: break;
1278 case EOpPrototype: break;
1279 case EOpComma:
1280 if(visit == PostVisit)
1281 {
1282 copy(result, arg[1]);
1283 }
1284 break;
1285 case EOpFunction:
1286 if(visit == PreVisit)
1287 {
1288 const TString &name = node->getName();
1289
1290 if(emitScope == FUNCTION)
1291 {
1292 if(functionArray.size() > 1) // No need for a label when there's only main()
1293 {
1294 Instruction *label = emit(sw::Shader::OPCODE_LABEL);
1295 label->dst.type = sw::Shader::PARAMETER_LABEL;
1296
1297 const Function *function = findFunction(name);
1298 ASSERT(function); // Should have been added during global pass
1299 label->dst.index = function->label;
1300 currentFunction = function->label;
1301 }
1302 }
1303 else if(emitScope == GLOBAL)
1304 {
1305 if(name != "main(")
1306 {
1307 TIntermSequence &arguments = node->getSequence()[0]->getAsAggregate()->getSequence();
1308 functionArray.push_back(Function(functionArray.size(), name, &arguments, node));
1309 }
1310 }
1311 else UNREACHABLE(emitScope);
1312
1313 currentScope = FUNCTION;
1314 }
1315 else if(visit == PostVisit)
1316 {
1317 if(emitScope == FUNCTION)
1318 {
1319 if(functionArray.size() > 1) // No need to return when there's only main()
1320 {
1321 emit(sw::Shader::OPCODE_RET);
1322 }
1323 }
1324
1325 currentScope = GLOBAL;
1326 }
1327 break;
1328 case EOpFunctionCall:
1329 if(visit == PostVisit)
1330 {
1331 if(node->isUserDefined())
1332 {
1333 const TString &name = node->getName();
1334 const Function *function = findFunction(name);
1335
1336 if(!function)
1337 {
1338 mContext.error(node->getLine(), "function definition not found", name.c_str());
1339 return false;
1340 }
1341
1342 TIntermSequence &arguments = *function->arg;
1343
1344 for(size_t i = 0; i < argumentCount; i++)
1345 {
1346 TIntermTyped *in = arguments[i]->getAsTyped();
1347
1348 if(in->getQualifier() == EvqIn ||
1349 in->getQualifier() == EvqInOut ||
1350 in->getQualifier() == EvqConstReadOnly)
1351 {
1352 copy(in, arg[i]);
1353 }
1354 }
1355
1356 Instruction *call = emit(sw::Shader::OPCODE_CALL);
1357 call->dst.type = sw::Shader::PARAMETER_LABEL;
1358 call->dst.index = function->label;
1359
1360 if(function->ret && function->ret->getType().getBasicType() != EbtVoid)
1361 {
1362 copy(result, function->ret);
1363 }
1364
1365 for(size_t i = 0; i < argumentCount; i++)
1366 {
1367 TIntermTyped *argument = arguments[i]->getAsTyped();
1368 TIntermTyped *out = arg[i]->getAsTyped();
1369
1370 if(argument->getQualifier() == EvqOut ||
1371 argument->getQualifier() == EvqInOut)
1372 {
Nicolas Capens5da2d3f2016-06-11 00:41:49 -04001373 assignLvalue(out, argument);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001374 }
1375 }
1376 }
1377 else
1378 {
1379 const TextureFunction textureFunction(node->getName());
Nicolas Capensa0b57832017-11-07 13:07:53 -05001380 TIntermTyped *s = arg[0]->getAsTyped();
Nicolas Capens0bac2852016-05-07 06:09:58 -04001381 TIntermTyped *t = arg[1]->getAsTyped();
1382
1383 Temporary coord(this);
1384
1385 if(textureFunction.proj)
1386 {
Nicolas Capens0484c792016-06-13 22:02:36 -04001387 Instruction *rcp = emit(sw::Shader::OPCODE_RCPX, &coord, arg[1]);
1388 rcp->src[0].swizzle = 0x55 * (t->getNominalSize() - 1);
1389 rcp->dst.mask = 0x7;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001390
Nicolas Capens0484c792016-06-13 22:02:36 -04001391 Instruction *mul = emit(sw::Shader::OPCODE_MUL, &coord, arg[1], &coord);
1392 mul->dst.mask = 0x7;
Nicolas Capensa0b57832017-11-07 13:07:53 -05001393
1394 if(IsShadowSampler(s->getBasicType()))
1395 {
1396 ASSERT(s->getBasicType() == EbtSampler2DShadow);
1397 Instruction *mov = emit(sw::Shader::OPCODE_MOV, &coord, &coord);
1398 mov->src[0].swizzle = 0xA4;
1399 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001400 }
1401 else
1402 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001403 Instruction *mov = emit(sw::Shader::OPCODE_MOV, &coord, arg[1]);
1404
1405 if(IsShadowSampler(s->getBasicType()) && t->getNominalSize() == 3)
1406 {
1407 ASSERT(s->getBasicType() == EbtSampler2DShadow);
1408 mov->src[0].swizzle = 0xA4;
1409 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001410 }
1411
1412 switch(textureFunction.method)
1413 {
1414 case TextureFunction::IMPLICIT:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001415 if(!textureFunction.offset)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001416 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001417 if(argumentCount == 2)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001418 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001419 emit(sw::Shader::OPCODE_TEX, result, &coord, s);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001420 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001421 else if(argumentCount == 3) // Bias
Nicolas Capens0bac2852016-05-07 06:09:58 -04001422 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001423 emit(sw::Shader::OPCODE_TEXBIAS, result, &coord, s, arg[2]);
1424 }
1425 else UNREACHABLE(argumentCount);
1426 }
1427 else // Offset
1428 {
1429 if(argumentCount == 3)
1430 {
1431 emit(sw::Shader::OPCODE_TEXOFFSET, result, &coord, s, arg[2]);
1432 }
1433 else if(argumentCount == 4) // Bias
1434 {
1435 emit(sw::Shader::OPCODE_TEXOFFSETBIAS, result, &coord, s, arg[2], arg[3]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001436 }
1437 else UNREACHABLE(argumentCount);
1438 }
1439 break;
1440 case TextureFunction::LOD:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001441 if(!textureFunction.offset && argumentCount == 3)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001442 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001443 emit(sw::Shader::OPCODE_TEXLOD, result, &coord, s, arg[2]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001444 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001445 else if(argumentCount == 4) // Offset
1446 {
1447 emit(sw::Shader::OPCODE_TEXLODOFFSET, result, &coord, s, arg[3], arg[2]);
1448 }
1449 else UNREACHABLE(argumentCount);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001450 break;
1451 case TextureFunction::FETCH:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001452 if(!textureFunction.offset && argumentCount == 3)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001453 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001454 emit(sw::Shader::OPCODE_TEXELFETCH, result, &coord, s, arg[2]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001455 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001456 else if(argumentCount == 4) // Offset
1457 {
1458 emit(sw::Shader::OPCODE_TEXELFETCHOFFSET, result, &coord, s, arg[3], arg[2]);
1459 }
1460 else UNREACHABLE(argumentCount);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001461 break;
1462 case TextureFunction::GRAD:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001463 if(!textureFunction.offset && argumentCount == 4)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001464 {
Nicolas Capensa0b57832017-11-07 13:07:53 -05001465 emit(sw::Shader::OPCODE_TEXGRAD, result, &coord, s, arg[2], arg[3]);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001466 }
Nicolas Capensa0b57832017-11-07 13:07:53 -05001467 else if(argumentCount == 5) // Offset
1468 {
1469 emit(sw::Shader::OPCODE_TEXGRADOFFSET, result, &coord, s, arg[2], arg[3], arg[4]);
1470 }
1471 else UNREACHABLE(argumentCount);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001472 break;
Alexis Hetu46768622018-01-16 22:09:28 -05001473 case TextureFunction::RECT:
1474 emit(sw::Shader::OPCODE_TEXRECT, result, &coord, s);
1475 break;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001476 case TextureFunction::SIZE:
Nicolas Capensa0b57832017-11-07 13:07:53 -05001477 emit(sw::Shader::OPCODE_TEXSIZE, result, arg[1], s);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001478 break;
1479 default:
1480 UNREACHABLE(textureFunction.method);
1481 }
1482 }
1483 }
1484 break;
1485 case EOpParameters:
1486 break;
1487 case EOpConstructFloat:
1488 case EOpConstructVec2:
1489 case EOpConstructVec3:
1490 case EOpConstructVec4:
1491 case EOpConstructBool:
1492 case EOpConstructBVec2:
1493 case EOpConstructBVec3:
1494 case EOpConstructBVec4:
1495 case EOpConstructInt:
1496 case EOpConstructIVec2:
1497 case EOpConstructIVec3:
1498 case EOpConstructIVec4:
1499 case EOpConstructUInt:
1500 case EOpConstructUVec2:
1501 case EOpConstructUVec3:
1502 case EOpConstructUVec4:
1503 if(visit == PostVisit)
1504 {
1505 int component = 0;
Alexis Hetu2a198552016-09-27 20:50:45 -04001506 int arrayMaxIndex = result->isArray() ? result->getArraySize() - 1 : 0;
1507 int arrayComponents = result->getType().getElementSize();
Nicolas Capens0bac2852016-05-07 06:09:58 -04001508 for(size_t i = 0; i < argumentCount; i++)
1509 {
1510 TIntermTyped *argi = arg[i]->getAsTyped();
1511 int size = argi->getNominalSize();
Alexis Hetu2a198552016-09-27 20:50:45 -04001512 int arrayIndex = std::min(component / arrayComponents, arrayMaxIndex);
1513 int swizzle = component - (arrayIndex * arrayComponents);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001514
1515 if(!argi->isMatrix())
1516 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001517 Instruction *mov = emitCast(result, arrayIndex, argi, 0);
1518 mov->dst.mask = (0xF << swizzle) & 0xF;
1519 mov->src[0].swizzle = readSwizzle(argi, size) << (swizzle * 2);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001520
1521 component += size;
1522 }
Alexis Hetu38338612018-01-18 15:53:36 -05001523 else if(!result->isMatrix()) // Construct a non matrix from a matrix
1524 {
1525 Instruction *mov = emitCast(result, arrayIndex, argi, 0);
1526 mov->dst.mask = (0xF << swizzle) & 0xF;
1527 mov->src[0].swizzle = readSwizzle(argi, size) << (swizzle * 2);
1528
1529 // At most one more instruction when constructing a vec3 from a mat2 or a vec4 from a mat2/mat3
1530 if(result->getNominalSize() > size)
1531 {
1532 Instruction *mov = emitCast(result, arrayIndex, argi, 1);
1533 mov->dst.mask = (0xF << (swizzle + size)) & 0xF;
1534 // mat2: xxxy (0x40), mat3: xxxx (0x00)
1535 mov->src[0].swizzle = ((size == 2) ? 0x40 : 0x00) << (swizzle * 2);
1536 }
1537
1538 component += size;
1539 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001540 else // Matrix
1541 {
1542 int column = 0;
1543
1544 while(component < resultType.getNominalSize())
1545 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001546 Instruction *mov = emitCast(result, arrayIndex, argi, column);
1547 mov->dst.mask = (0xF << swizzle) & 0xF;
1548 mov->src[0].swizzle = readSwizzle(argi, size) << (swizzle * 2);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001549
1550 column++;
1551 component += size;
1552 }
1553 }
1554 }
1555 }
1556 break;
1557 case EOpConstructMat2:
1558 case EOpConstructMat2x3:
1559 case EOpConstructMat2x4:
1560 case EOpConstructMat3x2:
1561 case EOpConstructMat3:
1562 case EOpConstructMat3x4:
1563 case EOpConstructMat4x2:
1564 case EOpConstructMat4x3:
1565 case EOpConstructMat4:
1566 if(visit == PostVisit)
1567 {
1568 TIntermTyped *arg0 = arg[0]->getAsTyped();
1569 const int outCols = result->getNominalSize();
1570 const int outRows = result->getSecondarySize();
1571
1572 if(arg0->isScalar() && arg.size() == 1) // Construct scale matrix
1573 {
1574 for(int i = 0; i < outCols; i++)
1575 {
Alexis Hetu7208e932016-06-02 11:19:24 -04001576 emit(sw::Shader::OPCODE_MOV, result, i, &zero);
Nicolas Capens0bac2852016-05-07 06:09:58 -04001577 Instruction *mov = emitCast(result, i, arg0, 0);
1578 mov->dst.mask = 1 << i;
1579 ASSERT(mov->src[0].swizzle == 0x00);
1580 }
1581 }
1582 else if(arg0->isMatrix())
1583 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001584 int arraySize = result->isArray() ? result->getArraySize() : 1;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001585
Alexis Hetu2a198552016-09-27 20:50:45 -04001586 for(int n = 0; n < arraySize; n++)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001587 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001588 TIntermTyped *argi = arg[n]->getAsTyped();
1589 const int inCols = argi->getNominalSize();
1590 const int inRows = argi->getSecondarySize();
Nicolas Capens0bac2852016-05-07 06:09:58 -04001591
Alexis Hetu2a198552016-09-27 20:50:45 -04001592 for(int i = 0; i < outCols; i++)
Nicolas Capens0bac2852016-05-07 06:09:58 -04001593 {
Alexis Hetu2a198552016-09-27 20:50:45 -04001594 if(i >= inCols || outRows > inRows)
1595 {
1596 // Initialize to identity matrix
1597 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));
1598 emitCast(result, i + n * outCols, &col, 0);
1599 }
1600
1601 if(i < inCols)
1602 {
1603 Instruction *mov = emitCast(result, i + n * outCols, argi, i);
1604 mov->dst.mask = 0xF >> (4 - inRows);
1605 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04001606 }
1607 }
1608 }
1609 else
1610 {
1611 int column = 0;
1612 int row = 0;
1613
1614 for(size_t i = 0; i < argumentCount; i++)
1615 {
1616 TIntermTyped *argi = arg[i]->getAsTyped();
1617 int size = argi->getNominalSize();
1618 int element = 0;
1619
1620 while(element < size)
1621 {
1622 Instruction *mov = emitCast(result, column, argi, 0);
1623 mov->dst.mask = (0xF << row) & 0xF;
1624 mov->src[0].swizzle = (readSwizzle(argi, size) << (row * 2)) + 0x55 * element;
1625
1626 int end = row + size - element;
1627 column = end >= outRows ? column + 1 : column;
1628 element = element + outRows - row;
1629 row = end >= outRows ? 0 : end;
1630 }
1631 }
1632 }
1633 }
1634 break;
1635 case EOpConstructStruct:
1636 if(visit == PostVisit)
1637 {
1638 int offset = 0;
1639 for(size_t i = 0; i < argumentCount; i++)
1640 {
1641 TIntermTyped *argi = arg[i]->getAsTyped();
1642 int size = argi->totalRegisterCount();
1643
1644 for(int index = 0; index < size; index++)
1645 {
1646 Instruction *mov = emit(sw::Shader::OPCODE_MOV, result, index + offset, argi, index);
1647 mov->dst.mask = writeMask(result, offset + index);
1648 }
1649
1650 offset += size;
1651 }
1652 }
1653 break;
1654 case EOpLessThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LT, result, arg[0], arg[1]); break;
1655 case EOpGreaterThan: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GT, result, arg[0], arg[1]); break;
1656 case EOpLessThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_LE, result, arg[0], arg[1]); break;
1657 case EOpGreaterThanEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_GE, result, arg[0], arg[1]); break;
1658 case EOpVectorEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_EQ, result, arg[0], arg[1]); break;
1659 case EOpVectorNotEqual: if(visit == PostVisit) emitCmp(sw::Shader::CONTROL_NE, result, arg[0], arg[1]); break;
1660 case EOpMod: if(visit == PostVisit) emit(sw::Shader::OPCODE_MOD, result, arg[0], arg[1]); break;
1661 case EOpModf:
1662 if(visit == PostVisit)
1663 {
1664 TIntermTyped* arg1 = arg[1]->getAsTyped();
1665 emit(sw::Shader::OPCODE_TRUNC, arg1, arg[0]);
1666 assignLvalue(arg1, arg1);
1667 emitBinary(sw::Shader::OPCODE_SUB, result, arg[0], arg1);
1668 }
1669 break;
1670 case EOpPow: if(visit == PostVisit) emit(sw::Shader::OPCODE_POW, result, arg[0], arg[1]); break;
1671 case EOpAtan: if(visit == PostVisit) emit(sw::Shader::OPCODE_ATAN2, result, arg[0], arg[1]); break;
1672 case EOpMin: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, arg[0], arg[1]); break;
1673 case EOpMax: if(visit == PostVisit) emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]); break;
1674 case EOpClamp:
1675 if(visit == PostVisit)
1676 {
1677 emit(getOpcode(sw::Shader::OPCODE_MAX, result), result, arg[0], arg[1]);
1678 emit(getOpcode(sw::Shader::OPCODE_MIN, result), result, result, arg[2]);
1679 }
1680 break;
Alexis Hetuc4711fa2018-01-12 11:59:35 -05001681 case EOpMix:
1682 if(visit == PostVisit)
1683 {
1684 if(arg[2]->getAsTyped()->getBasicType() == EbtBool)
1685 {
1686 emit(sw::Shader::OPCODE_SELECT, result, arg[2], arg[1], arg[0]);
1687 }
1688 else
1689 {
1690 emit(sw::Shader::OPCODE_LRP, result, arg[2], arg[1], arg[0]);
1691 }
1692 }
1693 break;
Nicolas Capens0bac2852016-05-07 06:09:58 -04001694 case EOpStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_STEP, result, arg[0], arg[1]); break;
1695 case EOpSmoothStep: if(visit == PostVisit) emit(sw::Shader::OPCODE_SMOOTH, result, arg[0], arg[1], arg[2]); break;
1696 case EOpDistance: if(visit == PostVisit) emit(sw::Shader::OPCODE_DIST(dim(arg[0])), result, arg[0], arg[1]); break;
1697 case EOpDot: if(visit == PostVisit) emit(sw::Shader::OPCODE_DP(dim(arg[0])), result, arg[0], arg[1]); break;
1698 case EOpCross: if(visit == PostVisit) emit(sw::Shader::OPCODE_CRS, result, arg[0], arg[1]); break;
1699 case EOpFaceForward: if(visit == PostVisit) emit(sw::Shader::OPCODE_FORWARD(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1700 case EOpReflect: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFLECT(dim(arg[0])), result, arg[0], arg[1]); break;
1701 case EOpRefract: if(visit == PostVisit) emit(sw::Shader::OPCODE_REFRACT(dim(arg[0])), result, arg[0], arg[1], arg[2]); break;
1702 case EOpMul:
1703 if(visit == PostVisit)
1704 {
1705 TIntermTyped *arg0 = arg[0]->getAsTyped();
Alexis Hetue97a31e2016-11-14 14:10:47 -05001706 ASSERT((arg0->getNominalSize() == arg[1]->getAsTyped()->getNominalSize()) &&
1707 (arg0->getSecondarySize() == arg[1]->getAsTyped()->getSecondarySize()));
Nicolas Capens0bac2852016-05-07 06:09:58 -04001708
1709 int size = arg0->getNominalSize();
1710 for(int i = 0; i < size; i++)
1711 {
1712 emit(sw::Shader::OPCODE_MUL, result, i, arg[0], i, arg[1], i);
1713 }
1714 }
1715 break;
1716 case EOpOuterProduct:
1717 if(visit == PostVisit)
1718 {
1719 for(int i = 0; i < dim(arg[1]); i++)
1720 {
1721 Instruction *mul = emit(sw::Shader::OPCODE_MUL, result, i, arg[0], 0, arg[1]);
1722 mul->src[1].swizzle = 0x55 * i;
1723 }
1724 }
1725 break;
1726 default: UNREACHABLE(node->getOp());
1727 }
1728
1729 return true;
1730 }
1731
1732 bool OutputASM::visitSelection(Visit visit, TIntermSelection *node)
1733 {
1734 if(currentScope != emitScope)
1735 {
1736 return false;
1737 }
1738
1739 TIntermTyped *condition = node->getCondition();
1740 TIntermNode *trueBlock = node->getTrueBlock();
1741 TIntermNode *falseBlock = node->getFalseBlock();
1742 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
1743
1744 condition->traverse(this);
1745
1746 if(node->usesTernaryOperator())
1747 {
1748 if(constantCondition)
1749 {
1750 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1751
1752 if(trueCondition)
1753 {
1754 trueBlock->traverse(this);
1755 copy(node, trueBlock);
1756 }
1757 else
1758 {
1759 falseBlock->traverse(this);
1760 copy(node, falseBlock);
1761 }
1762 }
1763 else if(trivial(node, 6)) // Fast to compute both potential results and no side effects
1764 {
1765 trueBlock->traverse(this);
1766 falseBlock->traverse(this);
1767 emit(sw::Shader::OPCODE_SELECT, node, condition, trueBlock, falseBlock);
1768 }
1769 else
1770 {
1771 emit(sw::Shader::OPCODE_IF, 0, condition);
1772
1773 if(trueBlock)
1774 {
1775 trueBlock->traverse(this);
1776 copy(node, trueBlock);
1777 }
1778
1779 if(falseBlock)
1780 {
1781 emit(sw::Shader::OPCODE_ELSE);
1782 falseBlock->traverse(this);
1783 copy(node, falseBlock);
1784 }
1785
1786 emit(sw::Shader::OPCODE_ENDIF);
1787 }
1788 }
1789 else // if/else statement
1790 {
1791 if(constantCondition)
1792 {
1793 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
1794
1795 if(trueCondition)
1796 {
1797 if(trueBlock)
1798 {
1799 trueBlock->traverse(this);
1800 }
1801 }
1802 else
1803 {
1804 if(falseBlock)
1805 {
1806 falseBlock->traverse(this);
1807 }
1808 }
1809 }
1810 else
1811 {
1812 emit(sw::Shader::OPCODE_IF, 0, condition);
1813
1814 if(trueBlock)
1815 {
1816 trueBlock->traverse(this);
1817 }
1818
1819 if(falseBlock)
1820 {
1821 emit(sw::Shader::OPCODE_ELSE);
1822 falseBlock->traverse(this);
1823 }
1824
1825 emit(sw::Shader::OPCODE_ENDIF);
1826 }
1827 }
1828
1829 return false;
1830 }
1831
1832 bool OutputASM::visitLoop(Visit visit, TIntermLoop *node)
1833 {
1834 if(currentScope != emitScope)
1835 {
1836 return false;
1837 }
1838
1839 unsigned int iterations = loopCount(node);
1840
1841 if(iterations == 0)
1842 {
1843 return false;
1844 }
1845
1846 bool unroll = (iterations <= 4);
1847
1848 if(unroll)
1849 {
1850 LoopUnrollable loopUnrollable;
1851 unroll = loopUnrollable.traverse(node);
1852 }
1853
1854 TIntermNode *init = node->getInit();
1855 TIntermTyped *condition = node->getCondition();
1856 TIntermTyped *expression = node->getExpression();
1857 TIntermNode *body = node->getBody();
1858 Constant True(true);
1859
1860 if(node->getType() == ELoopDoWhile)
1861 {
1862 Temporary iterate(this);
1863 emit(sw::Shader::OPCODE_MOV, &iterate, &True);
1864
1865 emit(sw::Shader::OPCODE_WHILE, 0, &iterate); // FIXME: Implement real do-while
1866
1867 if(body)
1868 {
1869 body->traverse(this);
1870 }
1871
1872 emit(sw::Shader::OPCODE_TEST);
1873
1874 condition->traverse(this);
1875 emit(sw::Shader::OPCODE_MOV, &iterate, condition);
1876
1877 emit(sw::Shader::OPCODE_ENDWHILE);
1878 }
1879 else
1880 {
1881 if(init)
1882 {
1883 init->traverse(this);
1884 }
1885
1886 if(unroll)
1887 {
1888 for(unsigned int i = 0; i < iterations; i++)
1889 {
1890 // condition->traverse(this); // Condition could contain statements, but not in an unrollable loop
1891
1892 if(body)
1893 {
1894 body->traverse(this);
1895 }
1896
1897 if(expression)
1898 {
1899 expression->traverse(this);
1900 }
1901 }
1902 }
1903 else
1904 {
1905 if(condition)
1906 {
1907 condition->traverse(this);
1908 }
1909 else
1910 {
1911 condition = &True;
1912 }
1913
1914 emit(sw::Shader::OPCODE_WHILE, 0, condition);
1915
1916 if(body)
1917 {
1918 body->traverse(this);
1919 }
1920
1921 emit(sw::Shader::OPCODE_TEST);
1922
1923 if(expression)
1924 {
1925 expression->traverse(this);
1926 }
1927
1928 if(condition)
1929 {
1930 condition->traverse(this);
1931 }
1932
1933 emit(sw::Shader::OPCODE_ENDWHILE);
1934 }
1935 }
1936
1937 return false;
1938 }
1939
1940 bool OutputASM::visitBranch(Visit visit, TIntermBranch *node)
1941 {
1942 if(currentScope != emitScope)
1943 {
1944 return false;
1945 }
1946
1947 switch(node->getFlowOp())
1948 {
1949 case EOpKill: if(visit == PostVisit) emit(sw::Shader::OPCODE_DISCARD); break;
1950 case EOpBreak: if(visit == PostVisit) emit(sw::Shader::OPCODE_BREAK); break;
1951 case EOpContinue: if(visit == PostVisit) emit(sw::Shader::OPCODE_CONTINUE); break;
1952 case EOpReturn:
1953 if(visit == PostVisit)
1954 {
1955 TIntermTyped *value = node->getExpression();
1956
1957 if(value)
1958 {
1959 copy(functionArray[currentFunction].ret, value);
1960 }
1961
1962 emit(sw::Shader::OPCODE_LEAVE);
1963 }
1964 break;
1965 default: UNREACHABLE(node->getFlowOp());
1966 }
1967
1968 return true;
1969 }
1970
Alexis Hetu9aa83a92016-05-02 17:34:46 -04001971 bool OutputASM::visitSwitch(Visit visit, TIntermSwitch *node)
1972 {
1973 if(currentScope != emitScope)
1974 {
1975 return false;
1976 }
1977
1978 TIntermTyped* switchValue = node->getInit();
1979 TIntermAggregate* opList = node->getStatementList();
1980
1981 if(!switchValue || !opList)
1982 {
1983 return false;
1984 }
1985
1986 switchValue->traverse(this);
1987
1988 emit(sw::Shader::OPCODE_SWITCH);
1989
1990 TIntermSequence& sequence = opList->getSequence();
1991 TIntermSequence::iterator it = sequence.begin();
1992 TIntermSequence::iterator defaultIt = sequence.end();
1993 int nbCases = 0;
1994 for(; it != sequence.end(); ++it)
1995 {
1996 TIntermCase* currentCase = (*it)->getAsCaseNode();
1997 if(currentCase)
1998 {
1999 TIntermSequence::iterator caseIt = it;
2000
2001 TIntermTyped* condition = currentCase->getCondition();
2002 if(condition) // non default case
2003 {
2004 if(nbCases != 0)
2005 {
2006 emit(sw::Shader::OPCODE_ELSE);
2007 }
2008
2009 condition->traverse(this);
2010 Temporary result(this);
2011 emitBinary(sw::Shader::OPCODE_EQ, &result, switchValue, condition);
2012 emit(sw::Shader::OPCODE_IF, 0, &result);
2013 nbCases++;
2014
Nicolas Capens6d123312018-01-08 12:57:52 -05002015 // Emit the code for this case and all subsequent cases until we hit a break statement.
2016 // TODO: This can repeat a lot of code for switches with many fall-through cases.
Alexis Hetu9aa83a92016-05-02 17:34:46 -04002017 for(++caseIt; caseIt != sequence.end(); ++caseIt)
2018 {
2019 (*caseIt)->traverse(this);
Nicolas Capens6d123312018-01-08 12:57:52 -05002020
2021 // Stop if we encounter an unconditional branch (break, continue, return, or kill).
2022 // TODO: This doesn't work if the statement is at a deeper scope level (e.g. {break;}).
2023 // Note that this eliminates useless operations but shouldn't affect correctness.
2024 if((*caseIt)->getAsBranchNode())
Alexis Hetu9aa83a92016-05-02 17:34:46 -04002025 {
2026 break;
2027 }
2028 }
2029 }
2030 else
2031 {
2032 defaultIt = it; // The default case might not be the last case, keep it for last
2033 }
2034 }
2035 }
2036
2037 // If there's a default case, traverse it here
2038 if(defaultIt != sequence.end())
2039 {
2040 emit(sw::Shader::OPCODE_ELSE);
2041 for(++defaultIt; defaultIt != sequence.end(); ++defaultIt)
2042 {
2043 (*defaultIt)->traverse(this);
2044 if((*defaultIt)->getAsBranchNode()) // Kill, Break, Continue or Return
2045 {
2046 break;
2047 }
2048 }
2049 }
2050
2051 for(int i = 0; i < nbCases; ++i)
2052 {
2053 emit(sw::Shader::OPCODE_ENDIF);
2054 }
2055
2056 emit(sw::Shader::OPCODE_ENDSWITCH);
2057
2058 return false;
2059 }
2060
Nicolas Capens0bac2852016-05-07 06:09:58 -04002061 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2, TIntermNode *src3, TIntermNode *src4)
2062 {
2063 return emit(op, dst, 0, src0, 0, src1, 0, src2, 0, src3, 0, src4, 0);
2064 }
2065
2066 Instruction *OutputASM::emit(sw::Shader::Opcode op, TIntermTyped *dst, int dstIndex, TIntermNode *src0, int index0, TIntermNode *src1, int index1,
2067 TIntermNode *src2, int index2, TIntermNode *src3, int index3, TIntermNode *src4, int index4)
2068 {
2069 Instruction *instruction = new Instruction(op);
2070
2071 if(dst)
2072 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002073 destination(instruction->dst, dst, dstIndex);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002074 }
2075
Alexis Hetu929c6b02017-11-07 16:04:25 -05002076 if(src0)
2077 {
2078 TIntermTyped* src = src0->getAsTyped();
2079 instruction->dst.partialPrecision = src && (src->getPrecision() <= EbpLow);
2080 }
2081
Nicolas Capens0530b452017-11-15 16:39:47 -05002082 source(instruction->src[0], src0, index0);
2083 source(instruction->src[1], src1, index1);
2084 source(instruction->src[2], src2, index2);
2085 source(instruction->src[3], src3, index3);
2086 source(instruction->src[4], src4, index4);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002087
2088 shader->append(instruction);
2089
2090 return instruction;
2091 }
2092
2093 Instruction *OutputASM::emitCast(TIntermTyped *dst, TIntermTyped *src)
2094 {
2095 return emitCast(dst, 0, src, 0);
2096 }
2097
2098 Instruction *OutputASM::emitCast(TIntermTyped *dst, int dstIndex, TIntermTyped *src, int srcIndex)
2099 {
2100 switch(src->getBasicType())
2101 {
2102 case EbtBool:
2103 switch(dst->getBasicType())
2104 {
2105 case EbtInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
2106 case EbtUInt: return emit(sw::Shader::OPCODE_B2I, dst, dstIndex, src, srcIndex);
2107 case EbtFloat: return emit(sw::Shader::OPCODE_B2F, dst, dstIndex, src, srcIndex);
2108 default: break;
2109 }
2110 break;
2111 case EbtInt:
2112 switch(dst->getBasicType())
2113 {
2114 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
2115 case EbtFloat: return emit(sw::Shader::OPCODE_I2F, dst, dstIndex, src, srcIndex);
2116 default: break;
2117 }
2118 break;
2119 case EbtUInt:
2120 switch(dst->getBasicType())
2121 {
2122 case EbtBool: return emit(sw::Shader::OPCODE_I2B, dst, dstIndex, src, srcIndex);
2123 case EbtFloat: return emit(sw::Shader::OPCODE_U2F, dst, dstIndex, src, srcIndex);
2124 default: break;
2125 }
2126 break;
2127 case EbtFloat:
2128 switch(dst->getBasicType())
2129 {
2130 case EbtBool: return emit(sw::Shader::OPCODE_F2B, dst, dstIndex, src, srcIndex);
2131 case EbtInt: return emit(sw::Shader::OPCODE_F2I, dst, dstIndex, src, srcIndex);
2132 case EbtUInt: return emit(sw::Shader::OPCODE_F2U, dst, dstIndex, src, srcIndex);
2133 default: break;
2134 }
2135 break;
2136 default:
2137 break;
2138 }
2139
2140 ASSERT((src->getBasicType() == dst->getBasicType()) ||
2141 ((src->getBasicType() == EbtInt) && (dst->getBasicType() == EbtUInt)) ||
2142 ((src->getBasicType() == EbtUInt) && (dst->getBasicType() == EbtInt)));
2143
2144 return emit(sw::Shader::OPCODE_MOV, dst, dstIndex, src, srcIndex);
2145 }
2146
2147 void OutputASM::emitBinary(sw::Shader::Opcode op, TIntermTyped *dst, TIntermNode *src0, TIntermNode *src1, TIntermNode *src2)
2148 {
2149 for(int index = 0; index < dst->elementRegisterCount(); index++)
2150 {
2151 emit(op, dst, index, src0, index, src1, index, src2, index);
2152 }
2153 }
2154
2155 void OutputASM::emitAssign(sw::Shader::Opcode op, TIntermTyped *result, TIntermTyped *lhs, TIntermTyped *src0, TIntermTyped *src1)
2156 {
2157 emitBinary(op, result, src0, src1);
2158 assignLvalue(lhs, result);
2159 }
2160
2161 void OutputASM::emitCmp(sw::Shader::Control cmpOp, TIntermTyped *dst, TIntermNode *left, TIntermNode *right, int index)
2162 {
2163 sw::Shader::Opcode opcode;
2164 switch(left->getAsTyped()->getBasicType())
2165 {
2166 case EbtBool:
2167 case EbtInt:
2168 opcode = sw::Shader::OPCODE_ICMP;
2169 break;
2170 case EbtUInt:
2171 opcode = sw::Shader::OPCODE_UCMP;
2172 break;
2173 default:
2174 opcode = sw::Shader::OPCODE_CMP;
2175 break;
2176 }
2177
2178 Instruction *cmp = emit(opcode, dst, 0, left, index, right, index);
2179 cmp->control = cmpOp;
2180 }
2181
2182 int componentCount(const TType &type, int registers)
2183 {
2184 if(registers == 0)
2185 {
2186 return 0;
2187 }
2188
2189 if(type.isArray() && registers >= type.elementRegisterCount())
2190 {
2191 int index = registers / type.elementRegisterCount();
2192 registers -= index * type.elementRegisterCount();
2193 return index * type.getElementSize() + componentCount(type, registers);
2194 }
2195
2196 if(type.isStruct() || type.isInterfaceBlock())
2197 {
2198 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2199 int elements = 0;
2200
Alexis Hetuda163ed2018-01-03 16:36:14 -05002201 for(const auto &field : fields)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002202 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05002203 const TType &fieldType = *(field->type());
Nicolas Capens0bac2852016-05-07 06:09:58 -04002204
2205 if(fieldType.totalRegisterCount() <= registers)
2206 {
2207 registers -= fieldType.totalRegisterCount();
2208 elements += fieldType.getObjectSize();
2209 }
2210 else // Register within this field
2211 {
2212 return elements + componentCount(fieldType, registers);
2213 }
2214 }
2215 }
2216 else if(type.isMatrix())
2217 {
2218 return registers * type.registerSize();
2219 }
2220
2221 UNREACHABLE(0);
2222 return 0;
2223 }
2224
2225 int registerSize(const TType &type, int registers)
2226 {
2227 if(registers == 0)
2228 {
2229 if(type.isStruct())
2230 {
2231 return registerSize(*((*(type.getStruct()->fields().begin()))->type()), 0);
2232 }
2233 else if(type.isInterfaceBlock())
2234 {
2235 return registerSize(*((*(type.getInterfaceBlock()->fields().begin()))->type()), 0);
2236 }
2237
2238 return type.registerSize();
2239 }
2240
2241 if(type.isArray() && registers >= type.elementRegisterCount())
2242 {
2243 int index = registers / type.elementRegisterCount();
2244 registers -= index * type.elementRegisterCount();
2245 return registerSize(type, registers);
2246 }
2247
2248 if(type.isStruct() || type.isInterfaceBlock())
2249 {
2250 const TFieldList& fields = type.getStruct() ? type.getStruct()->fields() : type.getInterfaceBlock()->fields();
2251 int elements = 0;
2252
Alexis Hetuda163ed2018-01-03 16:36:14 -05002253 for(const auto &field : fields)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002254 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05002255 const TType &fieldType = *(field->type());
Nicolas Capens0bac2852016-05-07 06:09:58 -04002256
2257 if(fieldType.totalRegisterCount() <= registers)
2258 {
2259 registers -= fieldType.totalRegisterCount();
2260 elements += fieldType.getObjectSize();
2261 }
2262 else // Register within this field
2263 {
2264 return registerSize(fieldType, registers);
2265 }
2266 }
2267 }
2268 else if(type.isMatrix())
2269 {
2270 return registerSize(type, 0);
2271 }
2272
2273 UNREACHABLE(0);
2274 return 0;
2275 }
2276
2277 int OutputASM::getBlockId(TIntermTyped *arg)
2278 {
2279 if(arg)
2280 {
2281 const TType &type = arg->getType();
2282 TInterfaceBlock* block = type.getInterfaceBlock();
2283 if(block && (type.getQualifier() == EvqUniform))
2284 {
2285 // Make sure the uniform block is declared
2286 uniformRegister(arg);
2287
2288 const char* blockName = block->name().c_str();
2289
2290 // Fetch uniform block index from array of blocks
2291 for(ActiveUniformBlocks::const_iterator it = shaderObject->activeUniformBlocks.begin(); it != shaderObject->activeUniformBlocks.end(); ++it)
2292 {
2293 if(blockName == it->name)
2294 {
2295 return it->blockId;
2296 }
2297 }
2298
2299 ASSERT(false);
2300 }
2301 }
2302
2303 return -1;
2304 }
2305
2306 OutputASM::ArgumentInfo OutputASM::getArgumentInfo(TIntermTyped *arg, int index)
2307 {
2308 const TType &type = arg->getType();
2309 int blockId = getBlockId(arg);
2310 ArgumentInfo argumentInfo(BlockMemberInfo::getDefaultBlockInfo(), type, -1, -1);
2311 if(blockId != -1)
2312 {
2313 argumentInfo.bufferIndex = 0;
2314 for(int i = 0; i < blockId; ++i)
2315 {
2316 int blockArraySize = shaderObject->activeUniformBlocks[i].arraySize;
2317 argumentInfo.bufferIndex += blockArraySize > 0 ? blockArraySize : 1;
2318 }
2319
2320 const BlockDefinitionIndexMap& blockDefinition = blockDefinitions[blockId];
2321
2322 BlockDefinitionIndexMap::const_iterator itEnd = blockDefinition.end();
2323 BlockDefinitionIndexMap::const_iterator it = itEnd;
2324
2325 argumentInfo.clampedIndex = index;
2326 if(type.isInterfaceBlock())
2327 {
2328 // Offset index to the beginning of the selected instance
2329 int blockRegisters = type.elementRegisterCount();
2330 int bufferOffset = argumentInfo.clampedIndex / blockRegisters;
2331 argumentInfo.bufferIndex += bufferOffset;
2332 argumentInfo.clampedIndex -= bufferOffset * blockRegisters;
2333 }
2334
2335 int regIndex = registerIndex(arg);
2336 for(int i = regIndex + argumentInfo.clampedIndex; i >= regIndex; --i)
2337 {
2338 it = blockDefinition.find(i);
2339 if(it != itEnd)
2340 {
2341 argumentInfo.clampedIndex -= (i - regIndex);
2342 break;
2343 }
2344 }
2345 ASSERT(it != itEnd);
2346
2347 argumentInfo.typedMemberInfo = it->second;
2348
2349 int registerCount = argumentInfo.typedMemberInfo.type.totalRegisterCount();
2350 argumentInfo.clampedIndex = (argumentInfo.clampedIndex >= registerCount) ? registerCount - 1 : argumentInfo.clampedIndex;
2351 }
2352 else
2353 {
2354 argumentInfo.clampedIndex = (index >= arg->totalRegisterCount()) ? arg->totalRegisterCount() - 1 : index;
2355 }
2356
2357 return argumentInfo;
2358 }
2359
Nicolas Capens0530b452017-11-15 16:39:47 -05002360 void OutputASM::source(sw::Shader::SourceParameter &parameter, TIntermNode *argument, int index)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002361 {
2362 if(argument)
2363 {
2364 TIntermTyped *arg = argument->getAsTyped();
2365 Temporary unpackedUniform(this);
2366
2367 const TType& srcType = arg->getType();
2368 TInterfaceBlock* srcBlock = srcType.getInterfaceBlock();
2369 if(srcBlock && (srcType.getQualifier() == EvqUniform))
2370 {
2371 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2372 const TType &memberType = argumentInfo.typedMemberInfo.type;
2373
2374 if(memberType.getBasicType() == EbtBool)
2375 {
Alexis Hetue97a31e2016-11-14 14:10:47 -05002376 ASSERT(argumentInfo.clampedIndex < (memberType.isArray() ? memberType.getArraySize() : 1)); // index < arraySize
Nicolas Capens0bac2852016-05-07 06:09:58 -04002377
2378 // Convert the packed bool, which is currently an int, to a true bool
2379 Instruction *instruction = new Instruction(sw::Shader::OPCODE_I2B);
2380 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2381 instruction->dst.index = registerIndex(&unpackedUniform);
2382 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2383 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2384 instruction->src[0].index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * argumentInfo.typedMemberInfo.arrayStride;
2385
2386 shader->append(instruction);
2387
2388 arg = &unpackedUniform;
2389 index = 0;
2390 }
Alexis Hetud2742532018-01-23 16:53:41 -05002391 else if((memberType.getLayoutQualifier().matrixPacking == EmpRowMajor) && memberType.isMatrix())
Nicolas Capens0bac2852016-05-07 06:09:58 -04002392 {
2393 int numCols = memberType.getNominalSize();
2394 int numRows = memberType.getSecondarySize();
Nicolas Capens0bac2852016-05-07 06:09:58 -04002395
Alexis Hetue97a31e2016-11-14 14:10:47 -05002396 ASSERT(argumentInfo.clampedIndex < (numCols * (memberType.isArray() ? memberType.getArraySize() : 1))); // index < cols * arraySize
Nicolas Capens0bac2852016-05-07 06:09:58 -04002397
2398 unsigned int dstIndex = registerIndex(&unpackedUniform);
2399 unsigned int srcSwizzle = (argumentInfo.clampedIndex % numCols) * 0x55;
2400 int arrayIndex = argumentInfo.clampedIndex / numCols;
2401 int matrixStartOffset = argumentInfo.typedMemberInfo.offset + arrayIndex * argumentInfo.typedMemberInfo.arrayStride;
2402
2403 for(int j = 0; j < numRows; ++j)
2404 {
2405 // Transpose the row major matrix
2406 Instruction *instruction = new Instruction(sw::Shader::OPCODE_MOV);
2407 instruction->dst.type = sw::Shader::PARAMETER_TEMP;
2408 instruction->dst.index = dstIndex;
2409 instruction->dst.mask = 1 << j;
2410 instruction->src[0].type = sw::Shader::PARAMETER_CONST;
2411 instruction->src[0].bufferIndex = argumentInfo.bufferIndex;
2412 instruction->src[0].index = matrixStartOffset + j * argumentInfo.typedMemberInfo.matrixStride;
2413 instruction->src[0].swizzle = srcSwizzle;
2414
2415 shader->append(instruction);
2416 }
2417
2418 arg = &unpackedUniform;
2419 index = 0;
2420 }
2421 }
2422
2423 const ArgumentInfo argumentInfo = getArgumentInfo(arg, index);
2424 const TType &type = argumentInfo.typedMemberInfo.type;
2425
2426 int size = registerSize(type, argumentInfo.clampedIndex);
2427
2428 parameter.type = registerType(arg);
2429 parameter.bufferIndex = argumentInfo.bufferIndex;
2430
2431 if(arg->getAsConstantUnion() && arg->getAsConstantUnion()->getUnionArrayPointer())
2432 {
2433 int component = componentCount(type, argumentInfo.clampedIndex);
2434 ConstantUnion *constants = arg->getAsConstantUnion()->getUnionArrayPointer();
2435
2436 for(int i = 0; i < 4; i++)
2437 {
2438 if(size == 1) // Replicate
2439 {
2440 parameter.value[i] = constants[component + 0].getAsFloat();
2441 }
2442 else if(i < size)
2443 {
2444 parameter.value[i] = constants[component + i].getAsFloat();
2445 }
2446 else
2447 {
2448 parameter.value[i] = 0.0f;
2449 }
2450 }
2451 }
2452 else
2453 {
2454 parameter.index = registerIndex(arg) + argumentInfo.clampedIndex;
2455
2456 if(parameter.bufferIndex != -1)
2457 {
2458 int stride = (argumentInfo.typedMemberInfo.matrixStride > 0) ? argumentInfo.typedMemberInfo.matrixStride : argumentInfo.typedMemberInfo.arrayStride;
2459 parameter.index = argumentInfo.typedMemberInfo.offset + argumentInfo.clampedIndex * stride;
2460 }
2461 }
2462
2463 if(!IsSampler(arg->getBasicType()))
2464 {
2465 parameter.swizzle = readSwizzle(arg, size);
2466 }
2467 }
2468 }
2469
Nicolas Capens0530b452017-11-15 16:39:47 -05002470 void OutputASM::destination(sw::Shader::DestinationParameter &parameter, TIntermTyped *arg, int index)
2471 {
2472 parameter.type = registerType(arg);
2473 parameter.index = registerIndex(arg) + index;
Nicolas Capens3ae571e2017-11-16 15:28:14 -05002474 parameter.mask = writeMask(arg, index);
Nicolas Capens0530b452017-11-15 16:39:47 -05002475 }
2476
Nicolas Capens0bac2852016-05-07 06:09:58 -04002477 void OutputASM::copy(TIntermTyped *dst, TIntermNode *src, int offset)
2478 {
2479 for(int index = 0; index < dst->totalRegisterCount(); index++)
2480 {
2481 Instruction *mov = emit(sw::Shader::OPCODE_MOV, dst, index, src, offset + index);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002482 }
2483 }
2484
2485 int swizzleElement(int swizzle, int index)
2486 {
2487 return (swizzle >> (index * 2)) & 0x03;
2488 }
2489
2490 int swizzleSwizzle(int leftSwizzle, int rightSwizzle)
2491 {
2492 return (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 0)) << 0) |
2493 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 1)) << 2) |
2494 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 2)) << 4) |
2495 (swizzleElement(leftSwizzle, swizzleElement(rightSwizzle, 3)) << 6);
2496 }
2497
2498 void OutputASM::assignLvalue(TIntermTyped *dst, TIntermTyped *src)
2499 {
Nicolas Capens84249fd2017-11-09 11:20:51 -05002500 if((src->isVector() && (!dst->isVector() || (src->getNominalSize() != dst->getNominalSize()))) ||
2501 (src->isMatrix() && (!dst->isMatrix() || (src->getNominalSize() != dst->getNominalSize()) || (src->getSecondarySize() != dst->getSecondarySize()))))
Nicolas Capens0bac2852016-05-07 06:09:58 -04002502 {
2503 return mContext.error(src->getLine(), "Result type should match the l-value type in compound assignment", src->isVector() ? "vector" : "matrix");
2504 }
2505
2506 TIntermBinary *binary = dst->getAsBinaryNode();
2507
2508 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && dst->isScalar())
2509 {
2510 Instruction *insert = new Instruction(sw::Shader::OPCODE_INSERT);
2511
Nicolas Capens6986b282017-11-16 10:38:19 -05002512 lvalue(insert->dst, dst);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002513
2514 insert->src[0].type = insert->dst.type;
2515 insert->src[0].index = insert->dst.index;
2516 insert->src[0].rel = insert->dst.rel;
Nicolas Capens0530b452017-11-15 16:39:47 -05002517 source(insert->src[1], src);
2518 source(insert->src[2], binary->getRight());
Nicolas Capens0bac2852016-05-07 06:09:58 -04002519
2520 shader->append(insert);
2521 }
2522 else
2523 {
Nicolas Capens84249fd2017-11-09 11:20:51 -05002524 Instruction *mov1 = new Instruction(sw::Shader::OPCODE_MOV);
2525
Nicolas Capens6986b282017-11-16 10:38:19 -05002526 int swizzle = lvalue(mov1->dst, dst);
Nicolas Capens84249fd2017-11-09 11:20:51 -05002527
Nicolas Capens0530b452017-11-15 16:39:47 -05002528 source(mov1->src[0], src);
Nicolas Capens84249fd2017-11-09 11:20:51 -05002529 mov1->src[0].swizzle = swizzleSwizzle(mov1->src[0].swizzle, swizzle);
2530
2531 shader->append(mov1);
2532
2533 for(int offset = 1; offset < dst->totalRegisterCount(); offset++)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002534 {
2535 Instruction *mov = new Instruction(sw::Shader::OPCODE_MOV);
2536
Nicolas Capens84249fd2017-11-09 11:20:51 -05002537 mov->dst = mov1->dst;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002538 mov->dst.index += offset;
Nicolas Capens84249fd2017-11-09 11:20:51 -05002539 mov->dst.mask = writeMask(dst, offset);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002540
Nicolas Capens0530b452017-11-15 16:39:47 -05002541 source(mov->src[0], src, offset);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002542
2543 shader->append(mov);
2544 }
2545 }
2546 }
2547
Nicolas Capensd469de22017-11-16 10:42:20 -05002548 void OutputASM::evaluateRvalue(TIntermTyped *node)
2549 {
2550 TIntermBinary *binary = node->getAsBinaryNode();
2551
2552 if(binary && binary->getOp() == EOpIndexIndirect && binary->getLeft()->isVector() && node->isScalar())
2553 {
2554 Instruction *insert = new Instruction(sw::Shader::OPCODE_EXTRACT);
2555
2556 destination(insert->dst, node);
2557
2558 Temporary address(this);
2559 unsigned char mask;
2560 TIntermTyped *root = nullptr;
2561 unsigned int offset = 0;
2562 int swizzle = lvalue(root, offset, insert->src[0].rel, mask, address, node);
2563
2564 source(insert->src[0], root, offset);
2565 insert->src[0].swizzle = swizzleSwizzle(insert->src[0].swizzle, swizzle);
2566
2567 source(insert->src[1], binary->getRight());
2568
2569 shader->append(insert);
2570 }
2571 else
2572 {
2573 Instruction *mov1 = new Instruction(sw::Shader::OPCODE_MOV);
2574
2575 destination(mov1->dst, node, 0);
2576
2577 Temporary address(this);
2578 unsigned char mask;
2579 TIntermTyped *root = nullptr;
2580 unsigned int offset = 0;
2581 int swizzle = lvalue(root, offset, mov1->src[0].rel, mask, address, node);
2582
2583 source(mov1->src[0], root, offset);
2584 mov1->src[0].swizzle = swizzleSwizzle(mov1->src[0].swizzle, swizzle);
2585
2586 shader->append(mov1);
2587
2588 for(int i = 1; i < node->totalRegisterCount(); i++)
2589 {
2590 Instruction *mov = emit(sw::Shader::OPCODE_MOV, node, i, root, offset + i);
2591 mov->src[0].rel = mov1->src[0].rel;
2592 }
2593 }
2594 }
2595
Nicolas Capens6986b282017-11-16 10:38:19 -05002596 int OutputASM::lvalue(sw::Shader::DestinationParameter &dst, TIntermTyped *node)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002597 {
Nicolas Capens6986b282017-11-16 10:38:19 -05002598 Temporary address(this);
Nicolas Capens0530b452017-11-15 16:39:47 -05002599 TIntermTyped *root = nullptr;
2600 unsigned int offset = 0;
2601 unsigned char mask = 0xF;
2602 int swizzle = lvalue(root, offset, dst.rel, mask, address, node);
2603
2604 dst.type = registerType(root);
2605 dst.index = registerIndex(root) + offset;
2606 dst.mask = mask;
2607
2608 return swizzle;
2609 }
2610
2611 int OutputASM::lvalue(TIntermTyped *&root, unsigned int &offset, sw::Shader::Relative &rel, unsigned char &mask, Temporary &address, TIntermTyped *node)
2612 {
Nicolas Capens0bac2852016-05-07 06:09:58 -04002613 TIntermTyped *result = node;
2614 TIntermBinary *binary = node->getAsBinaryNode();
2615 TIntermSymbol *symbol = node->getAsSymbolNode();
2616
2617 if(binary)
2618 {
2619 TIntermTyped *left = binary->getLeft();
2620 TIntermTyped *right = binary->getRight();
2621
Nicolas Capens0530b452017-11-15 16:39:47 -05002622 int leftSwizzle = lvalue(root, offset, rel, mask, address, left); // Resolve the l-value of the left side
Nicolas Capens0bac2852016-05-07 06:09:58 -04002623
2624 switch(binary->getOp())
2625 {
2626 case EOpIndexDirect:
2627 {
2628 int rightIndex = right->getAsConstantUnion()->getIConst(0);
2629
2630 if(left->isRegister())
2631 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002632 int leftMask = mask;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002633
Nicolas Capens0530b452017-11-15 16:39:47 -05002634 mask = 1;
2635 while((leftMask & mask) == 0)
Nicolas Capens0bac2852016-05-07 06:09:58 -04002636 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002637 mask = mask << 1;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002638 }
2639
2640 int element = swizzleElement(leftSwizzle, rightIndex);
Nicolas Capens0530b452017-11-15 16:39:47 -05002641 mask = 1 << element;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002642
2643 return element;
2644 }
2645 else if(left->isArray() || left->isMatrix())
2646 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002647 offset += rightIndex * result->totalRegisterCount();
Nicolas Capens0bac2852016-05-07 06:09:58 -04002648 return 0xE4;
2649 }
2650 else UNREACHABLE(0);
2651 }
2652 break;
2653 case EOpIndexIndirect:
2654 {
Nicolas Capens84249fd2017-11-09 11:20:51 -05002655 right->traverse(this);
2656
Nicolas Capens0bac2852016-05-07 06:09:58 -04002657 if(left->isRegister())
2658 {
2659 // Requires INSERT instruction (handled by calling function)
2660 }
2661 else if(left->isArray() || left->isMatrix())
2662 {
2663 int scale = result->totalRegisterCount();
2664
Nicolas Capens0530b452017-11-15 16:39:47 -05002665 if(rel.type == sw::Shader::PARAMETER_VOID) // Use the index register as the relative address directly
Nicolas Capens0bac2852016-05-07 06:09:58 -04002666 {
2667 if(left->totalRegisterCount() > 1)
2668 {
2669 sw::Shader::SourceParameter relativeRegister;
Nicolas Capens0530b452017-11-15 16:39:47 -05002670 source(relativeRegister, right);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002671
Nicolas Capens0530b452017-11-15 16:39:47 -05002672 rel.index = relativeRegister.index;
2673 rel.type = relativeRegister.type;
2674 rel.scale = scale;
2675 rel.deterministic = !(vertexShader && left->getQualifier() == EvqUniform);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002676 }
2677 }
Nicolas Capens0530b452017-11-15 16:39:47 -05002678 else if(rel.index != registerIndex(&address)) // Move the previous index register to the address register
Nicolas Capens0bac2852016-05-07 06:09:58 -04002679 {
2680 if(scale == 1)
2681 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002682 Constant oldScale((int)rel.scale);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002683 Instruction *mad = emit(sw::Shader::OPCODE_IMAD, &address, &address, &oldScale, right);
Nicolas Capens0530b452017-11-15 16:39:47 -05002684 mad->src[0].index = rel.index;
2685 mad->src[0].type = rel.type;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002686 }
2687 else
2688 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002689 Constant oldScale((int)rel.scale);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002690 Instruction *mul = emit(sw::Shader::OPCODE_IMUL, &address, &address, &oldScale);
Nicolas Capens0530b452017-11-15 16:39:47 -05002691 mul->src[0].index = rel.index;
2692 mul->src[0].type = rel.type;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002693
2694 Constant newScale(scale);
2695 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2696 }
2697
Nicolas Capens0530b452017-11-15 16:39:47 -05002698 rel.type = sw::Shader::PARAMETER_TEMP;
2699 rel.index = registerIndex(&address);
2700 rel.scale = 1;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002701 }
2702 else // Just add the new index to the address register
2703 {
2704 if(scale == 1)
2705 {
2706 emit(sw::Shader::OPCODE_IADD, &address, &address, right);
2707 }
2708 else
2709 {
2710 Constant newScale(scale);
2711 emit(sw::Shader::OPCODE_IMAD, &address, right, &newScale, &address);
2712 }
2713 }
2714 }
2715 else UNREACHABLE(0);
2716 }
2717 break;
2718 case EOpIndexDirectStruct:
2719 case EOpIndexDirectInterfaceBlock:
2720 {
2721 const TFieldList& fields = (binary->getOp() == EOpIndexDirectStruct) ?
2722 left->getType().getStruct()->fields() :
2723 left->getType().getInterfaceBlock()->fields();
2724 int index = right->getAsConstantUnion()->getIConst(0);
2725 int fieldOffset = 0;
2726
2727 for(int i = 0; i < index; i++)
2728 {
2729 fieldOffset += fields[i]->type()->totalRegisterCount();
2730 }
2731
Nicolas Capens0530b452017-11-15 16:39:47 -05002732 offset += fieldOffset;
2733 mask = writeMask(result);
Nicolas Capens0bac2852016-05-07 06:09:58 -04002734
2735 return 0xE4;
2736 }
2737 break;
2738 case EOpVectorSwizzle:
2739 {
2740 ASSERT(left->isRegister());
2741
Nicolas Capens0530b452017-11-15 16:39:47 -05002742 int leftMask = mask;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002743
2744 int swizzle = 0;
2745 int rightMask = 0;
2746
2747 TIntermSequence &sequence = right->getAsAggregate()->getSequence();
2748
2749 for(unsigned int i = 0; i < sequence.size(); i++)
2750 {
2751 int index = sequence[i]->getAsConstantUnion()->getIConst(0);
2752
2753 int element = swizzleElement(leftSwizzle, index);
2754 rightMask = rightMask | (1 << element);
2755 swizzle = swizzle | swizzleElement(leftSwizzle, i) << (element * 2);
2756 }
2757
Nicolas Capens0530b452017-11-15 16:39:47 -05002758 mask = leftMask & rightMask;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002759
2760 return swizzle;
2761 }
2762 break;
2763 default:
2764 UNREACHABLE(binary->getOp()); // Not an l-value operator
2765 break;
2766 }
2767 }
2768 else if(symbol)
2769 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002770 root = symbol;
2771 offset = 0;
2772 mask = writeMask(symbol);
2773
2774 return 0xE4;
2775 }
2776 else
2777 {
2778 node->traverse(this);
2779
2780 root = node;
2781 offset = 0;
2782 mask = writeMask(node);
2783
Nicolas Capens0bac2852016-05-07 06:09:58 -04002784 return 0xE4;
2785 }
2786
2787 return 0xE4;
2788 }
2789
2790 sw::Shader::ParameterType OutputASM::registerType(TIntermTyped *operand)
2791 {
2792 if(isSamplerRegister(operand))
2793 {
2794 return sw::Shader::PARAMETER_SAMPLER;
2795 }
2796
2797 const TQualifier qualifier = operand->getQualifier();
Nicolas Capens0530b452017-11-15 16:39:47 -05002798 if((qualifier == EvqFragColor) || (qualifier == EvqFragData))
Nicolas Capens0bac2852016-05-07 06:09:58 -04002799 {
Nicolas Capens0530b452017-11-15 16:39:47 -05002800 if(((qualifier == EvqFragData) && (outputQualifier == EvqFragColor)) ||
2801 ((qualifier == EvqFragColor) && (outputQualifier == EvqFragData)))
Nicolas Capens0bac2852016-05-07 06:09:58 -04002802 {
2803 mContext.error(operand->getLine(), "static assignment to both gl_FragData and gl_FragColor", "");
2804 }
2805 outputQualifier = qualifier;
2806 }
2807
2808 if(qualifier == EvqConstExpr && (!operand->getAsConstantUnion() || !operand->getAsConstantUnion()->getUnionArrayPointer()))
2809 {
Nicolas Capens7cbb1de2017-12-22 08:54:18 -05002810 // Constant arrays are in the constant register file.
2811 if(operand->isArray() && operand->getArraySize() > 1)
2812 {
2813 return sw::Shader::PARAMETER_CONST;
2814 }
2815 else
2816 {
2817 return sw::Shader::PARAMETER_TEMP;
2818 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04002819 }
2820
2821 switch(qualifier)
2822 {
2823 case EvqTemporary: return sw::Shader::PARAMETER_TEMP;
2824 case EvqGlobal: return sw::Shader::PARAMETER_TEMP;
2825 case EvqConstExpr: return sw::Shader::PARAMETER_FLOAT4LITERAL; // All converted to float
2826 case EvqAttribute: return sw::Shader::PARAMETER_INPUT;
2827 case EvqVaryingIn: return sw::Shader::PARAMETER_INPUT;
2828 case EvqVaryingOut: return sw::Shader::PARAMETER_OUTPUT;
2829 case EvqVertexIn: return sw::Shader::PARAMETER_INPUT;
2830 case EvqFragmentOut: return sw::Shader::PARAMETER_COLOROUT;
2831 case EvqVertexOut: return sw::Shader::PARAMETER_OUTPUT;
2832 case EvqFragmentIn: return sw::Shader::PARAMETER_INPUT;
2833 case EvqInvariantVaryingIn: return sw::Shader::PARAMETER_INPUT; // FIXME: Guarantee invariance at the backend
2834 case EvqInvariantVaryingOut: return sw::Shader::PARAMETER_OUTPUT; // FIXME: Guarantee invariance at the backend
2835 case EvqSmooth: return sw::Shader::PARAMETER_OUTPUT;
2836 case EvqFlat: return sw::Shader::PARAMETER_OUTPUT;
2837 case EvqCentroidOut: return sw::Shader::PARAMETER_OUTPUT;
2838 case EvqSmoothIn: return sw::Shader::PARAMETER_INPUT;
2839 case EvqFlatIn: return sw::Shader::PARAMETER_INPUT;
2840 case EvqCentroidIn: return sw::Shader::PARAMETER_INPUT;
2841 case EvqUniform: return sw::Shader::PARAMETER_CONST;
2842 case EvqIn: return sw::Shader::PARAMETER_TEMP;
2843 case EvqOut: return sw::Shader::PARAMETER_TEMP;
2844 case EvqInOut: return sw::Shader::PARAMETER_TEMP;
2845 case EvqConstReadOnly: return sw::Shader::PARAMETER_TEMP;
2846 case EvqPosition: return sw::Shader::PARAMETER_OUTPUT;
2847 case EvqPointSize: return sw::Shader::PARAMETER_OUTPUT;
2848 case EvqInstanceID: return sw::Shader::PARAMETER_MISCTYPE;
Alexis Hetu877ddfc2017-07-25 17:48:00 -04002849 case EvqVertexID: return sw::Shader::PARAMETER_MISCTYPE;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002850 case EvqFragCoord: return sw::Shader::PARAMETER_MISCTYPE;
2851 case EvqFrontFacing: return sw::Shader::PARAMETER_MISCTYPE;
2852 case EvqPointCoord: return sw::Shader::PARAMETER_INPUT;
2853 case EvqFragColor: return sw::Shader::PARAMETER_COLOROUT;
2854 case EvqFragData: return sw::Shader::PARAMETER_COLOROUT;
2855 case EvqFragDepth: return sw::Shader::PARAMETER_DEPTHOUT;
2856 default: UNREACHABLE(qualifier);
2857 }
2858
2859 return sw::Shader::PARAMETER_VOID;
2860 }
2861
Alexis Hetu12b00502016-05-20 13:01:11 -04002862 bool OutputASM::hasFlatQualifier(TIntermTyped *operand)
2863 {
2864 const TQualifier qualifier = operand->getQualifier();
2865 return qualifier == EvqFlat || qualifier == EvqFlatOut || qualifier == EvqFlatIn;
2866 }
2867
Nicolas Capens0bac2852016-05-07 06:09:58 -04002868 unsigned int OutputASM::registerIndex(TIntermTyped *operand)
2869 {
2870 if(isSamplerRegister(operand))
2871 {
2872 return samplerRegister(operand);
2873 }
2874
2875 switch(operand->getQualifier())
2876 {
2877 case EvqTemporary: return temporaryRegister(operand);
2878 case EvqGlobal: return temporaryRegister(operand);
2879 case EvqConstExpr: return temporaryRegister(operand); // Unevaluated constant expression
2880 case EvqAttribute: return attributeRegister(operand);
2881 case EvqVaryingIn: return varyingRegister(operand);
2882 case EvqVaryingOut: return varyingRegister(operand);
2883 case EvqVertexIn: return attributeRegister(operand);
2884 case EvqFragmentOut: return fragmentOutputRegister(operand);
2885 case EvqVertexOut: return varyingRegister(operand);
2886 case EvqFragmentIn: return varyingRegister(operand);
2887 case EvqInvariantVaryingIn: return varyingRegister(operand);
2888 case EvqInvariantVaryingOut: return varyingRegister(operand);
2889 case EvqSmooth: return varyingRegister(operand);
2890 case EvqFlat: return varyingRegister(operand);
2891 case EvqCentroidOut: return varyingRegister(operand);
2892 case EvqSmoothIn: return varyingRegister(operand);
2893 case EvqFlatIn: return varyingRegister(operand);
2894 case EvqCentroidIn: return varyingRegister(operand);
2895 case EvqUniform: return uniformRegister(operand);
2896 case EvqIn: return temporaryRegister(operand);
2897 case EvqOut: return temporaryRegister(operand);
2898 case EvqInOut: return temporaryRegister(operand);
2899 case EvqConstReadOnly: return temporaryRegister(operand);
2900 case EvqPosition: return varyingRegister(operand);
2901 case EvqPointSize: return varyingRegister(operand);
Alexis Hetu877ddfc2017-07-25 17:48:00 -04002902 case EvqInstanceID: vertexShader->declareInstanceId(); return sw::Shader::InstanceIDIndex;
2903 case EvqVertexID: vertexShader->declareVertexId(); return sw::Shader::VertexIDIndex;
2904 case EvqFragCoord: pixelShader->declareVPos(); return sw::Shader::VPosIndex;
2905 case EvqFrontFacing: pixelShader->declareVFace(); return sw::Shader::VFaceIndex;
Nicolas Capens0bac2852016-05-07 06:09:58 -04002906 case EvqPointCoord: return varyingRegister(operand);
2907 case EvqFragColor: return 0;
2908 case EvqFragData: return fragmentOutputRegister(operand);
2909 case EvqFragDepth: return 0;
2910 default: UNREACHABLE(operand->getQualifier());
2911 }
2912
2913 return 0;
2914 }
2915
2916 int OutputASM::writeMask(TIntermTyped *destination, int index)
2917 {
2918 if(destination->getQualifier() == EvqPointSize)
2919 {
2920 return 0x2; // Point size stored in the y component
2921 }
2922
2923 return 0xF >> (4 - registerSize(destination->getType(), index));
2924 }
2925
2926 int OutputASM::readSwizzle(TIntermTyped *argument, int size)
2927 {
2928 if(argument->getQualifier() == EvqPointSize)
2929 {
2930 return 0x55; // Point size stored in the y component
2931 }
2932
2933 static const unsigned char swizzleSize[5] = {0x00, 0x00, 0x54, 0xA4, 0xE4}; // (void), xxxx, xyyy, xyzz, xyzw
2934
2935 return swizzleSize[size];
2936 }
2937
2938 // Conservatively checks whether an expression is fast to compute and has no side effects
2939 bool OutputASM::trivial(TIntermTyped *expression, int budget)
2940 {
2941 if(!expression->isRegister())
2942 {
2943 return false;
2944 }
2945
2946 return cost(expression, budget) >= 0;
2947 }
2948
2949 // Returns the remaining computing budget (if < 0 the expression is too expensive or has side effects)
2950 int OutputASM::cost(TIntermNode *expression, int budget)
2951 {
2952 if(budget < 0)
2953 {
2954 return budget;
2955 }
2956
2957 if(expression->getAsSymbolNode())
2958 {
2959 return budget;
2960 }
2961 else if(expression->getAsConstantUnion())
2962 {
2963 return budget;
2964 }
2965 else if(expression->getAsBinaryNode())
2966 {
2967 TIntermBinary *binary = expression->getAsBinaryNode();
2968
2969 switch(binary->getOp())
2970 {
2971 case EOpVectorSwizzle:
2972 case EOpIndexDirect:
2973 case EOpIndexDirectStruct:
2974 case EOpIndexDirectInterfaceBlock:
2975 return cost(binary->getLeft(), budget - 0);
2976 case EOpAdd:
2977 case EOpSub:
2978 case EOpMul:
2979 return cost(binary->getLeft(), cost(binary->getRight(), budget - 1));
2980 default:
2981 return -1;
2982 }
2983 }
2984 else if(expression->getAsUnaryNode())
2985 {
2986 TIntermUnary *unary = expression->getAsUnaryNode();
2987
2988 switch(unary->getOp())
2989 {
2990 case EOpAbs:
2991 case EOpNegative:
2992 return cost(unary->getOperand(), budget - 1);
2993 default:
2994 return -1;
2995 }
2996 }
2997 else if(expression->getAsSelectionNode())
2998 {
2999 TIntermSelection *selection = expression->getAsSelectionNode();
3000
3001 if(selection->usesTernaryOperator())
3002 {
3003 TIntermTyped *condition = selection->getCondition();
3004 TIntermNode *trueBlock = selection->getTrueBlock();
3005 TIntermNode *falseBlock = selection->getFalseBlock();
3006 TIntermConstantUnion *constantCondition = condition->getAsConstantUnion();
3007
3008 if(constantCondition)
3009 {
3010 bool trueCondition = constantCondition->getUnionArrayPointer()->getBConst();
3011
3012 if(trueCondition)
3013 {
3014 return cost(trueBlock, budget - 0);
3015 }
3016 else
3017 {
3018 return cost(falseBlock, budget - 0);
3019 }
3020 }
3021 else
3022 {
3023 return cost(trueBlock, cost(falseBlock, budget - 2));
3024 }
3025 }
3026 }
3027
3028 return -1;
3029 }
3030
3031 const Function *OutputASM::findFunction(const TString &name)
3032 {
3033 for(unsigned int f = 0; f < functionArray.size(); f++)
3034 {
3035 if(functionArray[f].name == name)
3036 {
3037 return &functionArray[f];
3038 }
3039 }
3040
3041 return 0;
3042 }
3043
3044 int OutputASM::temporaryRegister(TIntermTyped *temporary)
3045 {
3046 return allocate(temporaries, temporary);
3047 }
3048
Alexis Hetu49351232017-11-02 16:00:32 -04003049 void OutputASM::setPixelShaderInputs(const TType& type, int var, bool flat)
3050 {
3051 if(type.isStruct())
3052 {
3053 const TFieldList &fields = type.getStruct()->fields();
3054 int fieldVar = var;
Alexis Hetuda163ed2018-01-03 16:36:14 -05003055 for(const auto &field : fields)
Alexis Hetu49351232017-11-02 16:00:32 -04003056 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003057 const TType& fieldType = *(field->type());
Alexis Hetu49351232017-11-02 16:00:32 -04003058 setPixelShaderInputs(fieldType, fieldVar, flat);
3059 fieldVar += fieldType.totalRegisterCount();
3060 }
3061 }
3062 else
3063 {
3064 for(int i = 0; i < type.totalRegisterCount(); i++)
3065 {
3066 pixelShader->setInput(var + i, type.registerSize(), sw::Shader::Semantic(sw::Shader::USAGE_COLOR, var + i, flat));
3067 }
3068 }
3069 }
3070
Nicolas Capens0bac2852016-05-07 06:09:58 -04003071 int OutputASM::varyingRegister(TIntermTyped *varying)
3072 {
3073 int var = lookup(varyings, varying);
3074
3075 if(var == -1)
3076 {
3077 var = allocate(varyings, varying);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003078 int registerCount = varying->totalRegisterCount();
3079
3080 if(pixelShader)
3081 {
Nicolas Capens3b4c93f2016-05-18 12:51:37 -04003082 if((var + registerCount) > sw::MAX_FRAGMENT_INPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003083 {
3084 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "fragment shader");
3085 return 0;
3086 }
3087
3088 if(varying->getQualifier() == EvqPointCoord)
3089 {
3090 ASSERT(varying->isRegister());
Alexis Hetu49351232017-11-02 16:00:32 -04003091 pixelShader->setInput(var, varying->registerSize(), sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, var));
Nicolas Capens0bac2852016-05-07 06:09:58 -04003092 }
3093 else
3094 {
Alexis Hetu49351232017-11-02 16:00:32 -04003095 setPixelShaderInputs(varying->getType(), var, hasFlatQualifier(varying));
Nicolas Capens0bac2852016-05-07 06:09:58 -04003096 }
3097 }
3098 else if(vertexShader)
3099 {
Nicolas Capensec0936c2016-05-18 12:32:02 -04003100 if((var + registerCount) > sw::MAX_VERTEX_OUTPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003101 {
3102 mContext.error(varying->getLine(), "Varyings packing failed: Too many varyings", "vertex shader");
3103 return 0;
3104 }
3105
3106 if(varying->getQualifier() == EvqPosition)
3107 {
3108 ASSERT(varying->isRegister());
Alexis Hetu02ad0aa2016-08-02 11:18:14 -04003109 vertexShader->setPositionRegister(var);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003110 }
3111 else if(varying->getQualifier() == EvqPointSize)
3112 {
3113 ASSERT(varying->isRegister());
Alexis Hetu02ad0aa2016-08-02 11:18:14 -04003114 vertexShader->setPointSizeRegister(var);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003115 }
3116 else
3117 {
3118 // Semantic indexes for user varyings will be assigned during program link to match the pixel shader
3119 }
3120 }
3121 else UNREACHABLE(0);
3122
3123 declareVarying(varying, var);
3124 }
3125
3126 return var;
3127 }
3128
3129 void OutputASM::declareVarying(TIntermTyped *varying, int reg)
3130 {
3131 if(varying->getQualifier() != EvqPointCoord) // gl_PointCoord does not need linking
3132 {
Alexis Hetu49351232017-11-02 16:00:32 -04003133 TIntermSymbol *symbol = varying->getAsSymbolNode();
3134 declareVarying(varying->getType(), symbol->getSymbol(), reg);
3135 }
3136 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003137
Alexis Hetu49351232017-11-02 16:00:32 -04003138 void OutputASM::declareVarying(const TType &type, const TString &varyingName, int registerIndex)
3139 {
3140 const char *name = varyingName.c_str();
3141 VaryingList &activeVaryings = shaderObject->varyings;
3142
3143 TStructure* structure = type.getStruct();
3144 if(structure)
3145 {
3146 int fieldRegisterIndex = registerIndex;
3147
3148 const TFieldList &fields = type.getStruct()->fields();
Alexis Hetuda163ed2018-01-03 16:36:14 -05003149 for(const auto &field : fields)
Alexis Hetu49351232017-11-02 16:00:32 -04003150 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003151 const TType& fieldType = *(field->type());
3152 declareVarying(fieldType, varyingName + "." + field->name(), fieldRegisterIndex);
Alexis Hetu49351232017-11-02 16:00:32 -04003153 if(fieldRegisterIndex >= 0)
3154 {
3155 fieldRegisterIndex += fieldType.totalRegisterCount();
3156 }
3157 }
3158 }
3159 else
3160 {
Nicolas Capens0bac2852016-05-07 06:09:58 -04003161 // Check if this varying has been declared before without having a register assigned
3162 for(VaryingList::iterator v = activeVaryings.begin(); v != activeVaryings.end(); v++)
3163 {
3164 if(v->name == name)
3165 {
Alexis Hetu49351232017-11-02 16:00:32 -04003166 if(registerIndex >= 0)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003167 {
Alexis Hetu924513c2018-01-05 15:48:12 -05003168 ASSERT(v->registerIndex < 0 || v->registerIndex == registerIndex);
3169 v->registerIndex = registerIndex;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003170 }
3171
3172 return;
3173 }
3174 }
3175
Alexis Hetu924513c2018-01-05 15:48:12 -05003176 activeVaryings.push_back(glsl::Varying(type, name, registerIndex, 0));
Nicolas Capens0bac2852016-05-07 06:09:58 -04003177 }
3178 }
3179
Alexis Hetu930df972018-01-30 16:54:13 -05003180 void OutputASM::declareFragmentOutput(TIntermTyped *fragmentOutput)
3181 {
3182 int requestedLocation = fragmentOutput->getType().getLayoutQualifier().location;
Alexis Hetu17e2e2f2018-02-05 10:41:47 -05003183 int registerCount = fragmentOutput->totalRegisterCount();
3184 if(requestedLocation < 0)
Alexis Hetu930df972018-01-30 16:54:13 -05003185 {
Alexis Hetu17e2e2f2018-02-05 10:41:47 -05003186 mContext.error(fragmentOutput->getLine(), "Invalid fragment output location", "fragment shader");
Alexis Hetu930df972018-01-30 16:54:13 -05003187 }
Alexis Hetu17e2e2f2018-02-05 10:41:47 -05003188 else if((requestedLocation + registerCount) > sw::RENDERTARGETS)
Alexis Hetu930df972018-01-30 16:54:13 -05003189 {
3190 mContext.error(fragmentOutput->getLine(), "Fragment output location larger or equal to MAX_DRAW_BUFFERS", "fragment shader");
3191 }
Alexis Hetu17e2e2f2018-02-05 10:41:47 -05003192 else
3193 {
3194 int currentIndex = lookup(fragmentOutputs, fragmentOutput);
3195 if(requestedLocation != currentIndex)
3196 {
3197 if(currentIndex != -1)
3198 {
3199 mContext.error(fragmentOutput->getLine(), "Multiple locations for fragment output", "fragment shader");
3200 }
3201 else
3202 {
3203 if(fragmentOutputs.size() <= (size_t)requestedLocation)
3204 {
3205 while(fragmentOutputs.size() < (size_t)requestedLocation)
3206 {
3207 fragmentOutputs.push_back(nullptr);
3208 }
3209 for(int i = 0; i < registerCount; i++)
3210 {
3211 fragmentOutputs.push_back(fragmentOutput);
3212 }
3213 }
3214 else
3215 {
3216 for(int i = 0; i < registerCount; i++)
3217 {
3218 if(!fragmentOutputs[requestedLocation + i])
3219 {
3220 fragmentOutputs[requestedLocation + i] = fragmentOutput;
3221 }
3222 else
3223 {
3224 mContext.error(fragmentOutput->getLine(), "Fragment output location aliasing", "fragment shader");
3225 return;
3226 }
3227 }
3228 }
3229 }
3230 }
3231 }
Alexis Hetu930df972018-01-30 16:54:13 -05003232 }
3233
Nicolas Capens0bac2852016-05-07 06:09:58 -04003234 int OutputASM::uniformRegister(TIntermTyped *uniform)
3235 {
3236 const TType &type = uniform->getType();
3237 ASSERT(!IsSampler(type.getBasicType()));
3238 TInterfaceBlock *block = type.getAsInterfaceBlock();
3239 TIntermSymbol *symbol = uniform->getAsSymbolNode();
3240 ASSERT(symbol || block);
3241
3242 if(symbol || block)
3243 {
3244 TInterfaceBlock* parentBlock = type.getInterfaceBlock();
3245 bool isBlockMember = (!block && parentBlock);
3246 int index = isBlockMember ? lookup(uniforms, parentBlock) : lookup(uniforms, uniform);
3247
3248 if(index == -1 || isBlockMember)
3249 {
3250 if(index == -1)
3251 {
3252 index = allocate(uniforms, uniform);
3253 }
3254
3255 // Verify if the current uniform is a member of an already declared block
3256 const TString &name = symbol ? symbol->getSymbol() : block->name();
3257 int blockMemberIndex = blockMemberLookup(type, name, index);
3258 if(blockMemberIndex == -1)
3259 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003260 declareUniform(type, name, index, false);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003261 }
3262 else
3263 {
3264 index = blockMemberIndex;
3265 }
3266 }
3267
3268 return index;
3269 }
3270
3271 return 0;
3272 }
3273
3274 int OutputASM::attributeRegister(TIntermTyped *attribute)
3275 {
3276 ASSERT(!attribute->isArray());
3277
3278 int index = lookup(attributes, attribute);
3279
3280 if(index == -1)
3281 {
3282 TIntermSymbol *symbol = attribute->getAsSymbolNode();
3283 ASSERT(symbol);
3284
3285 if(symbol)
3286 {
3287 index = allocate(attributes, attribute);
3288 const TType &type = attribute->getType();
3289 int registerCount = attribute->totalRegisterCount();
Alexis Hetub7508b82016-09-22 15:36:45 -04003290 sw::VertexShader::AttribType attribType = sw::VertexShader::ATTRIBTYPE_FLOAT;
3291 switch(type.getBasicType())
3292 {
3293 case EbtInt:
3294 attribType = sw::VertexShader::ATTRIBTYPE_INT;
3295 break;
3296 case EbtUInt:
3297 attribType = sw::VertexShader::ATTRIBTYPE_UINT;
3298 break;
3299 case EbtFloat:
3300 default:
3301 break;
3302 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003303
Nicolas Capensf0aef1a2016-05-18 14:44:21 -04003304 if(vertexShader && (index + registerCount) <= sw::MAX_VERTEX_INPUTS)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003305 {
3306 for(int i = 0; i < registerCount; i++)
3307 {
Alexis Hetub7508b82016-09-22 15:36:45 -04003308 vertexShader->setInput(index + i, sw::Shader::Semantic(sw::Shader::USAGE_TEXCOORD, index + i, false), attribType);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003309 }
3310 }
3311
3312 ActiveAttributes &activeAttributes = shaderObject->activeAttributes;
3313
3314 const char *name = symbol->getSymbol().c_str();
3315 activeAttributes.push_back(Attribute(glVariableType(type), name, type.getArraySize(), type.getLayoutQualifier().location, index));
3316 }
3317 }
3318
3319 return index;
3320 }
3321
3322 int OutputASM::fragmentOutputRegister(TIntermTyped *fragmentOutput)
3323 {
3324 return allocate(fragmentOutputs, fragmentOutput);
3325 }
3326
3327 int OutputASM::samplerRegister(TIntermTyped *sampler)
3328 {
3329 const TType &type = sampler->getType();
3330 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
3331
3332 TIntermSymbol *symbol = sampler->getAsSymbolNode();
3333 TIntermBinary *binary = sampler->getAsBinaryNode();
3334
Nicolas Capensfcb70fd2017-05-17 15:16:51 -04003335 if(symbol)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003336 {
Nicolas Capensfcb70fd2017-05-17 15:16:51 -04003337 switch(type.getQualifier())
3338 {
3339 case EvqUniform:
3340 return samplerRegister(symbol);
3341 case EvqIn:
3342 case EvqConstReadOnly:
3343 // Function arguments are not (uniform) sampler registers
3344 return -1;
3345 default:
3346 UNREACHABLE(type.getQualifier());
3347 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003348 }
3349 else if(binary)
3350 {
3351 TIntermTyped *left = binary->getLeft();
3352 TIntermTyped *right = binary->getRight();
3353 const TType &leftType = left->getType();
3354 int index = right->getAsConstantUnion() ? right->getAsConstantUnion()->getIConst(0) : 0;
3355 int offset = 0;
3356
3357 switch(binary->getOp())
3358 {
3359 case EOpIndexDirect:
3360 ASSERT(left->isArray());
Alexis Hetuda163ed2018-01-03 16:36:14 -05003361 offset = index * leftType.samplerRegisterCount();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003362 break;
3363 case EOpIndexDirectStruct:
3364 ASSERT(leftType.isStruct());
3365 {
3366 const TFieldList &fields = leftType.getStruct()->fields();
3367
3368 for(int i = 0; i < index; i++)
3369 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003370 offset += fields[i]->type()->totalSamplerRegisterCount();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003371 }
3372 }
3373 break;
3374 case EOpIndexIndirect: // Indirect indexing produces a temporary, not a sampler register
3375 return -1;
3376 case EOpIndexDirectInterfaceBlock: // Interface blocks can't contain samplers
3377 default:
3378 UNREACHABLE(binary->getOp());
3379 return -1;
3380 }
3381
3382 int base = samplerRegister(left);
3383
3384 if(base < 0)
3385 {
3386 return -1;
3387 }
3388
3389 return base + offset;
3390 }
3391
3392 UNREACHABLE(0);
Nicolas Capensfcb70fd2017-05-17 15:16:51 -04003393 return -1; // Not a (uniform) sampler register
Nicolas Capens0bac2852016-05-07 06:09:58 -04003394 }
3395
3396 int OutputASM::samplerRegister(TIntermSymbol *sampler)
3397 {
3398 const TType &type = sampler->getType();
3399 ASSERT(IsSampler(type.getBasicType()) || type.isStruct()); // Structures can contain samplers
3400
3401 int index = lookup(samplers, sampler);
3402
3403 if(index == -1)
3404 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003405 index = allocate(samplers, sampler, true);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003406
3407 if(sampler->getQualifier() == EvqUniform)
3408 {
3409 const char *name = sampler->getSymbol().c_str();
Alexis Hetuda163ed2018-01-03 16:36:14 -05003410 declareUniform(type, name, index, true);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003411 }
3412 }
3413
3414 return index;
3415 }
3416
3417 bool OutputASM::isSamplerRegister(TIntermTyped *operand)
3418 {
3419 return operand && IsSampler(operand->getBasicType()) && samplerRegister(operand) >= 0;
3420 }
3421
3422 int OutputASM::lookup(VariableArray &list, TIntermTyped *variable)
3423 {
3424 for(unsigned int i = 0; i < list.size(); i++)
3425 {
3426 if(list[i] == variable)
3427 {
3428 return i; // Pointer match
3429 }
3430 }
3431
3432 TIntermSymbol *varSymbol = variable->getAsSymbolNode();
3433 TInterfaceBlock *varBlock = variable->getType().getAsInterfaceBlock();
3434
3435 if(varBlock)
3436 {
3437 for(unsigned int i = 0; i < list.size(); i++)
3438 {
3439 if(list[i])
3440 {
3441 TInterfaceBlock *listBlock = list[i]->getType().getAsInterfaceBlock();
3442
3443 if(listBlock)
3444 {
3445 if(listBlock->name() == varBlock->name())
3446 {
3447 ASSERT(listBlock->arraySize() == varBlock->arraySize());
3448 ASSERT(listBlock->fields() == varBlock->fields());
3449 ASSERT(listBlock->blockStorage() == varBlock->blockStorage());
3450 ASSERT(listBlock->matrixPacking() == varBlock->matrixPacking());
3451
3452 return i;
3453 }
3454 }
3455 }
3456 }
3457 }
3458 else if(varSymbol)
3459 {
3460 for(unsigned int i = 0; i < list.size(); i++)
3461 {
3462 if(list[i])
3463 {
3464 TIntermSymbol *listSymbol = list[i]->getAsSymbolNode();
3465
3466 if(listSymbol)
3467 {
3468 if(listSymbol->getId() == varSymbol->getId())
3469 {
3470 ASSERT(listSymbol->getSymbol() == varSymbol->getSymbol());
3471 ASSERT(listSymbol->getType() == varSymbol->getType());
3472 ASSERT(listSymbol->getQualifier() == varSymbol->getQualifier());
3473
3474 return i;
3475 }
3476 }
3477 }
3478 }
3479 }
3480
3481 return -1;
3482 }
3483
3484 int OutputASM::lookup(VariableArray &list, TInterfaceBlock *block)
3485 {
3486 for(unsigned int i = 0; i < list.size(); i++)
3487 {
3488 if(list[i] && (list[i]->getType().getInterfaceBlock() == block))
3489 {
3490 return i; // Pointer match
3491 }
3492 }
3493 return -1;
3494 }
3495
Alexis Hetuda163ed2018-01-03 16:36:14 -05003496 int OutputASM::allocate(VariableArray &list, TIntermTyped *variable, bool samplersOnly)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003497 {
3498 int index = lookup(list, variable);
3499
3500 if(index == -1)
3501 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003502 unsigned int registerCount = variable->blockRegisterCount(samplersOnly);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003503
3504 for(unsigned int i = 0; i < list.size(); i++)
3505 {
3506 if(list[i] == 0)
3507 {
3508 unsigned int j = 1;
3509 for( ; j < registerCount && (i + j) < list.size(); j++)
3510 {
3511 if(list[i + j] != 0)
3512 {
3513 break;
3514 }
3515 }
3516
3517 if(j == registerCount) // Found free slots
3518 {
3519 for(unsigned int j = 0; j < registerCount; j++)
3520 {
3521 list[i + j] = variable;
3522 }
3523
3524 return i;
3525 }
3526 }
3527 }
3528
3529 index = list.size();
3530
3531 for(unsigned int i = 0; i < registerCount; i++)
3532 {
3533 list.push_back(variable);
3534 }
3535 }
3536
3537 return index;
3538 }
3539
3540 void OutputASM::free(VariableArray &list, TIntermTyped *variable)
3541 {
3542 int index = lookup(list, variable);
3543
3544 if(index >= 0)
3545 {
3546 list[index] = 0;
3547 }
3548 }
3549
3550 int OutputASM::blockMemberLookup(const TType &type, const TString &name, int registerIndex)
3551 {
3552 const TInterfaceBlock *block = type.getInterfaceBlock();
3553
3554 if(block)
3555 {
3556 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3557 const TFieldList& fields = block->fields();
3558 const TString &blockName = block->name();
3559 int fieldRegisterIndex = registerIndex;
3560
3561 if(!type.isInterfaceBlock())
3562 {
3563 // This is a uniform that's part of a block, let's see if the block is already defined
3564 for(size_t i = 0; i < activeUniformBlocks.size(); ++i)
3565 {
3566 if(activeUniformBlocks[i].name == blockName.c_str())
3567 {
3568 // The block is already defined, find the register for the current uniform and return it
3569 for(size_t j = 0; j < fields.size(); j++)
3570 {
3571 const TString &fieldName = fields[j]->name();
3572 if(fieldName == name)
3573 {
3574 return fieldRegisterIndex;
3575 }
3576
3577 fieldRegisterIndex += fields[j]->type()->totalRegisterCount();
3578 }
3579
3580 ASSERT(false);
3581 return fieldRegisterIndex;
3582 }
3583 }
3584 }
3585 }
3586
3587 return -1;
3588 }
3589
Alexis Hetuda163ed2018-01-03 16:36:14 -05003590 void OutputASM::declareUniform(const TType &type, const TString &name, int registerIndex, bool samplersOnly, int blockId, BlockLayoutEncoder* encoder)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003591 {
3592 const TStructure *structure = type.getStruct();
3593 const TInterfaceBlock *block = (type.isInterfaceBlock() || (blockId == -1)) ? type.getInterfaceBlock() : nullptr;
3594
3595 if(!structure && !block)
3596 {
3597 ActiveUniforms &activeUniforms = shaderObject->activeUniforms;
3598 const BlockMemberInfo blockInfo = encoder ? encoder->encodeType(type) : BlockMemberInfo::getDefaultBlockInfo();
3599 if(blockId >= 0)
3600 {
3601 blockDefinitions[blockId][registerIndex] = TypedMemberInfo(blockInfo, type);
3602 shaderObject->activeUniformBlocks[blockId].fields.push_back(activeUniforms.size());
3603 }
3604 int fieldRegisterIndex = encoder ? shaderObject->activeUniformBlocks[blockId].registerIndex + BlockLayoutEncoder::getBlockRegister(blockInfo) : registerIndex;
Alexis Hetuda163ed2018-01-03 16:36:14 -05003605 bool isSampler = IsSampler(type.getBasicType());
3606 if(isSampler && samplersOnly)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003607 {
3608 for(int i = 0; i < type.totalRegisterCount(); i++)
3609 {
3610 shader->declareSampler(fieldRegisterIndex + i);
3611 }
3612 }
Alexis Hetu924513c2018-01-05 15:48:12 -05003613 if(isSampler == samplersOnly)
Alexis Hetuda163ed2018-01-03 16:36:14 -05003614 {
Alexis Hetu924513c2018-01-05 15:48:12 -05003615 activeUniforms.push_back(Uniform(type, name.c_str(), fieldRegisterIndex, blockId, blockInfo));
Alexis Hetuda163ed2018-01-03 16:36:14 -05003616 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003617 }
3618 else if(block)
3619 {
3620 ActiveUniformBlocks &activeUniformBlocks = shaderObject->activeUniformBlocks;
3621 const TFieldList& fields = block->fields();
3622 const TString &blockName = block->name();
3623 int fieldRegisterIndex = registerIndex;
3624 bool isUniformBlockMember = !type.isInterfaceBlock() && (blockId == -1);
3625
3626 blockId = activeUniformBlocks.size();
3627 bool isRowMajor = block->matrixPacking() == EmpRowMajor;
3628 activeUniformBlocks.push_back(UniformBlock(blockName.c_str(), 0, block->arraySize(),
3629 block->blockStorage(), isRowMajor, registerIndex, blockId));
3630 blockDefinitions.push_back(BlockDefinitionIndexMap());
3631
Alexis Hetud2742532018-01-23 16:53:41 -05003632 Std140BlockEncoder currentBlockEncoder;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003633 currentBlockEncoder.enterAggregateType();
Alexis Hetuda163ed2018-01-03 16:36:14 -05003634 for(const auto &field : fields)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003635 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003636 const TType &fieldType = *(field->type());
3637 const TString &fieldName = field->name();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003638 if(isUniformBlockMember && (fieldName == name))
3639 {
3640 registerIndex = fieldRegisterIndex;
3641 }
3642
3643 const TString uniformName = block->hasInstanceName() ? blockName + "." + fieldName : fieldName;
3644
Alexis Hetuda163ed2018-01-03 16:36:14 -05003645 declareUniform(fieldType, uniformName, fieldRegisterIndex, samplersOnly, blockId, &currentBlockEncoder);
Nicolas Capens0bac2852016-05-07 06:09:58 -04003646 fieldRegisterIndex += fieldType.totalRegisterCount();
3647 }
3648 currentBlockEncoder.exitAggregateType();
3649 activeUniformBlocks[blockId].dataSize = currentBlockEncoder.getBlockSize();
3650 }
3651 else
3652 {
Alexis Hetu924513c2018-01-05 15:48:12 -05003653 // Store struct for program link time validation
3654 shaderObject->activeUniformStructs.push_back(Uniform(type, name.c_str(), registerIndex, -1, BlockMemberInfo::getDefaultBlockInfo()));
3655
Nicolas Capens0bac2852016-05-07 06:09:58 -04003656 int fieldRegisterIndex = registerIndex;
3657
3658 const TFieldList& fields = structure->fields();
3659 if(type.isArray() && (structure || type.isInterfaceBlock()))
3660 {
3661 for(int i = 0; i < type.getArraySize(); i++)
3662 {
3663 if(encoder)
3664 {
3665 encoder->enterAggregateType();
3666 }
Alexis Hetuda163ed2018-01-03 16:36:14 -05003667 for(const auto &field : fields)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003668 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003669 const TType &fieldType = *(field->type());
3670 const TString &fieldName = field->name();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003671 const TString uniformName = name + "[" + str(i) + "]." + fieldName;
3672
Alexis Hetuda163ed2018-01-03 16:36:14 -05003673 declareUniform(fieldType, uniformName, fieldRegisterIndex, samplersOnly, blockId, encoder);
3674 fieldRegisterIndex += samplersOnly ? fieldType.totalSamplerRegisterCount() : fieldType.totalRegisterCount();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003675 }
3676 if(encoder)
3677 {
3678 encoder->exitAggregateType();
3679 }
3680 }
3681 }
3682 else
3683 {
3684 if(encoder)
3685 {
3686 encoder->enterAggregateType();
3687 }
Alexis Hetuda163ed2018-01-03 16:36:14 -05003688 for(const auto &field : fields)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003689 {
Alexis Hetuda163ed2018-01-03 16:36:14 -05003690 const TType &fieldType = *(field->type());
3691 const TString &fieldName = field->name();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003692 const TString uniformName = name + "." + fieldName;
3693
Alexis Hetuda163ed2018-01-03 16:36:14 -05003694 declareUniform(fieldType, uniformName, fieldRegisterIndex, samplersOnly, blockId, encoder);
3695 fieldRegisterIndex += samplersOnly ? fieldType.totalSamplerRegisterCount() : fieldType.totalRegisterCount();
Nicolas Capens0bac2852016-05-07 06:09:58 -04003696 }
3697 if(encoder)
3698 {
3699 encoder->exitAggregateType();
3700 }
3701 }
3702 }
3703 }
3704
Nicolas Capens0bac2852016-05-07 06:09:58 -04003705 int OutputASM::dim(TIntermNode *v)
3706 {
3707 TIntermTyped *vector = v->getAsTyped();
3708 ASSERT(vector && vector->isRegister());
3709 return vector->getNominalSize();
3710 }
3711
3712 int OutputASM::dim2(TIntermNode *m)
3713 {
3714 TIntermTyped *matrix = m->getAsTyped();
3715 ASSERT(matrix && matrix->isMatrix() && !matrix->isArray());
3716 return matrix->getSecondarySize();
3717 }
3718
3719 // Returns ~0u if no loop count could be determined
3720 unsigned int OutputASM::loopCount(TIntermLoop *node)
3721 {
3722 // Parse loops of the form:
3723 // for(int index = initial; index [comparator] limit; index += increment)
3724 TIntermSymbol *index = 0;
3725 TOperator comparator = EOpNull;
3726 int initial = 0;
3727 int limit = 0;
3728 int increment = 0;
3729
3730 // Parse index name and intial value
3731 if(node->getInit())
3732 {
3733 TIntermAggregate *init = node->getInit()->getAsAggregate();
3734
3735 if(init)
3736 {
3737 TIntermSequence &sequence = init->getSequence();
3738 TIntermTyped *variable = sequence[0]->getAsTyped();
3739
Nicolas Capense3f05552017-05-24 10:45:56 -04003740 if(variable && variable->getQualifier() == EvqTemporary && variable->getBasicType() == EbtInt)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003741 {
3742 TIntermBinary *assign = variable->getAsBinaryNode();
3743
Nicolas Capensd0bfd912017-05-24 10:20:24 -04003744 if(assign && assign->getOp() == EOpInitialize)
Nicolas Capens0bac2852016-05-07 06:09:58 -04003745 {
3746 TIntermSymbol *symbol = assign->getLeft()->getAsSymbolNode();
3747 TIntermConstantUnion *constant = assign->getRight()->getAsConstantUnion();
3748
3749 if(symbol && constant)
3750 {
3751 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3752 {
3753 index = symbol;
3754 initial = constant->getUnionArrayPointer()[0].getIConst();
3755 }
3756 }
3757 }
3758 }
3759 }
3760 }
3761
3762 // Parse comparator and limit value
3763 if(index && node->getCondition())
3764 {
3765 TIntermBinary *test = node->getCondition()->getAsBinaryNode();
Alexis Hetu7be70cf2016-05-11 10:56:43 -04003766 TIntermSymbol *left = test ? test->getLeft()->getAsSymbolNode() : nullptr;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003767
Alexis Hetu7be70cf2016-05-11 10:56:43 -04003768 if(left && (left->getId() == index->getId()))
Nicolas Capens0bac2852016-05-07 06:09:58 -04003769 {
3770 TIntermConstantUnion *constant = test->getRight()->getAsConstantUnion();
3771
3772 if(constant)
3773 {
3774 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3775 {
3776 comparator = test->getOp();
3777 limit = constant->getUnionArrayPointer()[0].getIConst();
3778 }
3779 }
3780 }
3781 }
3782
3783 // Parse increment
3784 if(index && comparator != EOpNull && node->getExpression())
3785 {
3786 TIntermBinary *binaryTerminal = node->getExpression()->getAsBinaryNode();
3787 TIntermUnary *unaryTerminal = node->getExpression()->getAsUnaryNode();
3788
3789 if(binaryTerminal)
3790 {
3791 TOperator op = binaryTerminal->getOp();
3792 TIntermConstantUnion *constant = binaryTerminal->getRight()->getAsConstantUnion();
3793
3794 if(constant)
3795 {
3796 if(constant->getBasicType() == EbtInt && constant->getNominalSize() == 1)
3797 {
3798 int value = constant->getUnionArrayPointer()[0].getIConst();
3799
3800 switch(op)
3801 {
3802 case EOpAddAssign: increment = value; break;
3803 case EOpSubAssign: increment = -value; break;
3804 default: UNIMPLEMENTED();
3805 }
3806 }
3807 }
3808 }
3809 else if(unaryTerminal)
3810 {
3811 TOperator op = unaryTerminal->getOp();
3812
3813 switch(op)
3814 {
3815 case EOpPostIncrement: increment = 1; break;
3816 case EOpPostDecrement: increment = -1; break;
3817 case EOpPreIncrement: increment = 1; break;
3818 case EOpPreDecrement: increment = -1; break;
3819 default: UNIMPLEMENTED();
3820 }
3821 }
3822 }
3823
3824 if(index && comparator != EOpNull && increment != 0)
3825 {
3826 if(comparator == EOpLessThanEqual)
3827 {
3828 comparator = EOpLessThan;
3829 limit += 1;
3830 }
Nicolas Capense3f05552017-05-24 10:45:56 -04003831 else if(comparator == EOpGreaterThanEqual)
3832 {
3833 comparator = EOpLessThan;
3834 limit -= 1;
3835 std::swap(initial, limit);
3836 increment = -increment;
3837 }
3838 else if(comparator == EOpGreaterThan)
3839 {
3840 comparator = EOpLessThan;
3841 std::swap(initial, limit);
3842 increment = -increment;
3843 }
Nicolas Capens0bac2852016-05-07 06:09:58 -04003844
3845 if(comparator == EOpLessThan)
3846 {
Nicolas Capens930b7002017-01-06 17:22:13 -05003847 if(!(initial < limit)) // Never loops
Nicolas Capens0bac2852016-05-07 06:09:58 -04003848 {
Nicolas Capens930b7002017-01-06 17:22:13 -05003849 return 0;
3850 }
3851
3852 int iterations = (limit - initial + abs(increment) - 1) / increment; // Ceiling division
3853
3854 if(iterations < 0)
3855 {
3856 return ~0u;
Nicolas Capens0bac2852016-05-07 06:09:58 -04003857 }
3858
3859 return iterations;
3860 }
3861 else UNIMPLEMENTED(); // Falls through
3862 }
3863
3864 return ~0u;
3865 }
3866
3867 bool LoopUnrollable::traverse(TIntermNode *node)
3868 {
3869 loopDepth = 0;
3870 loopUnrollable = true;
3871
3872 node->traverse(this);
3873
3874 return loopUnrollable;
3875 }
3876
3877 bool LoopUnrollable::visitLoop(Visit visit, TIntermLoop *loop)
3878 {
3879 if(visit == PreVisit)
3880 {
3881 loopDepth++;
3882 }
3883 else if(visit == PostVisit)
3884 {
3885 loopDepth++;
3886 }
3887
3888 return true;
3889 }
3890
3891 bool LoopUnrollable::visitBranch(Visit visit, TIntermBranch *node)
3892 {
3893 if(!loopUnrollable)
3894 {
3895 return false;
3896 }
3897
3898 if(!loopDepth)
3899 {
3900 return true;
3901 }
3902
3903 switch(node->getFlowOp())
3904 {
3905 case EOpKill:
3906 case EOpReturn:
3907 break;
3908 case EOpBreak:
3909 case EOpContinue:
3910 loopUnrollable = false;
3911 break;
3912 default: UNREACHABLE(node->getFlowOp());
3913 }
3914
3915 return loopUnrollable;
3916 }
3917
3918 bool LoopUnrollable::visitAggregate(Visit visit, TIntermAggregate *node)
3919 {
3920 return loopUnrollable;
3921 }
3922}