Merge vk-gl-cts/vulkan-cts-1.1.5 into vk-gl-cts/vulkan-cts-1.2.0
[platform/upstream/VK-GL-CTS.git] / external / vulkancts / modules / vulkan / spirv_assembly / vktSpvAsmInstructionTests.cpp
1 /*-------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2015 Google Inc.
6  * Copyright (c) 2016 The Khronos Group Inc.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  *//*!
21  * \file
22  * \brief SPIR-V Assembly Tests for Instructions (special opcode/operand)
23  *//*--------------------------------------------------------------------*/
24
25 #include "vktSpvAsmInstructionTests.hpp"
26
27 #include "tcuCommandLine.hpp"
28 #include "tcuFormatUtil.hpp"
29 #include "tcuFloat.hpp"
30 #include "tcuFloatFormat.hpp"
31 #include "tcuRGBA.hpp"
32 #include "tcuStringTemplate.hpp"
33 #include "tcuTestLog.hpp"
34 #include "tcuVectorUtil.hpp"
35 #include "tcuInterval.hpp"
36
37 #include "vkDefs.hpp"
38 #include "vkDeviceUtil.hpp"
39 #include "vkMemUtil.hpp"
40 #include "vkPlatform.hpp"
41 #include "vkPrograms.hpp"
42 #include "vkQueryUtil.hpp"
43 #include "vkRef.hpp"
44 #include "vkRefUtil.hpp"
45 #include "vkStrUtil.hpp"
46 #include "vkTypeUtil.hpp"
47
48 #include "deStringUtil.hpp"
49 #include "deUniquePtr.hpp"
50 #include "deMath.h"
51 #include "deRandom.hpp"
52 #include "tcuStringTemplate.hpp"
53
54 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
55 #include "vktSpvAsm8bitStorageTests.hpp"
56 #include "vktSpvAsm16bitStorageTests.hpp"
57 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
58 #include "vktSpvAsmConditionalBranchTests.hpp"
59 #include "vktSpvAsmIndexingTests.hpp"
60 #include "vktSpvAsmImageSamplerTests.hpp"
61 #include "vktSpvAsmComputeShaderCase.hpp"
62 #include "vktSpvAsmComputeShaderTestUtil.hpp"
63 #include "vktSpvAsmFloatControlsTests.hpp"
64 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
65 #include "vktSpvAsmVariablePointersTests.hpp"
66 #include "vktSpvAsmVariableInitTests.hpp"
67 #include "vktSpvAsmPointerParameterTests.hpp"
68 #include "vktSpvAsmSpirvVersion1p4Tests.hpp"
69 #include "vktSpvAsmSpirvVersionTests.hpp"
70 #include "vktTestCaseUtil.hpp"
71 #include "vktSpvAsmLoopDepLenTests.hpp"
72 #include "vktSpvAsmLoopDepInfTests.hpp"
73 #include "vktSpvAsmCompositeInsertTests.hpp"
74 #include "vktSpvAsmVaryingNameTests.hpp"
75 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
76 #include "vktSpvAsmSignedIntCompareTests.hpp"
77 #include "vktSpvAsmPtrAccessChainTests.hpp"
78 #include "vktSpvAsmFloatControlsExtensionlessTests.hpp"
79
80 #include <cmath>
81 #include <limits>
82 #include <map>
83 #include <string>
84 #include <sstream>
85 #include <utility>
86 #include <stack>
87
88 namespace vkt
89 {
90 namespace SpirVAssembly
91 {
92
93 namespace
94 {
95
96 using namespace vk;
97 using std::map;
98 using std::string;
99 using std::vector;
100 using tcu::IVec3;
101 using tcu::IVec4;
102 using tcu::RGBA;
103 using tcu::TestLog;
104 using tcu::TestStatus;
105 using tcu::Vec4;
106 using de::UniquePtr;
107 using tcu::StringTemplate;
108 using tcu::Vec4;
109
110 const bool TEST_WITH_NAN        = true;
111 const bool TEST_WITHOUT_NAN     = false;
112
113 template<typename T>
114 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
115 {
116         T* const typedPtr = (T*)dst;
117         for (int ndx = 0; ndx < numValues; ndx++)
118                 typedPtr[offset + ndx] = de::randomScalar<T>(rnd, minValue, maxValue);
119 }
120
121 // Filter is a function that returns true if a value should pass, false otherwise.
122 template<typename T, typename FilterT>
123 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
124 {
125         T* const typedPtr = (T*)dst;
126         T value;
127         for (int ndx = 0; ndx < numValues; ndx++)
128         {
129                 do
130                         value = de::randomScalar<T>(rnd, minValue, maxValue);
131                 while (!filter(value));
132
133                 typedPtr[offset + ndx] = value;
134         }
135 }
136
137 // Gets a 64-bit integer with a more logarithmic distribution
138 deInt64 randomInt64LogDistributed (de::Random& rnd)
139 {
140         deInt64 val = rnd.getUint64();
141         val &= (1ull << rnd.getInt(1, 63)) - 1;
142         if (rnd.getBool())
143                 val = -val;
144         return val;
145 }
146
147 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
148 {
149         for (int ndx = 0; ndx < numValues; ndx++)
150                 dst[ndx] = randomInt64LogDistributed(rnd);
151 }
152
153 template<typename FilterT>
154 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
155 {
156         for (int ndx = 0; ndx < numValues; ndx++)
157         {
158                 deInt64 value;
159                 do {
160                         value = randomInt64LogDistributed(rnd);
161                 } while (!filter(value));
162                 dst[ndx] = value;
163         }
164 }
165
166 inline bool filterNonNegative (const deInt64 value)
167 {
168         return value >= 0;
169 }
170
171 inline bool filterPositive (const deInt64 value)
172 {
173         return value > 0;
174 }
175
176 inline bool filterNotZero (const deInt64 value)
177 {
178         return value != 0;
179 }
180
181 static void floorAll (vector<float>& values)
182 {
183         for (size_t i = 0; i < values.size(); i++)
184                 values[i] = deFloatFloor(values[i]);
185 }
186
187 static void floorAll (vector<Vec4>& values)
188 {
189         for (size_t i = 0; i < values.size(); i++)
190                 values[i] = floor(values[i]);
191 }
192
193 struct CaseParameter
194 {
195         const char*             name;
196         string                  param;
197
198         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
199 };
200
201 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
202 //
203 // #version 430
204 //
205 // layout(std140, set = 0, binding = 0) readonly buffer Input {
206 //   float elements[];
207 // } input_data;
208 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
209 //   float elements[];
210 // } output_data;
211 //
212 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
213 //
214 // void main() {
215 //   uint x = gl_GlobalInvocationID.x;
216 //   output_data.elements[x] = -input_data.elements[x];
217 // }
218
219 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
220 {
221         std::ostringstream out;
222         out << getComputeAsmShaderPreambleWithoutLocalSize();
223
224         if (useLiteralLocalSize)
225         {
226                 out << "OpExecutionMode %main LocalSize "
227                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
228         }
229
230         out << "OpSource GLSL 430\n"
231                 "OpName %main           \"main\"\n"
232                 "OpName %id             \"gl_GlobalInvocationID\"\n"
233                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
234
235         if (useSpecConstantWorkgroupSize)
236         {
237                 out << "OpDecorate %spec_0 SpecId 100\n"
238                         << "OpDecorate %spec_1 SpecId 101\n"
239                         << "OpDecorate %spec_2 SpecId 102\n"
240                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
241         }
242
243         out << getComputeAsmInputOutputBufferTraits()
244                 << getComputeAsmCommonTypes()
245                 << getComputeAsmInputOutputBuffer()
246                 << "%id        = OpVariable %uvec3ptr Input\n"
247                 << "%zero      = OpConstant %i32 0 \n";
248
249         if (useSpecConstantWorkgroupSize)
250         {
251                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
252                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
253                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
254                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
255         }
256
257         out << "%main      = OpFunction %void None %voidf\n"
258                 << "%label     = OpLabel\n"
259                 << "%idval     = OpLoad %uvec3 %id\n"
260                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
261
262                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
263                         "%inval     = OpLoad %f32 %inloc\n"
264                         "%neg       = OpFNegate %f32 %inval\n"
265                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
266                         "             OpStore %outloc %neg\n"
267                         "             OpReturn\n"
268                         "             OpFunctionEnd\n";
269         return out.str();
270 }
271
272 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
273 {
274         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
275         ComputeShaderSpec                               spec;
276         de::Random                                              rnd                             (deStringHash(group->getName()));
277         const deUint32                                  numElements             = 64u;
278         vector<float>                                   positiveFloats  (numElements, 0);
279         vector<float>                                   negativeFloats  (numElements, 0);
280
281         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
282
283         for (size_t ndx = 0; ndx < numElements; ++ndx)
284                 negativeFloats[ndx] = -positiveFloats[ndx];
285
286         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
287         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
288
289         spec.numWorkGroups = IVec3(numElements, 1, 1);
290
291         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
292         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
293
294         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
295         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
296
297         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
298         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
299
300         spec.numWorkGroups = IVec3(1, 1, 1);
301
302         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
304
305         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
306         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
307
308         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
309         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
310
311         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
312         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
313
314         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
315         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
316
317         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
318         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
319
320         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
321         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
322
323         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
324         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
325
326         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
327         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
328
329         return group.release();
330 }
331
332 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
333 {
334         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
335         ComputeShaderSpec                               spec;
336         de::Random                                              rnd                             (deStringHash(group->getName()));
337         const int                                               numElements             = 100;
338         vector<float>                                   positiveFloats  (numElements, 0);
339         vector<float>                                   negativeFloats  (numElements, 0);
340
341         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
342
343         for (size_t ndx = 0; ndx < numElements; ++ndx)
344                 negativeFloats[ndx] = -positiveFloats[ndx];
345
346         spec.assembly =
347                 string(getComputeAsmShaderPreamble()) +
348
349                 "OpSource GLSL 430\n"
350                 "OpName %main           \"main\"\n"
351                 "OpName %id             \"gl_GlobalInvocationID\"\n"
352
353                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
354
355                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
356
357                 + string(getComputeAsmInputOutputBuffer()) +
358
359                 "%id        = OpVariable %uvec3ptr Input\n"
360                 "%zero      = OpConstant %i32 0\n"
361
362                 "%main      = OpFunction %void None %voidf\n"
363                 "%label     = OpLabel\n"
364                 "%idval     = OpLoad %uvec3 %id\n"
365                 "%x         = OpCompositeExtract %u32 %idval 0\n"
366
367                 "             OpNop\n" // Inside a function body
368
369                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
370                 "%inval     = OpLoad %f32 %inloc\n"
371                 "%neg       = OpFNegate %f32 %inval\n"
372                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
373                 "             OpStore %outloc %neg\n"
374                 "             OpReturn\n"
375                 "             OpFunctionEnd\n";
376         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
377         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
378         spec.numWorkGroups = IVec3(numElements, 1, 1);
379
380         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
381
382         return group.release();
383 }
384
385 tcu::TestCaseGroup* createUnusedVariableComputeTests (tcu::TestContext& testCtx)
386 {
387         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "unused_variables", "Compute shaders with unused variables"));
388         de::Random                                              rnd                             (deStringHash(group->getName()));
389         const int                                               numElements             = 100;
390         vector<float>                                   positiveFloats  (numElements, 0);
391         vector<float>                                   negativeFloats  (numElements, 0);
392
393         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
394
395         for (size_t ndx = 0; ndx < numElements; ++ndx)
396                 negativeFloats[ndx] = -positiveFloats[ndx];
397
398         const VariableLocation                  testLocations[] =
399         {
400                 // Set          Binding
401                 { 0,            5                       },
402                 { 5,            5                       },
403         };
404
405         for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
406         {
407                 const VariableLocation& location = testLocations[locationNdx];
408
409                 // Unused variable.
410                 {
411                         ComputeShaderSpec                               spec;
412
413                         spec.assembly =
414                                 string(getComputeAsmShaderPreamble()) +
415
416                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
417
418                                 + getUnusedDecorations(location)
419
420                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
421
422                                 + getUnusedTypesAndConstants()
423
424                                 + string(getComputeAsmInputOutputBuffer())
425
426                                 + getUnusedBuffer() +
427
428                                 "%id        = OpVariable %uvec3ptr Input\n"
429                                 "%zero      = OpConstant %i32 0\n"
430
431                                 "%main      = OpFunction %void None %voidf\n"
432                                 "%label     = OpLabel\n"
433                                 "%idval     = OpLoad %uvec3 %id\n"
434                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
435
436                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
437                                 "%inval     = OpLoad %f32 %inloc\n"
438                                 "%neg       = OpFNegate %f32 %inval\n"
439                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
440                                 "             OpStore %outloc %neg\n"
441                                 "             OpReturn\n"
442                                 "             OpFunctionEnd\n";
443                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
444                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
445                         spec.numWorkGroups = IVec3(numElements, 1, 1);
446
447                         std::string testName            = "variable_" + location.toString();
448                         std::string testDescription     = "Unused variable test with " + location.toDescription();
449
450                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
451                 }
452
453                 // Unused function.
454                 {
455                         ComputeShaderSpec                               spec;
456
457                         spec.assembly =
458                                 string(getComputeAsmShaderPreamble("", "", "", getUnusedEntryPoint())) +
459
460                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
461
462                                 + getUnusedDecorations(location)
463
464                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
465
466                                 + getUnusedTypesAndConstants() +
467
468                                 "%c_i32_0 = OpConstant %i32 0\n"
469                                 "%c_i32_1 = OpConstant %i32 1\n"
470
471                                 + string(getComputeAsmInputOutputBuffer())
472
473                                 + getUnusedBuffer() +
474
475                                 "%id        = OpVariable %uvec3ptr Input\n"
476                                 "%zero      = OpConstant %i32 0\n"
477
478                                 "%main      = OpFunction %void None %voidf\n"
479                                 "%label     = OpLabel\n"
480                                 "%idval     = OpLoad %uvec3 %id\n"
481                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
482
483                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
484                                 "%inval     = OpLoad %f32 %inloc\n"
485                                 "%neg       = OpFNegate %f32 %inval\n"
486                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
487                                 "             OpStore %outloc %neg\n"
488                                 "             OpReturn\n"
489                                 "             OpFunctionEnd\n"
490
491                                 + getUnusedFunctionBody();
492
493                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
494                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
495                         spec.numWorkGroups = IVec3(numElements, 1, 1);
496
497                         std::string testName            = "function_" + location.toString();
498                         std::string testDescription     = "Unused function test with " + location.toDescription();
499
500                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
501                 }
502         }
503
504         return group.release();
505 }
506
507 template<bool nanSupported>
508 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
509 {
510         if (outputAllocs.size() != 1)
511                 return false;
512
513         vector<deUint8> input1Bytes;
514         vector<deUint8> input2Bytes;
515         vector<deUint8> expectedBytes;
516
517         inputs[0].getBytes(input1Bytes);
518         inputs[1].getBytes(input2Bytes);
519         expectedOutputs[0].getBytes(expectedBytes);
520
521         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
522         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
523         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
524         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
525         bool returnValue                                                                = true;
526
527         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
528         {
529                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
530                         continue;
531
532                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
533                 {
534                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
535                         returnValue = false;
536                 }
537         }
538         return returnValue;
539 }
540
541 typedef VkBool32 (*compareFuncType) (float, float);
542
543 struct OpFUnordCase
544 {
545         const char*             name;
546         const char*             opCode;
547         compareFuncType compareFunc;
548
549                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
550                                                 : name                          (_name)
551                                                 , opCode                        (_opCode)
552                                                 , compareFunc           (_compareFunc) {}
553 };
554
555 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
556 do { \
557         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
558         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
559 } while (deGetFalse())
560
561 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool testWithNan)
562 {
563         const string                                    nan                             = testWithNan ? "_nan" : "";
564         const string                                    groupName               = "opfunord" + nan;
565         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
566         de::Random                                              rnd                             (deStringHash(group->getName()));
567         const int                                               numElements             = 100;
568         vector<OpFUnordCase>                    cases;
569         string                                                  extensions              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
570         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
571         string                                                  exeModes                = testWithNan ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
572         const StringTemplate                    shaderTemplate  (
573                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
574                 "OpSource GLSL 430\n"
575                 "OpName %main           \"main\"\n"
576                 "OpName %id             \"gl_GlobalInvocationID\"\n"
577
578                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
579
580                 "OpDecorate %buf BufferBlock\n"
581                 "OpDecorate %buf2 BufferBlock\n"
582                 "OpDecorate %indata1 DescriptorSet 0\n"
583                 "OpDecorate %indata1 Binding 0\n"
584                 "OpDecorate %indata2 DescriptorSet 0\n"
585                 "OpDecorate %indata2 Binding 1\n"
586                 "OpDecorate %outdata DescriptorSet 0\n"
587                 "OpDecorate %outdata Binding 2\n"
588                 "OpDecorate %f32arr ArrayStride 4\n"
589                 "OpDecorate %i32arr ArrayStride 4\n"
590                 "OpMemberDecorate %buf 0 Offset 0\n"
591                 "OpMemberDecorate %buf2 0 Offset 0\n"
592
593                 + string(getComputeAsmCommonTypes()) +
594
595                 "%buf        = OpTypeStruct %f32arr\n"
596                 "%bufptr     = OpTypePointer Uniform %buf\n"
597                 "%indata1    = OpVariable %bufptr Uniform\n"
598                 "%indata2    = OpVariable %bufptr Uniform\n"
599
600                 "%buf2       = OpTypeStruct %i32arr\n"
601                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
602                 "%outdata    = OpVariable %buf2ptr Uniform\n"
603
604                 "%id        = OpVariable %uvec3ptr Input\n"
605                 "%zero      = OpConstant %i32 0\n"
606                 "%consti1   = OpConstant %i32 1\n"
607                 "%constf1   = OpConstant %f32 1.0\n"
608
609                 "%main      = OpFunction %void None %voidf\n"
610                 "%label     = OpLabel\n"
611                 "%idval     = OpLoad %uvec3 %id\n"
612                 "%x         = OpCompositeExtract %u32 %idval 0\n"
613
614                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
615                 "%inval1    = OpLoad %f32 %inloc1\n"
616                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
617                 "%inval2    = OpLoad %f32 %inloc2\n"
618                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
619
620                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
621                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
622                 "             OpStore %outloc %int_res\n"
623
624                 "             OpReturn\n"
625                 "             OpFunctionEnd\n");
626
627         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
628         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
629         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
630         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
631         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
632         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
633
634         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
635         {
636                 map<string, string>                     specializations;
637                 ComputeShaderSpec                       spec;
638                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
639                 vector<float>                           inputFloats1    (numElements, 0);
640                 vector<float>                           inputFloats2    (numElements, 0);
641                 vector<deInt32>                         expectedInts    (numElements, 0);
642
643                 specializations["OPCODE"]       = cases[caseNdx].opCode;
644                 spec.assembly                           = shaderTemplate.specialize(specializations);
645
646                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
647                 for (size_t ndx = 0; ndx < numElements; ++ndx)
648                 {
649                         switch (ndx % 6)
650                         {
651                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
652                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
653                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
654                                 case 3:         inputFloats2[ndx] = NaN; break;
655                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
656                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
657                         }
658                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
659                 }
660
661                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
662                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
663                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
664                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
665                 spec.verifyIO           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
666
667                 if (testWithNan)
668                 {
669                         spec.extensions.push_back("VK_KHR_shader_float_controls");
670                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
671                 }
672
673                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
674         }
675
676         return group.release();
677 }
678
679 struct OpAtomicCase
680 {
681         const char*             name;
682         const char*             assembly;
683         const char*             retValAssembly;
684         OpAtomicType    opAtomic;
685         deInt32                 numOutputElements;
686
687                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
688                                                 : name                          (_name)
689                                                 , assembly                      (_assembly)
690                                                 , retValAssembly        (_retValAssembly)
691                                                 , opAtomic                      (_opAtomic)
692                                                 , numOutputElements     (_numOutputElements) {}
693 };
694
695 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false, bool volatileAtomic = false)
696 {
697         std::string                                             groupName                       ("opatomic");
698         if (useStorageBuffer)
699                 groupName += "_storage_buffer";
700         if (verifyReturnValues)
701                 groupName += "_return_values";
702         if (volatileAtomic)
703                 groupName += "_volatile";
704         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
705         vector<OpAtomicCase>                    cases;
706
707         const StringTemplate                    shaderTemplate  (
708
709                 string("OpCapability Shader\n") +
710                 (volatileAtomic ? "OpCapability VulkanMemoryModelKHR\n" : "") +
711                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
712                 (volatileAtomic ? "OpExtension \"SPV_KHR_vulkan_memory_model\"\n" : "") +
713                 (volatileAtomic ? "OpMemoryModel Logical VulkanKHR\n" : "OpMemoryModel Logical GLSL450\n") +
714                 "OpEntryPoint GLCompute %main \"main\" %id\n"
715                 "OpExecutionMode %main LocalSize 1 1 1\n" +
716
717                 "OpSource GLSL 430\n"
718                 "OpName %main           \"main\"\n"
719                 "OpName %id             \"gl_GlobalInvocationID\"\n"
720
721                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
722
723                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
724                 "OpDecorate %indata DescriptorSet 0\n"
725                 "OpDecorate %indata Binding 0\n"
726                 "OpDecorate %i32arr ArrayStride 4\n"
727                 "OpMemberDecorate %buf 0 Offset 0\n"
728
729                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
730                 "OpDecorate %sum DescriptorSet 0\n"
731                 "OpDecorate %sum Binding 1\n"
732                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
733
734                 "${RETVAL_BUF_DECORATE}"
735
736                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
737
738                 "%buf       = OpTypeStruct %i32arr\n"
739                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
740                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
741
742                 "%sumbuf    = OpTypeStruct %i32arr\n"
743                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
744                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
745
746                 "${RETVAL_BUF_DECL}"
747
748                 "%id        = OpVariable %uvec3ptr Input\n"
749                 "%minusone  = OpConstant %i32 -1\n"
750                 "%zero      = OpConstant %i32 0\n"
751                 "%one       = OpConstant %u32 1\n"
752                 "%two       = OpConstant %i32 2\n"
753                 "%five      = OpConstant %i32 5\n"
754                 "%volbit    = OpConstant %i32 32768\n"
755
756                 "%main      = OpFunction %void None %voidf\n"
757                 "%label     = OpLabel\n"
758                 "%idval     = OpLoad %uvec3 %id\n"
759                 "%x         = OpCompositeExtract %u32 %idval 0\n"
760
761                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
762                 "%inval     = OpLoad %i32 %inloc\n"
763
764                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
765                 "${INSTRUCTION}"
766                 "${RETVAL_ASSEMBLY}"
767
768                 "             OpReturn\n"
769                 "             OpFunctionEnd\n");
770
771         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
772         do { \
773                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
774                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
775         } while (deGetFalse())
776         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
777         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
778
779         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc ${SCOPE} ${SEMANTICS} %inval\n",
780                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
781         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc ${SCOPE} ${SEMANTICS} %inval\n",
782                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
783         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc ${SCOPE} ${SEMANTICS}\n",
784                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
785         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc ${SCOPE} ${SEMANTICS}\n",
786                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
787         if (!verifyReturnValues)
788         {
789                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc ${SCOPE} ${SEMANTICS}\n"
790                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
791                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc ${SCOPE} ${SEMANTICS} %inval\n", "", OPATOMIC_STORE );
792         }
793
794         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
795                                                                 "             OpStore %outloc %even\n"
796                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc ${SCOPE} ${SEMANTICS} ${SEMANTICS} %minusone %zero\n",
797                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
798
799
800         #undef ADD_OPATOMIC_CASE
801         #undef ADD_OPATOMIC_CASE_1
802         #undef ADD_OPATOMIC_CASE_N
803
804         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
805         {
806                 map<string, string>                     specializations;
807                 ComputeShaderSpec                       spec;
808                 vector<deInt32>                         inputInts               (numElements, 0);
809                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
810
811                 if (volatileAtomic)
812                 {
813                         spec.extensions.push_back("VK_KHR_vulkan_memory_model");
814                         // volatile, queuefamily scope
815                         specializations["SEMANTICS"] = "%volbit";
816                         specializations["SCOPE"] = "%five";
817                 }
818                 else
819                 {
820                         // non-volatile, device scope
821                         specializations["SEMANTICS"] = "%zero";
822                         specializations["SCOPE"] = "%one";
823                 }
824                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
825                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
826                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
827                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
828
829                 if (verifyReturnValues)
830                 {
831                         const StringTemplate blockDecoration    (
832                                 "\n"
833                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
834                                 "OpDecorate %ret DescriptorSet 0\n"
835                                 "OpDecorate %ret Binding 2\n"
836                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
837
838                         const StringTemplate blockDeclaration   (
839                                 "\n"
840                                 "%retbuf    = OpTypeStruct %i32arr\n"
841                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
842                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
843
844                         specializations["RETVAL_ASSEMBLY"] =
845                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
846                                 + std::string(cases[caseNdx].retValAssembly);
847
848                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
849                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
850                 }
851                 else
852                 {
853                         specializations["RETVAL_ASSEMBLY"]              = "";
854                         specializations["RETVAL_BUF_DECORATE"]  = "";
855                         specializations["RETVAL_BUF_DECL"]              = "";
856                 }
857
858                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
859
860                 // Specialize one more time, to catch things that were in a template parameter
861                 const StringTemplate                                    assemblyTemplate(spec.assembly);
862                 spec.assembly                                                   = assemblyTemplate.specialize(specializations);
863
864                 if (useStorageBuffer)
865                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
866
867                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
868                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
869                 if (verifyReturnValues)
870                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
871                 spec.numWorkGroups = IVec3(numElements, 1, 1);
872
873                 if (verifyReturnValues)
874                 {
875                         switch (cases[caseNdx].opAtomic)
876                         {
877                                 case OPATOMIC_IADD:
878                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
879                                         break;
880                                 case OPATOMIC_ISUB:
881                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
882                                         break;
883                                 case OPATOMIC_IINC:
884                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
885                                         break;
886                                 case OPATOMIC_IDEC:
887                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
888                                         break;
889                                 case OPATOMIC_COMPEX:
890                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
891                                         break;
892                                 default:
893                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
894                         }
895                 }
896                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
897         }
898
899         return group.release();
900 }
901
902 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
903 {
904         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
905         ComputeShaderSpec                               spec;
906         de::Random                                              rnd                             (deStringHash(group->getName()));
907         const int                                               numElements             = 100;
908         vector<float>                                   positiveFloats  (numElements, 0);
909         vector<float>                                   negativeFloats  (numElements, 0);
910
911         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
912
913         for (size_t ndx = 0; ndx < numElements; ++ndx)
914                 negativeFloats[ndx] = -positiveFloats[ndx];
915
916         spec.assembly =
917                 string(getComputeAsmShaderPreamble()) +
918
919                 "%fname1 = OpString \"negateInputs.comp\"\n"
920                 "%fname2 = OpString \"negateInputs\"\n"
921
922                 "OpSource GLSL 430\n"
923                 "OpName %main           \"main\"\n"
924                 "OpName %id             \"gl_GlobalInvocationID\"\n"
925
926                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
927
928                 + string(getComputeAsmInputOutputBufferTraits()) +
929
930                 "OpLine %fname1 0 0\n" // At the earliest possible position
931
932                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
933
934                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
935                 "OpLine %fname2 1 0\n" // Different filenames
936                 "OpLine %fname1 1000 100000\n"
937
938                 "%id        = OpVariable %uvec3ptr Input\n"
939                 "%zero      = OpConstant %i32 0\n"
940
941                 "OpLine %fname1 1 1\n" // Before a function
942
943                 "%main      = OpFunction %void None %voidf\n"
944                 "%label     = OpLabel\n"
945
946                 "OpLine %fname1 1 1\n" // In a function
947
948                 "%idval     = OpLoad %uvec3 %id\n"
949                 "%x         = OpCompositeExtract %u32 %idval 0\n"
950                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
951                 "%inval     = OpLoad %f32 %inloc\n"
952                 "%neg       = OpFNegate %f32 %inval\n"
953                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
954                 "             OpStore %outloc %neg\n"
955                 "             OpReturn\n"
956                 "             OpFunctionEnd\n";
957         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
958         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
959         spec.numWorkGroups = IVec3(numElements, 1, 1);
960
961         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
962
963         return group.release();
964 }
965
966 bool veryfiBinaryShader (const ProgramBinary& binary)
967 {
968         const size_t    paternCount                     = 3u;
969         bool paternsCheck[paternCount]          =
970         {
971                 false, false, false
972         };
973         const string patersns[paternCount]      =
974         {
975                 "VULKAN CTS",
976                 "Negative values",
977                 "Date: 2017/09/21"
978         };
979         size_t                  paternNdx               = 0u;
980
981         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
982         {
983                 if (false == paternsCheck[paternNdx] &&
984                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
985                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
986                 {
987                         paternsCheck[paternNdx]= true;
988                         paternNdx++;
989                         if (paternNdx == paternCount)
990                                 break;
991                 }
992         }
993
994         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
995         {
996                 if (!paternsCheck[ndx])
997                         return false;
998         }
999
1000         return true;
1001 }
1002
1003 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
1004 {
1005         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
1006         ComputeShaderSpec                               spec;
1007         de::Random                                              rnd                             (deStringHash(group->getName()));
1008         const int                                               numElements             = 10;
1009         vector<float>                                   positiveFloats  (numElements, 0);
1010         vector<float>                                   negativeFloats  (numElements, 0);
1011
1012         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
1013
1014         for (size_t ndx = 0; ndx < numElements; ++ndx)
1015                 negativeFloats[ndx] = -positiveFloats[ndx];
1016
1017         spec.assembly =
1018                 string(getComputeAsmShaderPreamble()) +
1019                 "%fname = OpString \"negateInputs.comp\"\n"
1020
1021                 "OpSource GLSL 430\n"
1022                 "OpName %main           \"main\"\n"
1023                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1024                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
1025                 "OpModuleProcessed \"Negative values\"\n"
1026                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
1027                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1028
1029                 + string(getComputeAsmInputOutputBufferTraits())
1030
1031                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1032
1033                 "OpLine %fname 0 1\n"
1034
1035                 "OpLine %fname 1000 1\n"
1036
1037                 "%id        = OpVariable %uvec3ptr Input\n"
1038                 "%zero      = OpConstant %i32 0\n"
1039                 "%main      = OpFunction %void None %voidf\n"
1040
1041                 "%label     = OpLabel\n"
1042                 "%idval     = OpLoad %uvec3 %id\n"
1043                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1044
1045                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1046                 "%inval     = OpLoad %f32 %inloc\n"
1047                 "%neg       = OpFNegate %f32 %inval\n"
1048                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1049                 "             OpStore %outloc %neg\n"
1050                 "             OpReturn\n"
1051                 "             OpFunctionEnd\n";
1052         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1053         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1054         spec.numWorkGroups = IVec3(numElements, 1, 1);
1055         spec.verifyBinary = veryfiBinaryShader;
1056         spec.spirvVersion = SPIRV_VERSION_1_3;
1057
1058         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
1059
1060         return group.release();
1061 }
1062
1063 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
1064 {
1065         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
1066         ComputeShaderSpec                               spec;
1067         de::Random                                              rnd                             (deStringHash(group->getName()));
1068         const int                                               numElements             = 100;
1069         vector<float>                                   positiveFloats  (numElements, 0);
1070         vector<float>                                   negativeFloats  (numElements, 0);
1071
1072         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
1073
1074         for (size_t ndx = 0; ndx < numElements; ++ndx)
1075                 negativeFloats[ndx] = -positiveFloats[ndx];
1076
1077         spec.assembly =
1078                 string(getComputeAsmShaderPreamble()) +
1079
1080                 "%fname = OpString \"negateInputs.comp\"\n"
1081
1082                 "OpSource GLSL 430\n"
1083                 "OpName %main           \"main\"\n"
1084                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1085
1086                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1087
1088                 + string(getComputeAsmInputOutputBufferTraits()) +
1089
1090                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
1091
1092                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1093
1094                 "OpLine %fname 0 1\n"
1095                 "OpNoLine\n" // Immediately following a preceding OpLine
1096
1097                 "OpLine %fname 1000 1\n"
1098
1099                 "%id        = OpVariable %uvec3ptr Input\n"
1100                 "%zero      = OpConstant %i32 0\n"
1101
1102                 "OpNoLine\n" // Contents after the previous OpLine
1103
1104                 "%main      = OpFunction %void None %voidf\n"
1105                 "%label     = OpLabel\n"
1106                 "%idval     = OpLoad %uvec3 %id\n"
1107                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1108
1109                 "OpNoLine\n" // Multiple OpNoLine
1110                 "OpNoLine\n"
1111                 "OpNoLine\n"
1112
1113                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1114                 "%inval     = OpLoad %f32 %inloc\n"
1115                 "%neg       = OpFNegate %f32 %inval\n"
1116                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1117                 "             OpStore %outloc %neg\n"
1118                 "             OpReturn\n"
1119                 "             OpFunctionEnd\n";
1120         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1121         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1122         spec.numWorkGroups = IVec3(numElements, 1, 1);
1123
1124         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
1125
1126         return group.release();
1127 }
1128
1129 // Compare instruction for the contraction compute case.
1130 // Returns true if the output is what is expected from the test case.
1131 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1132 {
1133         if (outputAllocs.size() != 1)
1134                 return false;
1135
1136         // Only size is needed because we are not comparing the exact values.
1137         size_t byteSize = expectedOutputs[0].getByteSize();
1138
1139         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1140
1141         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
1142                 if (outputAsFloat[i] != 0.f &&
1143                         outputAsFloat[i] != -ldexp(1, -24)) {
1144                         return false;
1145                 }
1146         }
1147
1148         return true;
1149 }
1150
1151 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1152 {
1153         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1154         vector<CaseParameter>                   cases;
1155         const int                                               numElements             = 100;
1156         vector<float>                                   inputFloats1    (numElements, 0);
1157         vector<float>                                   inputFloats2    (numElements, 0);
1158         vector<float>                                   outputFloats    (numElements, 0);
1159         const StringTemplate                    shaderTemplate  (
1160                 string(getComputeAsmShaderPreamble()) +
1161
1162                 "OpName %main           \"main\"\n"
1163                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1164
1165                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1166
1167                 "${DECORATION}\n"
1168
1169                 "OpDecorate %buf BufferBlock\n"
1170                 "OpDecorate %indata1 DescriptorSet 0\n"
1171                 "OpDecorate %indata1 Binding 0\n"
1172                 "OpDecorate %indata2 DescriptorSet 0\n"
1173                 "OpDecorate %indata2 Binding 1\n"
1174                 "OpDecorate %outdata DescriptorSet 0\n"
1175                 "OpDecorate %outdata Binding 2\n"
1176                 "OpDecorate %f32arr ArrayStride 4\n"
1177                 "OpMemberDecorate %buf 0 Offset 0\n"
1178
1179                 + string(getComputeAsmCommonTypes()) +
1180
1181                 "%buf        = OpTypeStruct %f32arr\n"
1182                 "%bufptr     = OpTypePointer Uniform %buf\n"
1183                 "%indata1    = OpVariable %bufptr Uniform\n"
1184                 "%indata2    = OpVariable %bufptr Uniform\n"
1185                 "%outdata    = OpVariable %bufptr Uniform\n"
1186
1187                 "%id         = OpVariable %uvec3ptr Input\n"
1188                 "%zero       = OpConstant %i32 0\n"
1189                 "%c_f_m1     = OpConstant %f32 -1.\n"
1190
1191                 "%main       = OpFunction %void None %voidf\n"
1192                 "%label      = OpLabel\n"
1193                 "%idval      = OpLoad %uvec3 %id\n"
1194                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1195                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1196                 "%inval1     = OpLoad %f32 %inloc1\n"
1197                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1198                 "%inval2     = OpLoad %f32 %inloc2\n"
1199                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1200                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1201                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1202                 "              OpStore %outloc %add\n"
1203                 "              OpReturn\n"
1204                 "              OpFunctionEnd\n");
1205
1206         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1207         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1208         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1209
1210         for (size_t ndx = 0; ndx < numElements; ++ndx)
1211         {
1212                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1213                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1214                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1215                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1216                 // So the final result will be 0.f or 0x1p-24.
1217                 // If the operation is combined into a precise fused multiply-add, then the result would be
1218                 // 2^-46 (0xa8800000).
1219                 outputFloats[ndx]       = 0.f;
1220         }
1221
1222         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1223         {
1224                 map<string, string>             specializations;
1225                 ComputeShaderSpec               spec;
1226
1227                 specializations["DECORATION"] = cases[caseNdx].param;
1228                 spec.assembly = shaderTemplate.specialize(specializations);
1229                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1230                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1231                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1232                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1233                 // Check against the two possible answers based on rounding mode.
1234                 spec.verifyIO = &compareNoContractCase;
1235
1236                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1237         }
1238         return group.release();
1239 }
1240
1241 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1242 {
1243         if (outputAllocs.size() != 1)
1244                 return false;
1245
1246         vector<deUint8> expectedBytes;
1247         expectedOutputs[0].getBytes(expectedBytes);
1248
1249         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1250         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1251
1252         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1253         {
1254                 const float f0 = expectedOutputAsFloat[idx];
1255                 const float f1 = outputAsFloat[idx];
1256                 // \todo relative error needs to be fairly high because FRem may be implemented as
1257                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1258                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1259                         return false;
1260         }
1261
1262         return true;
1263 }
1264
1265 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1266 {
1267         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1268         ComputeShaderSpec                               spec;
1269         de::Random                                              rnd                             (deStringHash(group->getName()));
1270         const int                                               numElements             = 200;
1271         vector<float>                                   inputFloats1    (numElements, 0);
1272         vector<float>                                   inputFloats2    (numElements, 0);
1273         vector<float>                                   outputFloats    (numElements, 0);
1274
1275         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1276         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1277
1278         for (size_t ndx = 0; ndx < numElements; ++ndx)
1279         {
1280                 // Guard against divisors near zero.
1281                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1282                         inputFloats2[ndx] = 8.f;
1283
1284                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1285                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1286         }
1287
1288         spec.assembly =
1289                 string(getComputeAsmShaderPreamble()) +
1290
1291                 "OpName %main           \"main\"\n"
1292                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1293
1294                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1295
1296                 "OpDecorate %buf BufferBlock\n"
1297                 "OpDecorate %indata1 DescriptorSet 0\n"
1298                 "OpDecorate %indata1 Binding 0\n"
1299                 "OpDecorate %indata2 DescriptorSet 0\n"
1300                 "OpDecorate %indata2 Binding 1\n"
1301                 "OpDecorate %outdata DescriptorSet 0\n"
1302                 "OpDecorate %outdata Binding 2\n"
1303                 "OpDecorate %f32arr ArrayStride 4\n"
1304                 "OpMemberDecorate %buf 0 Offset 0\n"
1305
1306                 + string(getComputeAsmCommonTypes()) +
1307
1308                 "%buf        = OpTypeStruct %f32arr\n"
1309                 "%bufptr     = OpTypePointer Uniform %buf\n"
1310                 "%indata1    = OpVariable %bufptr Uniform\n"
1311                 "%indata2    = OpVariable %bufptr Uniform\n"
1312                 "%outdata    = OpVariable %bufptr Uniform\n"
1313
1314                 "%id        = OpVariable %uvec3ptr Input\n"
1315                 "%zero      = OpConstant %i32 0\n"
1316
1317                 "%main      = OpFunction %void None %voidf\n"
1318                 "%label     = OpLabel\n"
1319                 "%idval     = OpLoad %uvec3 %id\n"
1320                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1321                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1322                 "%inval1    = OpLoad %f32 %inloc1\n"
1323                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1324                 "%inval2    = OpLoad %f32 %inloc2\n"
1325                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1326                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1327                 "             OpStore %outloc %rem\n"
1328                 "             OpReturn\n"
1329                 "             OpFunctionEnd\n";
1330
1331         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1332         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1333         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1334         spec.numWorkGroups = IVec3(numElements, 1, 1);
1335         spec.verifyIO = &compareFRem;
1336
1337         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1338
1339         return group.release();
1340 }
1341
1342 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1343 {
1344         if (outputAllocs.size() != 1)
1345                 return false;
1346
1347         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1348         std::vector<deUint8>    data;
1349         expectedOutput->getBytes(data);
1350
1351         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1352         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1353
1354         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1355         {
1356                 const float f0 = expectedOutputAsFloat[idx];
1357                 const float f1 = outputAsFloat[idx];
1358
1359                 // For NMin, we accept NaN as output if both inputs were NaN.
1360                 // Otherwise the NaN is the wrong choise, as on architectures that
1361                 // do not handle NaN, those are huge values.
1362                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1363                         return false;
1364         }
1365
1366         return true;
1367 }
1368
1369 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1370 {
1371         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1372         ComputeShaderSpec                               spec;
1373         de::Random                                              rnd                             (deStringHash(group->getName()));
1374         const int                                               numElements             = 200;
1375         vector<float>                                   inputFloats1    (numElements, 0);
1376         vector<float>                                   inputFloats2    (numElements, 0);
1377         vector<float>                                   outputFloats    (numElements, 0);
1378
1379         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1380         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1381
1382         // Make the first case a full-NAN case.
1383         inputFloats1[0] = TCU_NAN;
1384         inputFloats2[0] = TCU_NAN;
1385
1386         for (size_t ndx = 0; ndx < numElements; ++ndx)
1387         {
1388                 // By default, pick the smallest
1389                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1390
1391                 // Make half of the cases NaN cases
1392                 if ((ndx & 1) == 0)
1393                 {
1394                         // Alternate between the NaN operand
1395                         if ((ndx & 2) == 0)
1396                         {
1397                                 outputFloats[ndx] = inputFloats2[ndx];
1398                                 inputFloats1[ndx] = TCU_NAN;
1399                         }
1400                         else
1401                         {
1402                                 outputFloats[ndx] = inputFloats1[ndx];
1403                                 inputFloats2[ndx] = TCU_NAN;
1404                         }
1405                 }
1406         }
1407
1408         spec.assembly =
1409                 "OpCapability Shader\n"
1410                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1411                 "OpMemoryModel Logical GLSL450\n"
1412                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1413                 "OpExecutionMode %main LocalSize 1 1 1\n"
1414
1415                 "OpName %main           \"main\"\n"
1416                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1417
1418                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1419
1420                 "OpDecorate %buf BufferBlock\n"
1421                 "OpDecorate %indata1 DescriptorSet 0\n"
1422                 "OpDecorate %indata1 Binding 0\n"
1423                 "OpDecorate %indata2 DescriptorSet 0\n"
1424                 "OpDecorate %indata2 Binding 1\n"
1425                 "OpDecorate %outdata DescriptorSet 0\n"
1426                 "OpDecorate %outdata Binding 2\n"
1427                 "OpDecorate %f32arr ArrayStride 4\n"
1428                 "OpMemberDecorate %buf 0 Offset 0\n"
1429
1430                 + string(getComputeAsmCommonTypes()) +
1431
1432                 "%buf        = OpTypeStruct %f32arr\n"
1433                 "%bufptr     = OpTypePointer Uniform %buf\n"
1434                 "%indata1    = OpVariable %bufptr Uniform\n"
1435                 "%indata2    = OpVariable %bufptr Uniform\n"
1436                 "%outdata    = OpVariable %bufptr Uniform\n"
1437
1438                 "%id        = OpVariable %uvec3ptr Input\n"
1439                 "%zero      = OpConstant %i32 0\n"
1440
1441                 "%main      = OpFunction %void None %voidf\n"
1442                 "%label     = OpLabel\n"
1443                 "%idval     = OpLoad %uvec3 %id\n"
1444                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1445                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1446                 "%inval1    = OpLoad %f32 %inloc1\n"
1447                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1448                 "%inval2    = OpLoad %f32 %inloc2\n"
1449                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1450                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1451                 "             OpStore %outloc %rem\n"
1452                 "             OpReturn\n"
1453                 "             OpFunctionEnd\n";
1454
1455         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1456         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1457         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1458         spec.numWorkGroups = IVec3(numElements, 1, 1);
1459         spec.verifyIO = &compareNMin;
1460
1461         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1462
1463         return group.release();
1464 }
1465
1466 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1467 {
1468         if (outputAllocs.size() != 1)
1469                 return false;
1470
1471         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1472         std::vector<deUint8>    data;
1473         expectedOutput->getBytes(data);
1474
1475         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1476         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1477
1478         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1479         {
1480                 const float f0 = expectedOutputAsFloat[idx];
1481                 const float f1 = outputAsFloat[idx];
1482
1483                 // For NMax, NaN is considered acceptable result, since in
1484                 // architectures that do not handle NaNs, those are huge values.
1485                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1486                         return false;
1487         }
1488
1489         return true;
1490 }
1491
1492 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1493 {
1494         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1495         ComputeShaderSpec                               spec;
1496         de::Random                                              rnd                             (deStringHash(group->getName()));
1497         const int                                               numElements             = 200;
1498         vector<float>                                   inputFloats1    (numElements, 0);
1499         vector<float>                                   inputFloats2    (numElements, 0);
1500         vector<float>                                   outputFloats    (numElements, 0);
1501
1502         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1503         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1504
1505         // Make the first case a full-NAN case.
1506         inputFloats1[0] = TCU_NAN;
1507         inputFloats2[0] = TCU_NAN;
1508
1509         for (size_t ndx = 0; ndx < numElements; ++ndx)
1510         {
1511                 // By default, pick the biggest
1512                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1513
1514                 // Make half of the cases NaN cases
1515                 if ((ndx & 1) == 0)
1516                 {
1517                         // Alternate between the NaN operand
1518                         if ((ndx & 2) == 0)
1519                         {
1520                                 outputFloats[ndx] = inputFloats2[ndx];
1521                                 inputFloats1[ndx] = TCU_NAN;
1522                         }
1523                         else
1524                         {
1525                                 outputFloats[ndx] = inputFloats1[ndx];
1526                                 inputFloats2[ndx] = TCU_NAN;
1527                         }
1528                 }
1529         }
1530
1531         spec.assembly =
1532                 "OpCapability Shader\n"
1533                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1534                 "OpMemoryModel Logical GLSL450\n"
1535                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1536                 "OpExecutionMode %main LocalSize 1 1 1\n"
1537
1538                 "OpName %main           \"main\"\n"
1539                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1540
1541                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1542
1543                 "OpDecorate %buf BufferBlock\n"
1544                 "OpDecorate %indata1 DescriptorSet 0\n"
1545                 "OpDecorate %indata1 Binding 0\n"
1546                 "OpDecorate %indata2 DescriptorSet 0\n"
1547                 "OpDecorate %indata2 Binding 1\n"
1548                 "OpDecorate %outdata DescriptorSet 0\n"
1549                 "OpDecorate %outdata Binding 2\n"
1550                 "OpDecorate %f32arr ArrayStride 4\n"
1551                 "OpMemberDecorate %buf 0 Offset 0\n"
1552
1553                 + string(getComputeAsmCommonTypes()) +
1554
1555                 "%buf        = OpTypeStruct %f32arr\n"
1556                 "%bufptr     = OpTypePointer Uniform %buf\n"
1557                 "%indata1    = OpVariable %bufptr Uniform\n"
1558                 "%indata2    = OpVariable %bufptr Uniform\n"
1559                 "%outdata    = OpVariable %bufptr Uniform\n"
1560
1561                 "%id        = OpVariable %uvec3ptr Input\n"
1562                 "%zero      = OpConstant %i32 0\n"
1563
1564                 "%main      = OpFunction %void None %voidf\n"
1565                 "%label     = OpLabel\n"
1566                 "%idval     = OpLoad %uvec3 %id\n"
1567                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1568                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1569                 "%inval1    = OpLoad %f32 %inloc1\n"
1570                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1571                 "%inval2    = OpLoad %f32 %inloc2\n"
1572                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1573                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1574                 "             OpStore %outloc %rem\n"
1575                 "             OpReturn\n"
1576                 "             OpFunctionEnd\n";
1577
1578         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1579         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1580         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1581         spec.numWorkGroups = IVec3(numElements, 1, 1);
1582         spec.verifyIO = &compareNMax;
1583
1584         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1585
1586         return group.release();
1587 }
1588
1589 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1590 {
1591         if (outputAllocs.size() != 1)
1592                 return false;
1593
1594         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1595         std::vector<deUint8>    data;
1596         expectedOutput->getBytes(data);
1597
1598         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1599         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1600
1601         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1602         {
1603                 const float e0 = expectedOutputAsFloat[idx * 2];
1604                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1605                 const float res = outputAsFloat[idx];
1606
1607                 // For NClamp, we have two possible outcomes based on
1608                 // whether NaNs are handled or not.
1609                 // If either min or max value is NaN, the result is undefined,
1610                 // so this test doesn't stress those. If the clamped value is
1611                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1612                 // handled, they are big values that result in max.
1613                 // If all three parameters are NaN, the result should be NaN.
1614                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1615                          (deFloatAbs(e0 - res) < 0.00001f) ||
1616                          (deFloatAbs(e1 - res) < 0.00001f)))
1617                         return false;
1618         }
1619
1620         return true;
1621 }
1622
1623 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1624 {
1625         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1626         ComputeShaderSpec                               spec;
1627         de::Random                                              rnd                             (deStringHash(group->getName()));
1628         const int                                               numElements             = 200;
1629         vector<float>                                   inputFloats1    (numElements, 0);
1630         vector<float>                                   inputFloats2    (numElements, 0);
1631         vector<float>                                   inputFloats3    (numElements, 0);
1632         vector<float>                                   outputFloats    (numElements * 2, 0);
1633
1634         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1635         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1636         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1637
1638         for (size_t ndx = 0; ndx < numElements; ++ndx)
1639         {
1640                 // Results are only defined if max value is bigger than min value.
1641                 if (inputFloats2[ndx] > inputFloats3[ndx])
1642                 {
1643                         float t = inputFloats2[ndx];
1644                         inputFloats2[ndx] = inputFloats3[ndx];
1645                         inputFloats3[ndx] = t;
1646                 }
1647
1648                 // By default, do the clamp, setting both possible answers
1649                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1650
1651                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1652                 float maxResB = maxResA;
1653
1654                 // Alternate between the NaN cases
1655                 if (ndx & 1)
1656                 {
1657                         inputFloats1[ndx] = TCU_NAN;
1658                         // If NaN is handled, the result should be same as the clamp minimum.
1659                         // If NaN is not handled, the result should clamp to the clamp maximum.
1660                         maxResA = inputFloats2[ndx];
1661                         maxResB = inputFloats3[ndx];
1662                 }
1663                 else
1664                 {
1665                         // Not a NaN case - only one legal result.
1666                         maxResA = defaultRes;
1667                         maxResB = defaultRes;
1668                 }
1669
1670                 outputFloats[ndx * 2] = maxResA;
1671                 outputFloats[ndx * 2 + 1] = maxResB;
1672         }
1673
1674         // Make the first case a full-NAN case.
1675         inputFloats1[0] = TCU_NAN;
1676         inputFloats2[0] = TCU_NAN;
1677         inputFloats3[0] = TCU_NAN;
1678         outputFloats[0] = TCU_NAN;
1679         outputFloats[1] = TCU_NAN;
1680
1681         spec.assembly =
1682                 "OpCapability Shader\n"
1683                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1684                 "OpMemoryModel Logical GLSL450\n"
1685                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1686                 "OpExecutionMode %main LocalSize 1 1 1\n"
1687
1688                 "OpName %main           \"main\"\n"
1689                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1690
1691                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1692
1693                 "OpDecorate %buf BufferBlock\n"
1694                 "OpDecorate %indata1 DescriptorSet 0\n"
1695                 "OpDecorate %indata1 Binding 0\n"
1696                 "OpDecorate %indata2 DescriptorSet 0\n"
1697                 "OpDecorate %indata2 Binding 1\n"
1698                 "OpDecorate %indata3 DescriptorSet 0\n"
1699                 "OpDecorate %indata3 Binding 2\n"
1700                 "OpDecorate %outdata DescriptorSet 0\n"
1701                 "OpDecorate %outdata Binding 3\n"
1702                 "OpDecorate %f32arr ArrayStride 4\n"
1703                 "OpMemberDecorate %buf 0 Offset 0\n"
1704
1705                 + string(getComputeAsmCommonTypes()) +
1706
1707                 "%buf        = OpTypeStruct %f32arr\n"
1708                 "%bufptr     = OpTypePointer Uniform %buf\n"
1709                 "%indata1    = OpVariable %bufptr Uniform\n"
1710                 "%indata2    = OpVariable %bufptr Uniform\n"
1711                 "%indata3    = OpVariable %bufptr Uniform\n"
1712                 "%outdata    = OpVariable %bufptr Uniform\n"
1713
1714                 "%id        = OpVariable %uvec3ptr Input\n"
1715                 "%zero      = OpConstant %i32 0\n"
1716
1717                 "%main      = OpFunction %void None %voidf\n"
1718                 "%label     = OpLabel\n"
1719                 "%idval     = OpLoad %uvec3 %id\n"
1720                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1721                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1722                 "%inval1    = OpLoad %f32 %inloc1\n"
1723                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1724                 "%inval2    = OpLoad %f32 %inloc2\n"
1725                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1726                 "%inval3    = OpLoad %f32 %inloc3\n"
1727                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1728                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1729                 "             OpStore %outloc %rem\n"
1730                 "             OpReturn\n"
1731                 "             OpFunctionEnd\n";
1732
1733         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1734         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1735         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1736         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1737         spec.numWorkGroups = IVec3(numElements, 1, 1);
1738         spec.verifyIO = &compareNClamp;
1739
1740         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1741
1742         return group.release();
1743 }
1744
1745 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1746 {
1747         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1748         de::Random                                              rnd                             (deStringHash(group->getName()));
1749         const int                                               numElements             = 200;
1750
1751         const struct CaseParams
1752         {
1753                 const char*             name;
1754                 const char*             failMessage;            // customized status message
1755                 qpTestResult    failResult;                     // override status on failure
1756                 int                             op1Min, op1Max;         // operand ranges
1757                 int                             op2Min, op2Max;
1758         } cases[] =
1759         {
1760                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1761                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1762         };
1763         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1764
1765         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1766         {
1767                 const CaseParams&       params          = cases[caseNdx];
1768                 ComputeShaderSpec       spec;
1769                 vector<deInt32>         inputInts1      (numElements, 0);
1770                 vector<deInt32>         inputInts2      (numElements, 0);
1771                 vector<deInt32>         outputInts      (numElements, 0);
1772
1773                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1774                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1775
1776                 for (int ndx = 0; ndx < numElements; ++ndx)
1777                 {
1778                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1779                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1780                 }
1781
1782                 spec.assembly =
1783                         string(getComputeAsmShaderPreamble()) +
1784
1785                         "OpName %main           \"main\"\n"
1786                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1787
1788                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1789
1790                         "OpDecorate %buf BufferBlock\n"
1791                         "OpDecorate %indata1 DescriptorSet 0\n"
1792                         "OpDecorate %indata1 Binding 0\n"
1793                         "OpDecorate %indata2 DescriptorSet 0\n"
1794                         "OpDecorate %indata2 Binding 1\n"
1795                         "OpDecorate %outdata DescriptorSet 0\n"
1796                         "OpDecorate %outdata Binding 2\n"
1797                         "OpDecorate %i32arr ArrayStride 4\n"
1798                         "OpMemberDecorate %buf 0 Offset 0\n"
1799
1800                         + string(getComputeAsmCommonTypes()) +
1801
1802                         "%buf        = OpTypeStruct %i32arr\n"
1803                         "%bufptr     = OpTypePointer Uniform %buf\n"
1804                         "%indata1    = OpVariable %bufptr Uniform\n"
1805                         "%indata2    = OpVariable %bufptr Uniform\n"
1806                         "%outdata    = OpVariable %bufptr Uniform\n"
1807
1808                         "%id        = OpVariable %uvec3ptr Input\n"
1809                         "%zero      = OpConstant %i32 0\n"
1810
1811                         "%main      = OpFunction %void None %voidf\n"
1812                         "%label     = OpLabel\n"
1813                         "%idval     = OpLoad %uvec3 %id\n"
1814                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1815                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1816                         "%inval1    = OpLoad %i32 %inloc1\n"
1817                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1818                         "%inval2    = OpLoad %i32 %inloc2\n"
1819                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1820                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1821                         "             OpStore %outloc %rem\n"
1822                         "             OpReturn\n"
1823                         "             OpFunctionEnd\n";
1824
1825                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1826                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1827                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1828                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1829                 spec.failResult                 = params.failResult;
1830                 spec.failMessage                = params.failMessage;
1831
1832                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1833         }
1834
1835         return group.release();
1836 }
1837
1838 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1839 {
1840         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1841         de::Random                                              rnd                             (deStringHash(group->getName()));
1842         const int                                               numElements             = 200;
1843
1844         const struct CaseParams
1845         {
1846                 const char*             name;
1847                 const char*             failMessage;            // customized status message
1848                 qpTestResult    failResult;                     // override status on failure
1849                 bool                    positive;
1850         } cases[] =
1851         {
1852                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1853                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1854         };
1855         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1856
1857         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1858         {
1859                 const CaseParams&       params          = cases[caseNdx];
1860                 ComputeShaderSpec       spec;
1861                 vector<deInt64>         inputInts1      (numElements, 0);
1862                 vector<deInt64>         inputInts2      (numElements, 0);
1863                 vector<deInt64>         outputInts      (numElements, 0);
1864
1865                 if (params.positive)
1866                 {
1867                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1868                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1869                 }
1870                 else
1871                 {
1872                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1873                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1874                 }
1875
1876                 for (int ndx = 0; ndx < numElements; ++ndx)
1877                 {
1878                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1879                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1880                 }
1881
1882                 spec.assembly =
1883                         "OpCapability Int64\n"
1884
1885                         + string(getComputeAsmShaderPreamble()) +
1886
1887                         "OpName %main           \"main\"\n"
1888                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1889
1890                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1891
1892                         "OpDecorate %buf BufferBlock\n"
1893                         "OpDecorate %indata1 DescriptorSet 0\n"
1894                         "OpDecorate %indata1 Binding 0\n"
1895                         "OpDecorate %indata2 DescriptorSet 0\n"
1896                         "OpDecorate %indata2 Binding 1\n"
1897                         "OpDecorate %outdata DescriptorSet 0\n"
1898                         "OpDecorate %outdata Binding 2\n"
1899                         "OpDecorate %i64arr ArrayStride 8\n"
1900                         "OpMemberDecorate %buf 0 Offset 0\n"
1901
1902                         + string(getComputeAsmCommonTypes())
1903                         + string(getComputeAsmCommonInt64Types()) +
1904
1905                         "%buf        = OpTypeStruct %i64arr\n"
1906                         "%bufptr     = OpTypePointer Uniform %buf\n"
1907                         "%indata1    = OpVariable %bufptr Uniform\n"
1908                         "%indata2    = OpVariable %bufptr Uniform\n"
1909                         "%outdata    = OpVariable %bufptr Uniform\n"
1910
1911                         "%id        = OpVariable %uvec3ptr Input\n"
1912                         "%zero      = OpConstant %i64 0\n"
1913
1914                         "%main      = OpFunction %void None %voidf\n"
1915                         "%label     = OpLabel\n"
1916                         "%idval     = OpLoad %uvec3 %id\n"
1917                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1918                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1919                         "%inval1    = OpLoad %i64 %inloc1\n"
1920                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1921                         "%inval2    = OpLoad %i64 %inloc2\n"
1922                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1923                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1924                         "             OpStore %outloc %rem\n"
1925                         "             OpReturn\n"
1926                         "             OpFunctionEnd\n";
1927
1928                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1929                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1930                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1931                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1932                 spec.failResult                 = params.failResult;
1933                 spec.failMessage                = params.failMessage;
1934
1935                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1936
1937                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1938         }
1939
1940         return group.release();
1941 }
1942
1943 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1944 {
1945         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1946         de::Random                                              rnd                             (deStringHash(group->getName()));
1947         const int                                               numElements             = 200;
1948
1949         const struct CaseParams
1950         {
1951                 const char*             name;
1952                 const char*             failMessage;            // customized status message
1953                 qpTestResult    failResult;                     // override status on failure
1954                 int                             op1Min, op1Max;         // operand ranges
1955                 int                             op2Min, op2Max;
1956         } cases[] =
1957         {
1958                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1959                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1960         };
1961         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1962
1963         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1964         {
1965                 const CaseParams&       params          = cases[caseNdx];
1966
1967                 ComputeShaderSpec       spec;
1968                 vector<deInt32>         inputInts1      (numElements, 0);
1969                 vector<deInt32>         inputInts2      (numElements, 0);
1970                 vector<deInt32>         outputInts      (numElements, 0);
1971
1972                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1973                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1974
1975                 for (int ndx = 0; ndx < numElements; ++ndx)
1976                 {
1977                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1978                         if (rem == 0)
1979                         {
1980                                 outputInts[ndx] = 0;
1981                         }
1982                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1983                         {
1984                                 // They have the same sign
1985                                 outputInts[ndx] = rem;
1986                         }
1987                         else
1988                         {
1989                                 // They have opposite sign.  The remainder operation takes the
1990                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1991                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1992                                 // the result has the correct sign and that it is still
1993                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1994                                 //
1995                                 // See also http://mathforum.org/library/drmath/view/52343.html
1996                                 outputInts[ndx] = rem + inputInts2[ndx];
1997                         }
1998                 }
1999
2000                 spec.assembly =
2001                         string(getComputeAsmShaderPreamble()) +
2002
2003                         "OpName %main           \"main\"\n"
2004                         "OpName %id             \"gl_GlobalInvocationID\"\n"
2005
2006                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
2007
2008                         "OpDecorate %buf BufferBlock\n"
2009                         "OpDecorate %indata1 DescriptorSet 0\n"
2010                         "OpDecorate %indata1 Binding 0\n"
2011                         "OpDecorate %indata2 DescriptorSet 0\n"
2012                         "OpDecorate %indata2 Binding 1\n"
2013                         "OpDecorate %outdata DescriptorSet 0\n"
2014                         "OpDecorate %outdata Binding 2\n"
2015                         "OpDecorate %i32arr ArrayStride 4\n"
2016                         "OpMemberDecorate %buf 0 Offset 0\n"
2017
2018                         + string(getComputeAsmCommonTypes()) +
2019
2020                         "%buf        = OpTypeStruct %i32arr\n"
2021                         "%bufptr     = OpTypePointer Uniform %buf\n"
2022                         "%indata1    = OpVariable %bufptr Uniform\n"
2023                         "%indata2    = OpVariable %bufptr Uniform\n"
2024                         "%outdata    = OpVariable %bufptr Uniform\n"
2025
2026                         "%id        = OpVariable %uvec3ptr Input\n"
2027                         "%zero      = OpConstant %i32 0\n"
2028
2029                         "%main      = OpFunction %void None %voidf\n"
2030                         "%label     = OpLabel\n"
2031                         "%idval     = OpLoad %uvec3 %id\n"
2032                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2033                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
2034                         "%inval1    = OpLoad %i32 %inloc1\n"
2035                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
2036                         "%inval2    = OpLoad %i32 %inloc2\n"
2037                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
2038                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2039                         "             OpStore %outloc %rem\n"
2040                         "             OpReturn\n"
2041                         "             OpFunctionEnd\n";
2042
2043                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
2044                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
2045                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
2046                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2047                 spec.failResult                 = params.failResult;
2048                 spec.failMessage                = params.failMessage;
2049
2050                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2051         }
2052
2053         return group.release();
2054 }
2055
2056 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
2057 {
2058         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
2059         de::Random                                              rnd                             (deStringHash(group->getName()));
2060         const int                                               numElements             = 200;
2061
2062         const struct CaseParams
2063         {
2064                 const char*             name;
2065                 const char*             failMessage;            // customized status message
2066                 qpTestResult    failResult;                     // override status on failure
2067                 bool                    positive;
2068         } cases[] =
2069         {
2070                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
2071                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
2072         };
2073         // If either operand is negative the result is undefined. Some implementations may still return correct values.
2074
2075         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
2076         {
2077                 const CaseParams&       params          = cases[caseNdx];
2078
2079                 ComputeShaderSpec       spec;
2080                 vector<deInt64>         inputInts1      (numElements, 0);
2081                 vector<deInt64>         inputInts2      (numElements, 0);
2082                 vector<deInt64>         outputInts      (numElements, 0);
2083
2084
2085                 if (params.positive)
2086                 {
2087                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
2088                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
2089                 }
2090                 else
2091                 {
2092                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
2093                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
2094                 }
2095
2096                 for (int ndx = 0; ndx < numElements; ++ndx)
2097                 {
2098                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
2099                         if (rem == 0)
2100                         {
2101                                 outputInts[ndx] = 0;
2102                         }
2103                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
2104                         {
2105                                 // They have the same sign
2106                                 outputInts[ndx] = rem;
2107                         }
2108                         else
2109                         {
2110                                 // They have opposite sign.  The remainder operation takes the
2111                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
2112                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
2113                                 // the result has the correct sign and that it is still
2114                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
2115                                 //
2116                                 // See also http://mathforum.org/library/drmath/view/52343.html
2117                                 outputInts[ndx] = rem + inputInts2[ndx];
2118                         }
2119                 }
2120
2121                 spec.assembly =
2122                         "OpCapability Int64\n"
2123
2124                         + string(getComputeAsmShaderPreamble()) +
2125
2126                         "OpName %main           \"main\"\n"
2127                         "OpName %id             \"gl_GlobalInvocationID\"\n"
2128
2129                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
2130
2131                         "OpDecorate %buf BufferBlock\n"
2132                         "OpDecorate %indata1 DescriptorSet 0\n"
2133                         "OpDecorate %indata1 Binding 0\n"
2134                         "OpDecorate %indata2 DescriptorSet 0\n"
2135                         "OpDecorate %indata2 Binding 1\n"
2136                         "OpDecorate %outdata DescriptorSet 0\n"
2137                         "OpDecorate %outdata Binding 2\n"
2138                         "OpDecorate %i64arr ArrayStride 8\n"
2139                         "OpMemberDecorate %buf 0 Offset 0\n"
2140
2141                         + string(getComputeAsmCommonTypes())
2142                         + string(getComputeAsmCommonInt64Types()) +
2143
2144                         "%buf        = OpTypeStruct %i64arr\n"
2145                         "%bufptr     = OpTypePointer Uniform %buf\n"
2146                         "%indata1    = OpVariable %bufptr Uniform\n"
2147                         "%indata2    = OpVariable %bufptr Uniform\n"
2148                         "%outdata    = OpVariable %bufptr Uniform\n"
2149
2150                         "%id        = OpVariable %uvec3ptr Input\n"
2151                         "%zero      = OpConstant %i64 0\n"
2152
2153                         "%main      = OpFunction %void None %voidf\n"
2154                         "%label     = OpLabel\n"
2155                         "%idval     = OpLoad %uvec3 %id\n"
2156                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2157                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2158                         "%inval1    = OpLoad %i64 %inloc1\n"
2159                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2160                         "%inval2    = OpLoad %i64 %inloc2\n"
2161                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2162                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2163                         "             OpStore %outloc %rem\n"
2164                         "             OpReturn\n"
2165                         "             OpFunctionEnd\n";
2166
2167                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2168                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2169                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2170                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2171                 spec.failResult                 = params.failResult;
2172                 spec.failMessage                = params.failMessage;
2173
2174                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2175
2176                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2177         }
2178
2179         return group.release();
2180 }
2181
2182 // Copy contents in the input buffer to the output buffer.
2183 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2184 {
2185         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2186         de::Random                                              rnd                             (deStringHash(group->getName()));
2187         const int                                               numElements             = 100;
2188
2189         // The following case adds vec4(0., 0.5, 1.5, 2.5) to each of the elements in the input buffer and writes output to the output buffer.
2190         ComputeShaderSpec                               spec1;
2191         vector<Vec4>                                    inputFloats1    (numElements);
2192         vector<Vec4>                                    outputFloats1   (numElements);
2193
2194         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2195
2196         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2197         floorAll(inputFloats1);
2198
2199         for (size_t ndx = 0; ndx < numElements; ++ndx)
2200                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2201
2202         spec1.assembly =
2203                 string(getComputeAsmShaderPreamble()) +
2204
2205                 "OpName %main           \"main\"\n"
2206                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2207
2208                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2209                 "OpDecorate %vec4arr ArrayStride 16\n"
2210
2211                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2212
2213                 "%vec4       = OpTypeVector %f32 4\n"
2214                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2215                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2216                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2217                 "%buf        = OpTypeStruct %vec4arr\n"
2218                 "%bufptr     = OpTypePointer Uniform %buf\n"
2219                 "%indata     = OpVariable %bufptr Uniform\n"
2220                 "%outdata    = OpVariable %bufptr Uniform\n"
2221
2222                 "%id         = OpVariable %uvec3ptr Input\n"
2223                 "%zero       = OpConstant %i32 0\n"
2224                 "%c_f_0      = OpConstant %f32 0.\n"
2225                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2226                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2227                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2228                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2229
2230                 "%main       = OpFunction %void None %voidf\n"
2231                 "%label      = OpLabel\n"
2232                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2233                 "%idval      = OpLoad %uvec3 %id\n"
2234                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2235                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2236                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2237                 "              OpCopyMemory %v_vec4 %inloc\n"
2238                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2239                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2240                 "              OpStore %outloc %add\n"
2241                 "              OpReturn\n"
2242                 "              OpFunctionEnd\n";
2243
2244         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2245         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2246         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2247
2248         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2249
2250         // The following case copies a float[100] variable from the input buffer to the output buffer.
2251         ComputeShaderSpec                               spec2;
2252         vector<float>                                   inputFloats2    (numElements);
2253         vector<float>                                   outputFloats2   (numElements);
2254
2255         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2256
2257         for (size_t ndx = 0; ndx < numElements; ++ndx)
2258                 outputFloats2[ndx] = inputFloats2[ndx];
2259
2260         spec2.assembly =
2261                 string(getComputeAsmShaderPreamble()) +
2262
2263                 "OpName %main           \"main\"\n"
2264                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2265
2266                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2267                 "OpDecorate %f32arr100 ArrayStride 4\n"
2268
2269                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2270
2271                 "%hundred        = OpConstant %u32 100\n"
2272                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2273                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2274                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2275                 "%buf            = OpTypeStruct %f32arr100\n"
2276                 "%bufptr         = OpTypePointer Uniform %buf\n"
2277                 "%indata         = OpVariable %bufptr Uniform\n"
2278                 "%outdata        = OpVariable %bufptr Uniform\n"
2279
2280                 "%id             = OpVariable %uvec3ptr Input\n"
2281                 "%zero           = OpConstant %i32 0\n"
2282
2283                 "%main           = OpFunction %void None %voidf\n"
2284                 "%label          = OpLabel\n"
2285                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2286                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2287                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2288                 "                  OpCopyMemory %var %inarr\n"
2289                 "                  OpCopyMemory %outarr %var\n"
2290                 "                  OpReturn\n"
2291                 "                  OpFunctionEnd\n";
2292
2293         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2294         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2295         spec2.numWorkGroups = IVec3(1, 1, 1);
2296
2297         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2298
2299         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2300         ComputeShaderSpec                               spec3;
2301         vector<float>                                   inputFloats3    (16);
2302         vector<float>                                   outputFloats3   (16);
2303
2304         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2305
2306         for (size_t ndx = 0; ndx < 16; ++ndx)
2307                 outputFloats3[ndx] = inputFloats3[ndx];
2308
2309         spec3.assembly =
2310                 string(getComputeAsmShaderPreamble()) +
2311
2312                 "OpName %main           \"main\"\n"
2313                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2314
2315                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2316                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2317                 "OpMemberDecorate %buf 1 Offset 16\n"
2318                 "OpMemberDecorate %buf 2 Offset 32\n"
2319                 "OpMemberDecorate %buf 3 Offset 48\n"
2320
2321                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2322
2323                 "%vec4      = OpTypeVector %f32 4\n"
2324                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2325                 "%bufptr    = OpTypePointer Uniform %buf\n"
2326                 "%indata    = OpVariable %bufptr Uniform\n"
2327                 "%outdata   = OpVariable %bufptr Uniform\n"
2328                 "%vec4stptr = OpTypePointer Function %buf\n"
2329
2330                 "%id        = OpVariable %uvec3ptr Input\n"
2331                 "%zero      = OpConstant %i32 0\n"
2332
2333                 "%main      = OpFunction %void None %voidf\n"
2334                 "%label     = OpLabel\n"
2335                 "%var       = OpVariable %vec4stptr Function\n"
2336                 "             OpCopyMemory %var %indata\n"
2337                 "             OpCopyMemory %outdata %var\n"
2338                 "             OpReturn\n"
2339                 "             OpFunctionEnd\n";
2340
2341         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2342         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2343         spec3.numWorkGroups = IVec3(1, 1, 1);
2344
2345         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2346
2347         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2348         ComputeShaderSpec                               spec4;
2349         vector<float>                                   inputFloats4    (numElements);
2350         vector<float>                                   outputFloats4   (numElements);
2351
2352         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2353
2354         for (size_t ndx = 0; ndx < numElements; ++ndx)
2355                 outputFloats4[ndx] = -inputFloats4[ndx];
2356
2357         spec4.assembly =
2358                 string(getComputeAsmShaderPreamble()) +
2359
2360                 "OpName %main           \"main\"\n"
2361                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2362
2363                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2364
2365                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2366
2367                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2368                 "%id        = OpVariable %uvec3ptr Input\n"
2369                 "%zero      = OpConstant %i32 0\n"
2370
2371                 "%main      = OpFunction %void None %voidf\n"
2372                 "%label     = OpLabel\n"
2373                 "%var       = OpVariable %f32ptr_f Function\n"
2374                 "%idval     = OpLoad %uvec3 %id\n"
2375                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2376                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2377                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2378                 "             OpCopyMemory %var %inloc\n"
2379                 "%val       = OpLoad %f32 %var\n"
2380                 "%neg       = OpFNegate %f32 %val\n"
2381                 "             OpStore %outloc %neg\n"
2382                 "             OpReturn\n"
2383                 "             OpFunctionEnd\n";
2384
2385         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2386         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2387         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2388
2389         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2390
2391         return group.release();
2392 }
2393
2394 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2395 {
2396         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2397         ComputeShaderSpec                               spec;
2398         de::Random                                              rnd                             (deStringHash(group->getName()));
2399         const int                                               numElements             = 100;
2400         vector<float>                                   inputFloats             (numElements, 0);
2401         vector<float>                                   outputFloats    (numElements, 0);
2402
2403         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2404
2405         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2406         floorAll(inputFloats);
2407
2408         for (size_t ndx = 0; ndx < numElements; ++ndx)
2409                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2410
2411         spec.assembly =
2412                 string(getComputeAsmShaderPreamble()) +
2413
2414                 "OpName %main           \"main\"\n"
2415                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2416
2417                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2418
2419                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2420
2421                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2422                 "%three    = OpConstant %u32 3\n"
2423                 "%farr     = OpTypeArray %f32 %three\n"
2424                 "%fst      = OpTypeStruct %f32 %f32\n"
2425
2426                 + string(getComputeAsmInputOutputBuffer()) +
2427
2428                 "%id            = OpVariable %uvec3ptr Input\n"
2429                 "%zero          = OpConstant %i32 0\n"
2430                 "%c_f           = OpConstant %f32 1.5\n"
2431                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2432                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2433                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2434                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2435
2436                 "%main          = OpFunction %void None %voidf\n"
2437                 "%label         = OpLabel\n"
2438                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2439                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2440                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2441                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2442                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2443                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2444                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2445                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2446                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2447                 // Add up. 1.5 * 5 = 7.5.
2448                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2449                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2450                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2451                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2452
2453                 "%idval         = OpLoad %uvec3 %id\n"
2454                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2455                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2456                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2457                 "%inval         = OpLoad %f32 %inloc\n"
2458                 "%add           = OpFAdd %f32 %add4 %inval\n"
2459                 "                 OpStore %outloc %add\n"
2460                 "                 OpReturn\n"
2461                 "                 OpFunctionEnd\n";
2462         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2463         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2464         spec.numWorkGroups = IVec3(numElements, 1, 1);
2465
2466         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2467
2468         return group.release();
2469 }
2470 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2471 //
2472 // #version 430
2473 //
2474 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2475 //   float elements[];
2476 // } input_data;
2477 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2478 //   float elements[];
2479 // } output_data;
2480 //
2481 // void not_called_func() {
2482 //   // place OpUnreachable here
2483 // }
2484 //
2485 // uint modulo4(uint val) {
2486 //   switch (val % uint(4)) {
2487 //     case 0:  return 3;
2488 //     case 1:  return 2;
2489 //     case 2:  return 1;
2490 //     case 3:  return 0;
2491 //     default: return 100; // place OpUnreachable here
2492 //   }
2493 // }
2494 //
2495 // uint const5() {
2496 //   return 5;
2497 //   // place OpUnreachable here
2498 // }
2499 //
2500 // void main() {
2501 //   uint x = gl_GlobalInvocationID.x;
2502 //   if (const5() > modulo4(1000)) {
2503 //     output_data.elements[x] = -input_data.elements[x];
2504 //   } else {
2505 //     // place OpUnreachable here
2506 //     output_data.elements[x] = input_data.elements[x];
2507 //   }
2508 // }
2509
2510 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2511 {
2512         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2513         ComputeShaderSpec                               spec;
2514         de::Random                                              rnd                             (deStringHash(group->getName()));
2515         const int                                               numElements             = 100;
2516         vector<float>                                   positiveFloats  (numElements, 0);
2517         vector<float>                                   negativeFloats  (numElements, 0);
2518
2519         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2520
2521         for (size_t ndx = 0; ndx < numElements; ++ndx)
2522                 negativeFloats[ndx] = -positiveFloats[ndx];
2523
2524         spec.assembly =
2525                 string(getComputeAsmShaderPreamble()) +
2526
2527                 "OpSource GLSL 430\n"
2528                 "OpName %main            \"main\"\n"
2529                 "OpName %func_not_called_func \"not_called_func(\"\n"
2530                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2531                 "OpName %func_const5          \"const5(\"\n"
2532                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2533
2534                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2535
2536                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2537
2538                 "%u32ptr    = OpTypePointer Function %u32\n"
2539                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2540                 "%unitf     = OpTypeFunction %u32\n"
2541
2542                 "%id        = OpVariable %uvec3ptr Input\n"
2543                 "%zero      = OpConstant %u32 0\n"
2544                 "%one       = OpConstant %u32 1\n"
2545                 "%two       = OpConstant %u32 2\n"
2546                 "%three     = OpConstant %u32 3\n"
2547                 "%four      = OpConstant %u32 4\n"
2548                 "%five      = OpConstant %u32 5\n"
2549                 "%hundred   = OpConstant %u32 100\n"
2550                 "%thousand  = OpConstant %u32 1000\n"
2551
2552                 + string(getComputeAsmInputOutputBuffer()) +
2553
2554                 // Main()
2555                 "%main   = OpFunction %void None %voidf\n"
2556                 "%main_entry  = OpLabel\n"
2557                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2558                 "%idval       = OpLoad %uvec3 %id\n"
2559                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2560                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2561                 "%inval       = OpLoad %f32 %inloc\n"
2562                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2563                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2564                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2565                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2566                 "               OpSelectionMerge %if_end None\n"
2567                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2568                 "%if_true     = OpLabel\n"
2569                 "%negate      = OpFNegate %f32 %inval\n"
2570                 "               OpStore %outloc %negate\n"
2571                 "               OpBranch %if_end\n"
2572                 "%if_false    = OpLabel\n"
2573                 "               OpUnreachable\n" // Unreachable else branch for if statement
2574                 "%if_end      = OpLabel\n"
2575                 "               OpReturn\n"
2576                 "               OpFunctionEnd\n"
2577
2578                 // not_called_function()
2579                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2580                 "%not_called_func_entry = OpLabel\n"
2581                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2582                 "                         OpFunctionEnd\n"
2583
2584                 // modulo4()
2585                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2586                 "%valptr        = OpFunctionParameter %u32ptr\n"
2587                 "%modulo4_entry = OpLabel\n"
2588                 "%val           = OpLoad %u32 %valptr\n"
2589                 "%modulo        = OpUMod %u32 %val %four\n"
2590                 "                 OpSelectionMerge %switch_merge None\n"
2591                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2592                 "%case0         = OpLabel\n"
2593                 "                 OpReturnValue %three\n"
2594                 "%case1         = OpLabel\n"
2595                 "                 OpReturnValue %two\n"
2596                 "%case2         = OpLabel\n"
2597                 "                 OpReturnValue %one\n"
2598                 "%case3         = OpLabel\n"
2599                 "                 OpReturnValue %zero\n"
2600                 "%default       = OpLabel\n"
2601                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2602                 "%switch_merge  = OpLabel\n"
2603                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2604                 "                 OpFunctionEnd\n"
2605
2606                 // const5()
2607                 "%func_const5  = OpFunction %u32 None %unitf\n"
2608                 "%const5_entry = OpLabel\n"
2609                 "                OpReturnValue %five\n"
2610                 "%unreachable  = OpLabel\n"
2611                 "                OpUnreachable\n" // Unreachable block in function
2612                 "                OpFunctionEnd\n";
2613         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2614         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2615         spec.numWorkGroups = IVec3(numElements, 1, 1);
2616
2617         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2618
2619         return group.release();
2620 }
2621
2622 // Assembly code used for testing decoration group is based on GLSL source code:
2623 //
2624 // #version 430
2625 //
2626 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2627 //   float elements[];
2628 // } input_data0;
2629 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2630 //   float elements[];
2631 // } input_data1;
2632 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2633 //   float elements[];
2634 // } input_data2;
2635 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2636 //   float elements[];
2637 // } input_data3;
2638 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2639 //   float elements[];
2640 // } input_data4;
2641 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2642 //   float elements[];
2643 // } output_data;
2644 //
2645 // void main() {
2646 //   uint x = gl_GlobalInvocationID.x;
2647 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2648 // }
2649 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2650 {
2651         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2652         ComputeShaderSpec                               spec;
2653         de::Random                                              rnd                             (deStringHash(group->getName()));
2654         const int                                               numElements             = 100;
2655         vector<float>                                   inputFloats0    (numElements, 0);
2656         vector<float>                                   inputFloats1    (numElements, 0);
2657         vector<float>                                   inputFloats2    (numElements, 0);
2658         vector<float>                                   inputFloats3    (numElements, 0);
2659         vector<float>                                   inputFloats4    (numElements, 0);
2660         vector<float>                                   outputFloats    (numElements, 0);
2661
2662         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2663         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2664         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2665         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2666         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2667
2668         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2669         floorAll(inputFloats0);
2670         floorAll(inputFloats1);
2671         floorAll(inputFloats2);
2672         floorAll(inputFloats3);
2673         floorAll(inputFloats4);
2674
2675         for (size_t ndx = 0; ndx < numElements; ++ndx)
2676                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2677
2678         spec.assembly =
2679                 string(getComputeAsmShaderPreamble()) +
2680
2681                 "OpSource GLSL 430\n"
2682                 "OpName %main \"main\"\n"
2683                 "OpName %id \"gl_GlobalInvocationID\"\n"
2684
2685                 // Not using group decoration on variable.
2686                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2687                 // Not using group decoration on type.
2688                 "OpDecorate %f32arr ArrayStride 4\n"
2689
2690                 "OpDecorate %groups BufferBlock\n"
2691                 "OpDecorate %groupm Offset 0\n"
2692                 "%groups = OpDecorationGroup\n"
2693                 "%groupm = OpDecorationGroup\n"
2694
2695                 // Group decoration on multiple structs.
2696                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2697                 // Group decoration on multiple struct members.
2698                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2699
2700                 "OpDecorate %group1 DescriptorSet 0\n"
2701                 "OpDecorate %group3 DescriptorSet 0\n"
2702                 "OpDecorate %group3 NonWritable\n"
2703                 "OpDecorate %group3 Restrict\n"
2704                 "%group0 = OpDecorationGroup\n"
2705                 "%group1 = OpDecorationGroup\n"
2706                 "%group3 = OpDecorationGroup\n"
2707
2708                 // Applying the same decoration group multiple times.
2709                 "OpGroupDecorate %group1 %outdata\n"
2710                 "OpGroupDecorate %group1 %outdata\n"
2711                 "OpGroupDecorate %group1 %outdata\n"
2712                 "OpDecorate %outdata DescriptorSet 0\n"
2713                 "OpDecorate %outdata Binding 5\n"
2714                 // Applying decoration group containing nothing.
2715                 "OpGroupDecorate %group0 %indata0\n"
2716                 "OpDecorate %indata0 DescriptorSet 0\n"
2717                 "OpDecorate %indata0 Binding 0\n"
2718                 // Applying decoration group containing one decoration.
2719                 "OpGroupDecorate %group1 %indata1\n"
2720                 "OpDecorate %indata1 Binding 1\n"
2721                 // Applying decoration group containing multiple decorations.
2722                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2723                 "OpDecorate %indata2 Binding 2\n"
2724                 "OpDecorate %indata3 Binding 3\n"
2725                 // Applying multiple decoration groups (with overlapping).
2726                 "OpGroupDecorate %group0 %indata4\n"
2727                 "OpGroupDecorate %group1 %indata4\n"
2728                 "OpGroupDecorate %group3 %indata4\n"
2729                 "OpDecorate %indata4 Binding 4\n"
2730
2731                 + string(getComputeAsmCommonTypes()) +
2732
2733                 "%id   = OpVariable %uvec3ptr Input\n"
2734                 "%zero = OpConstant %i32 0\n"
2735
2736                 "%outbuf    = OpTypeStruct %f32arr\n"
2737                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2738                 "%outdata   = OpVariable %outbufptr Uniform\n"
2739                 "%inbuf0    = OpTypeStruct %f32arr\n"
2740                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2741                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2742                 "%inbuf1    = OpTypeStruct %f32arr\n"
2743                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2744                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2745                 "%inbuf2    = OpTypeStruct %f32arr\n"
2746                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2747                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2748                 "%inbuf3    = OpTypeStruct %f32arr\n"
2749                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2750                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2751                 "%inbuf4    = OpTypeStruct %f32arr\n"
2752                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2753                 "%indata4   = OpVariable %inbufptr Uniform\n"
2754
2755                 "%main   = OpFunction %void None %voidf\n"
2756                 "%label  = OpLabel\n"
2757                 "%idval  = OpLoad %uvec3 %id\n"
2758                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2759                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2760                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2761                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2762                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2763                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2764                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2765                 "%inval0 = OpLoad %f32 %inloc0\n"
2766                 "%inval1 = OpLoad %f32 %inloc1\n"
2767                 "%inval2 = OpLoad %f32 %inloc2\n"
2768                 "%inval3 = OpLoad %f32 %inloc3\n"
2769                 "%inval4 = OpLoad %f32 %inloc4\n"
2770                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2771                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2772                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2773                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2774                 "          OpStore %outloc %add\n"
2775                 "          OpReturn\n"
2776                 "          OpFunctionEnd\n";
2777         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2778         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2779         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2780         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2781         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2782         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2783         spec.numWorkGroups = IVec3(numElements, 1, 1);
2784
2785         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2786
2787         return group.release();
2788 }
2789
2790 struct SpecConstantTwoIntCase
2791 {
2792         const char*             caseName;
2793         const char*             scDefinition0;
2794         const char*             scDefinition1;
2795         const char*             scResultType;
2796         const char*             scOperation;
2797         deInt32                 scActualValue0;
2798         deInt32                 scActualValue1;
2799         const char*             resultOperation;
2800         vector<deInt32> expectedOutput;
2801         deInt32                 scActualValueLength;
2802
2803                                         SpecConstantTwoIntCase (const char* name,
2804                                                                                         const char* definition0,
2805                                                                                         const char* definition1,
2806                                                                                         const char* resultType,
2807                                                                                         const char* operation,
2808                                                                                         deInt32 value0,
2809                                                                                         deInt32 value1,
2810                                                                                         const char* resultOp,
2811                                                                                         const vector<deInt32>& output,
2812                                                                                         const deInt32   valueLength = sizeof(deInt32))
2813                                                 : caseName                              (name)
2814                                                 , scDefinition0                 (definition0)
2815                                                 , scDefinition1                 (definition1)
2816                                                 , scResultType                  (resultType)
2817                                                 , scOperation                   (operation)
2818                                                 , scActualValue0                (value0)
2819                                                 , scActualValue1                (value1)
2820                                                 , resultOperation               (resultOp)
2821                                                 , expectedOutput                (output)
2822                                                 , scActualValueLength   (valueLength)
2823                                                 {}
2824 };
2825
2826 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2827 {
2828         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2829         vector<SpecConstantTwoIntCase>  cases;
2830         de::Random                                              rnd                             (deStringHash(group->getName()));
2831         const int                                               numElements             = 100;
2832         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2833         vector<deInt32>                                 inputInts               (numElements, 0);
2834         vector<deInt32>                                 outputInts1             (numElements, 0);
2835         vector<deInt32>                                 outputInts2             (numElements, 0);
2836         vector<deInt32>                                 outputInts3             (numElements, 0);
2837         vector<deInt32>                                 outputInts4             (numElements, 0);
2838         const StringTemplate                    shaderTemplate  (
2839                 "${CAPABILITIES:opt}"
2840                 + string(getComputeAsmShaderPreamble()) +
2841
2842                 "OpName %main           \"main\"\n"
2843                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2844
2845                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2846                 "OpDecorate %sc_0  SpecId 0\n"
2847                 "OpDecorate %sc_1  SpecId 1\n"
2848                 "OpDecorate %i32arr ArrayStride 4\n"
2849
2850                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2851
2852                 "${OPTYPE_DEFINITIONS:opt}"
2853                 "%buf     = OpTypeStruct %i32arr\n"
2854                 "%bufptr  = OpTypePointer Uniform %buf\n"
2855                 "%indata    = OpVariable %bufptr Uniform\n"
2856                 "%outdata   = OpVariable %bufptr Uniform\n"
2857
2858                 "%id        = OpVariable %uvec3ptr Input\n"
2859                 "%zero      = OpConstant %i32 0\n"
2860
2861                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2862                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2863                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2864
2865                 "%main      = OpFunction %void None %voidf\n"
2866                 "%label     = OpLabel\n"
2867                 "${TYPE_CONVERT:opt}"
2868                 "%idval     = OpLoad %uvec3 %id\n"
2869                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2870                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2871                 "%inval     = OpLoad %i32 %inloc\n"
2872                 "%final     = ${GEN_RESULT}\n"
2873                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2874                 "             OpStore %outloc %final\n"
2875                 "             OpReturn\n"
2876                 "             OpFunctionEnd\n");
2877
2878         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2879
2880         for (size_t ndx = 0; ndx < numElements; ++ndx)
2881         {
2882                 outputInts1[ndx] = inputInts[ndx] + 42;
2883                 outputInts2[ndx] = inputInts[ndx];
2884                 outputInts3[ndx] = inputInts[ndx] - 11200;
2885                 outputInts4[ndx] = inputInts[ndx] + 1;
2886         }
2887
2888         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2889         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2890         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2891         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2892
2893         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2894         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2895         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2896         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2897         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2898         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2899         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2900         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2901         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2902         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2903         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2904         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2905         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2906         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2907         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2908         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2909         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2910         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2911         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2912         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2913         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2914         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2915         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2916         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2917         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2918         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2919         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2920         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2921         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2922         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2923         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2924         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2925         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2926         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2927         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2928         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2929
2930         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2931         {
2932                 map<string, string>             specializations;
2933                 ComputeShaderSpec               spec;
2934
2935                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2936                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2937                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2938                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2939                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2940
2941                 // Special SPIR-V code for SConvert-case
2942                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2943                 {
2944                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2945                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2946                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2947                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2948                 }
2949
2950                 // Special SPIR-V code for FConvert-case
2951                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2952                 {
2953                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2954                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2955                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2956                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2957                 }
2958
2959                 // Special SPIR-V code for FConvert-case for 16-bit floats
2960                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2961                 {
2962                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2963                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2964                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2965                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2966                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2967                 }
2968
2969                 spec.assembly = shaderTemplate.specialize(specializations);
2970                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2971                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2972                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2973                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2974                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2975
2976                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2977         }
2978
2979         ComputeShaderSpec                               spec;
2980
2981         spec.assembly =
2982                 string(getComputeAsmShaderPreamble()) +
2983
2984                 "OpName %main           \"main\"\n"
2985                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2986
2987                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2988                 "OpDecorate %sc_0  SpecId 0\n"
2989                 "OpDecorate %sc_1  SpecId 1\n"
2990                 "OpDecorate %sc_2  SpecId 2\n"
2991                 "OpDecorate %i32arr ArrayStride 4\n"
2992
2993                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2994
2995                 "%ivec3       = OpTypeVector %i32 3\n"
2996                 "%buf         = OpTypeStruct %i32arr\n"
2997                 "%bufptr      = OpTypePointer Uniform %buf\n"
2998                 "%indata      = OpVariable %bufptr Uniform\n"
2999                 "%outdata     = OpVariable %bufptr Uniform\n"
3000
3001                 "%id          = OpVariable %uvec3ptr Input\n"
3002                 "%zero        = OpConstant %i32 0\n"
3003                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
3004                 "%vec3_undef  = OpUndef %ivec3\n"
3005
3006                 "%sc_0        = OpSpecConstant %i32 0\n"
3007                 "%sc_1        = OpSpecConstant %i32 0\n"
3008                 "%sc_2        = OpSpecConstant %i32 0\n"
3009                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
3010                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
3011                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
3012                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
3013                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
3014                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
3015                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
3016                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
3017                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
3018                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
3019                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
3020                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
3021                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
3022
3023                 "%main      = OpFunction %void None %voidf\n"
3024                 "%label     = OpLabel\n"
3025                 "%idval     = OpLoad %uvec3 %id\n"
3026                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3027                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
3028                 "%inval     = OpLoad %i32 %inloc\n"
3029                 "%final     = OpIAdd %i32 %inval %sc_final\n"
3030                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
3031                 "             OpStore %outloc %final\n"
3032                 "             OpReturn\n"
3033                 "             OpFunctionEnd\n";
3034         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
3035         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
3036         spec.numWorkGroups = IVec3(numElements, 1, 1);
3037         spec.specConstants.append<deInt32>(123);
3038         spec.specConstants.append<deInt32>(56);
3039         spec.specConstants.append<deInt32>(-77);
3040
3041         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
3042
3043         return group.release();
3044 }
3045
3046 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
3047 {
3048         ComputeShaderSpec       specInt;
3049         ComputeShaderSpec       specFloat;
3050         ComputeShaderSpec       specFloat16;
3051         ComputeShaderSpec       specVec3;
3052         ComputeShaderSpec       specMat4;
3053         ComputeShaderSpec       specArray;
3054         ComputeShaderSpec       specStruct;
3055         de::Random                      rnd                             (deStringHash(group->getName()));
3056         const int                       numElements             = 100;
3057         vector<float>           inputFloats             (numElements, 0);
3058         vector<float>           outputFloats    (numElements, 0);
3059         vector<deFloat16>       inputFloats16   (numElements, 0);
3060         vector<deFloat16>       outputFloats16  (numElements, 0);
3061
3062         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3063
3064         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3065         floorAll(inputFloats);
3066
3067         for (size_t ndx = 0; ndx < numElements; ++ndx)
3068         {
3069                 // Just check if the value is positive or not
3070                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
3071         }
3072
3073         for (size_t ndx = 0; ndx < numElements; ++ndx)
3074         {
3075                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
3076                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
3077         }
3078
3079         // All of the tests are of the form:
3080         //
3081         // testtype r
3082         //
3083         // if (inputdata > 0)
3084         //   r = 1
3085         // else
3086         //   r = -1
3087         //
3088         // return (float)r
3089
3090         specFloat.assembly =
3091                 string(getComputeAsmShaderPreamble()) +
3092
3093                 "OpSource GLSL 430\n"
3094                 "OpName %main \"main\"\n"
3095                 "OpName %id \"gl_GlobalInvocationID\"\n"
3096
3097                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3098
3099                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3100
3101                 "%id = OpVariable %uvec3ptr Input\n"
3102                 "%zero       = OpConstant %i32 0\n"
3103                 "%float_0    = OpConstant %f32 0.0\n"
3104                 "%float_1    = OpConstant %f32 1.0\n"
3105                 "%float_n1   = OpConstant %f32 -1.0\n"
3106
3107                 "%main     = OpFunction %void None %voidf\n"
3108                 "%entry    = OpLabel\n"
3109                 "%idval    = OpLoad %uvec3 %id\n"
3110                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3111                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3112                 "%inval    = OpLoad %f32 %inloc\n"
3113
3114                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3115                 "            OpSelectionMerge %cm None\n"
3116                 "            OpBranchConditional %comp %tb %fb\n"
3117                 "%tb       = OpLabel\n"
3118                 "            OpBranch %cm\n"
3119                 "%fb       = OpLabel\n"
3120                 "            OpBranch %cm\n"
3121                 "%cm       = OpLabel\n"
3122                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
3123
3124                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3125                 "            OpStore %outloc %res\n"
3126                 "            OpReturn\n"
3127
3128                 "            OpFunctionEnd\n";
3129         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3130         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3131         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
3132
3133         specFloat16.assembly =
3134                 "OpCapability Shader\n"
3135                 "OpCapability StorageUniformBufferBlock16\n"
3136                 "OpCapability Float16\n"
3137                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
3138                 "OpMemoryModel Logical GLSL450\n"
3139                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3140                 "OpExecutionMode %main LocalSize 1 1 1\n"
3141
3142                 "OpSource GLSL 430\n"
3143                 "OpName %main \"main\"\n"
3144                 "OpName %id \"gl_GlobalInvocationID\"\n"
3145
3146                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3147
3148                 "OpDecorate %buf BufferBlock\n"
3149                 "OpDecorate %indata DescriptorSet 0\n"
3150                 "OpDecorate %indata Binding 0\n"
3151                 "OpDecorate %outdata DescriptorSet 0\n"
3152                 "OpDecorate %outdata Binding 1\n"
3153                 "OpDecorate %f16arr ArrayStride 2\n"
3154                 "OpMemberDecorate %buf 0 Offset 0\n"
3155
3156                 "%f16      = OpTypeFloat 16\n"
3157                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3158                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3159
3160                 + string(getComputeAsmCommonTypes()) +
3161
3162                 "%buf      = OpTypeStruct %f16arr\n"
3163                 "%bufptr   = OpTypePointer Uniform %buf\n"
3164                 "%indata   = OpVariable %bufptr Uniform\n"
3165                 "%outdata  = OpVariable %bufptr Uniform\n"
3166
3167                 "%id       = OpVariable %uvec3ptr Input\n"
3168                 "%zero     = OpConstant %i32 0\n"
3169                 "%float_0  = OpConstant %f32 0.0\n"
3170                 "%float_1  = OpConstant %f32 1.0\n"
3171                 "%float_n1 = OpConstant %f32 -1.0\n"
3172
3173                 "%main     = OpFunction %void None %voidf\n"
3174                 "%entry    = OpLabel\n"
3175                 "%idval    = OpLoad %uvec3 %id\n"
3176                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3177                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3178                 "%inval    = OpLoad %f16 %inloc\n"
3179                 "%f32_inval = OpFConvert %f32 %inval\n"
3180
3181                 "%comp     = OpFOrdGreaterThan %bool %f32_inval %float_0\n"
3182                 "            OpSelectionMerge %cm None\n"
3183                 "            OpBranchConditional %comp %tb %fb\n"
3184                 "%tb       = OpLabel\n"
3185                 "            OpBranch %cm\n"
3186                 "%fb       = OpLabel\n"
3187                 "            OpBranch %cm\n"
3188                 "%cm       = OpLabel\n"
3189                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
3190                 "%f16_res  = OpFConvert %f16 %res\n"
3191
3192                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3193                 "            OpStore %outloc %f16_res\n"
3194                 "            OpReturn\n"
3195
3196                 "            OpFunctionEnd\n";
3197         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3198         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3199         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3200         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3201         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3202
3203         specMat4.assembly =
3204                 string(getComputeAsmShaderPreamble()) +
3205
3206                 "OpSource GLSL 430\n"
3207                 "OpName %main \"main\"\n"
3208                 "OpName %id \"gl_GlobalInvocationID\"\n"
3209
3210                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3211
3212                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3213
3214                 "%id = OpVariable %uvec3ptr Input\n"
3215                 "%v4f32      = OpTypeVector %f32 4\n"
3216                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3217                 "%zero       = OpConstant %i32 0\n"
3218                 "%float_0    = OpConstant %f32 0.0\n"
3219                 "%float_1    = OpConstant %f32 1.0\n"
3220                 "%float_n1   = OpConstant %f32 -1.0\n"
3221                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3222                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3223                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3224                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3225                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3226                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3227                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3228                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3229                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3230                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3231
3232                 "%main     = OpFunction %void None %voidf\n"
3233                 "%entry    = OpLabel\n"
3234                 "%idval    = OpLoad %uvec3 %id\n"
3235                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3236                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3237                 "%inval    = OpLoad %f32 %inloc\n"
3238
3239                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3240                 "            OpSelectionMerge %cm None\n"
3241                 "            OpBranchConditional %comp %tb %fb\n"
3242                 "%tb       = OpLabel\n"
3243                 "            OpBranch %cm\n"
3244                 "%fb       = OpLabel\n"
3245                 "            OpBranch %cm\n"
3246                 "%cm       = OpLabel\n"
3247                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3248                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3249
3250                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3251                 "            OpStore %outloc %res\n"
3252                 "            OpReturn\n"
3253
3254                 "            OpFunctionEnd\n";
3255         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3256         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3257         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3258
3259         specVec3.assembly =
3260                 string(getComputeAsmShaderPreamble()) +
3261
3262                 "OpSource GLSL 430\n"
3263                 "OpName %main \"main\"\n"
3264                 "OpName %id \"gl_GlobalInvocationID\"\n"
3265
3266                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3267
3268                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3269
3270                 "%id = OpVariable %uvec3ptr Input\n"
3271                 "%zero       = OpConstant %i32 0\n"
3272                 "%float_0    = OpConstant %f32 0.0\n"
3273                 "%float_1    = OpConstant %f32 1.0\n"
3274                 "%float_n1   = OpConstant %f32 -1.0\n"
3275                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3276                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3277
3278                 "%main     = OpFunction %void None %voidf\n"
3279                 "%entry    = OpLabel\n"
3280                 "%idval    = OpLoad %uvec3 %id\n"
3281                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3282                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3283                 "%inval    = OpLoad %f32 %inloc\n"
3284
3285                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3286                 "            OpSelectionMerge %cm None\n"
3287                 "            OpBranchConditional %comp %tb %fb\n"
3288                 "%tb       = OpLabel\n"
3289                 "            OpBranch %cm\n"
3290                 "%fb       = OpLabel\n"
3291                 "            OpBranch %cm\n"
3292                 "%cm       = OpLabel\n"
3293                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3294                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3295
3296                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3297                 "            OpStore %outloc %res\n"
3298                 "            OpReturn\n"
3299
3300                 "            OpFunctionEnd\n";
3301         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3302         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3303         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3304
3305         specInt.assembly =
3306                 string(getComputeAsmShaderPreamble()) +
3307
3308                 "OpSource GLSL 430\n"
3309                 "OpName %main \"main\"\n"
3310                 "OpName %id \"gl_GlobalInvocationID\"\n"
3311
3312                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3313
3314                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3315
3316                 "%id = OpVariable %uvec3ptr Input\n"
3317                 "%zero       = OpConstant %i32 0\n"
3318                 "%float_0    = OpConstant %f32 0.0\n"
3319                 "%i1         = OpConstant %i32 1\n"
3320                 "%i2         = OpConstant %i32 -1\n"
3321
3322                 "%main     = OpFunction %void None %voidf\n"
3323                 "%entry    = OpLabel\n"
3324                 "%idval    = OpLoad %uvec3 %id\n"
3325                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3326                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3327                 "%inval    = OpLoad %f32 %inloc\n"
3328
3329                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3330                 "            OpSelectionMerge %cm None\n"
3331                 "            OpBranchConditional %comp %tb %fb\n"
3332                 "%tb       = OpLabel\n"
3333                 "            OpBranch %cm\n"
3334                 "%fb       = OpLabel\n"
3335                 "            OpBranch %cm\n"
3336                 "%cm       = OpLabel\n"
3337                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3338                 "%res      = OpConvertSToF %f32 %ires\n"
3339
3340                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3341                 "            OpStore %outloc %res\n"
3342                 "            OpReturn\n"
3343
3344                 "            OpFunctionEnd\n";
3345         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3346         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3347         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3348
3349         specArray.assembly =
3350                 string(getComputeAsmShaderPreamble()) +
3351
3352                 "OpSource GLSL 430\n"
3353                 "OpName %main \"main\"\n"
3354                 "OpName %id \"gl_GlobalInvocationID\"\n"
3355
3356                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3357
3358                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3359
3360                 "%id = OpVariable %uvec3ptr Input\n"
3361                 "%zero       = OpConstant %i32 0\n"
3362                 "%u7         = OpConstant %u32 7\n"
3363                 "%float_0    = OpConstant %f32 0.0\n"
3364                 "%float_1    = OpConstant %f32 1.0\n"
3365                 "%float_n1   = OpConstant %f32 -1.0\n"
3366                 "%f32a7      = OpTypeArray %f32 %u7\n"
3367                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3368                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3369                 "%main     = OpFunction %void None %voidf\n"
3370                 "%entry    = OpLabel\n"
3371                 "%idval    = OpLoad %uvec3 %id\n"
3372                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3373                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3374                 "%inval    = OpLoad %f32 %inloc\n"
3375
3376                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3377                 "            OpSelectionMerge %cm None\n"
3378                 "            OpBranchConditional %comp %tb %fb\n"
3379                 "%tb       = OpLabel\n"
3380                 "            OpBranch %cm\n"
3381                 "%fb       = OpLabel\n"
3382                 "            OpBranch %cm\n"
3383                 "%cm       = OpLabel\n"
3384                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3385                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3386
3387                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3388                 "            OpStore %outloc %res\n"
3389                 "            OpReturn\n"
3390
3391                 "            OpFunctionEnd\n";
3392         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3393         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3394         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3395
3396         specStruct.assembly =
3397                 string(getComputeAsmShaderPreamble()) +
3398
3399                 "OpSource GLSL 430\n"
3400                 "OpName %main \"main\"\n"
3401                 "OpName %id \"gl_GlobalInvocationID\"\n"
3402
3403                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3404
3405                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3406
3407                 "%id = OpVariable %uvec3ptr Input\n"
3408                 "%zero       = OpConstant %i32 0\n"
3409                 "%float_0    = OpConstant %f32 0.0\n"
3410                 "%float_1    = OpConstant %f32 1.0\n"
3411                 "%float_n1   = OpConstant %f32 -1.0\n"
3412
3413                 "%v2f32      = OpTypeVector %f32 2\n"
3414                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3415                 "%Data       = OpTypeStruct %Data2 %f32\n"
3416
3417                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3418                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3419                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3420                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3421                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3422                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3423
3424                 "%main     = OpFunction %void None %voidf\n"
3425                 "%entry    = OpLabel\n"
3426                 "%idval    = OpLoad %uvec3 %id\n"
3427                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3428                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3429                 "%inval    = OpLoad %f32 %inloc\n"
3430
3431                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3432                 "            OpSelectionMerge %cm None\n"
3433                 "            OpBranchConditional %comp %tb %fb\n"
3434                 "%tb       = OpLabel\n"
3435                 "            OpBranch %cm\n"
3436                 "%fb       = OpLabel\n"
3437                 "            OpBranch %cm\n"
3438                 "%cm       = OpLabel\n"
3439                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3440                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3441
3442                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3443                 "            OpStore %outloc %res\n"
3444                 "            OpReturn\n"
3445
3446                 "            OpFunctionEnd\n";
3447         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3448         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3449         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3450
3451         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3452         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3453         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3454         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3455         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3456         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3457         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3458 }
3459
3460 string generateConstantDefinitions (int count)
3461 {
3462         std::ostringstream      r;
3463         for (int i = 0; i < count; i++)
3464                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3465         r << "\n";
3466         return r.str();
3467 }
3468
3469 string generateSwitchCases (int count)
3470 {
3471         std::ostringstream      r;
3472         for (int i = 0; i < count; i++)
3473                 r << " " << i << " %case" << i;
3474         r << "\n";
3475         return r.str();
3476 }
3477
3478 string generateSwitchTargets (int count)
3479 {
3480         std::ostringstream      r;
3481         for (int i = 0; i < count; i++)
3482                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3483         r << "\n";
3484         return r.str();
3485 }
3486
3487 string generateOpPhiParams (int count)
3488 {
3489         std::ostringstream      r;
3490         for (int i = 0; i < count; i++)
3491                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3492         r << "\n";
3493         return r.str();
3494 }
3495
3496 string generateIntWidth (int value)
3497 {
3498         std::ostringstream      r;
3499         r << value;
3500         return r.str();
3501 }
3502
3503 // Expand input string by injecting "ABC" between the input
3504 // string characters. The acc/add/treshold parameters are used
3505 // to skip some of the injections to make the result less
3506 // uniform (and a lot shorter).
3507 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3508 {
3509         std::ostringstream      res;
3510         const char*                     p = s.c_str();
3511
3512         while (*p)
3513         {
3514                 res << *p;
3515                 acc += add;
3516                 if (acc > treshold)
3517                 {
3518                         acc -= treshold;
3519                         res << "ABC";
3520                 }
3521                 p++;
3522         }
3523         return res.str();
3524 }
3525
3526 // Calculate expected result based on the code string
3527 float calcOpPhiCase5 (float val, const string& s)
3528 {
3529         const char*             p               = s.c_str();
3530         float                   x[8];
3531         bool                    b[8];
3532         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3533         const float             v               = deFloatAbs(val);
3534         float                   res             = 0;
3535         int                             depth   = -1;
3536         int                             skip    = 0;
3537
3538         for (int i = 7; i >= 0; --i)
3539                 x[i] = std::fmod((float)v, (float)(2 << i));
3540         for (int i = 7; i >= 0; --i)
3541                 b[i] = x[i] > tv[i];
3542
3543         while (*p)
3544         {
3545                 if (*p == 'A')
3546                 {
3547                         depth++;
3548                         if (skip == 0 && b[depth])
3549                         {
3550                                 res++;
3551                         }
3552                         else
3553                                 skip++;
3554                 }
3555                 if (*p == 'B')
3556                 {
3557                         if (skip)
3558                                 skip--;
3559                         if (b[depth] || skip)
3560                                 skip++;
3561                 }
3562                 if (*p == 'C')
3563                 {
3564                         depth--;
3565                         if (skip)
3566                                 skip--;
3567                 }
3568                 p++;
3569         }
3570         return res;
3571 }
3572
3573 // In the code string, the letters represent the following:
3574 //
3575 // A:
3576 //     if (certain bit is set)
3577 //     {
3578 //       result++;
3579 //
3580 // B:
3581 //     } else {
3582 //
3583 // C:
3584 //     }
3585 //
3586 // examples:
3587 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3588 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3589 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3590 //
3591 // Code generation gets a bit complicated due to the else-branches,
3592 // which do not generate new values. Thus, the generator needs to
3593 // keep track of the previous variable change seen by the else
3594 // branch.
3595 string generateOpPhiCase5 (const string& s)
3596 {
3597         std::stack<int>                         idStack;
3598         std::stack<std::string>         value;
3599         std::stack<std::string>         valueLabel;
3600         std::stack<std::string>         mergeLeft;
3601         std::stack<std::string>         mergeRight;
3602         std::ostringstream                      res;
3603         const char*                                     p                       = s.c_str();
3604         int                                                     depth           = -1;
3605         int                                                     currId          = 0;
3606         int                                                     iter            = 0;
3607
3608         idStack.push(-1);
3609         value.push("%f32_0");
3610         valueLabel.push("%f32_0 %entry");
3611
3612         while (*p)
3613         {
3614                 if (*p == 'A')
3615                 {
3616                         depth++;
3617                         currId = iter;
3618                         idStack.push(currId);
3619                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3620                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3621                         res << "%t" << currId << " = OpLabel\n";
3622                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3623                         std::ostringstream tag;
3624                         tag << "%rt" << currId;
3625                         value.push(tag.str());
3626                         tag << " %t" << currId;
3627                         valueLabel.push(tag.str());
3628                 }
3629
3630                 if (*p == 'B')
3631                 {
3632                         mergeLeft.push(valueLabel.top());
3633                         value.pop();
3634                         valueLabel.pop();
3635                         res << "\tOpBranch %m" << currId << "\n";
3636                         res << "%f" << currId << " = OpLabel\n";
3637                         std::ostringstream tag;
3638                         tag << value.top() << " %f" << currId;
3639                         valueLabel.pop();
3640                         valueLabel.push(tag.str());
3641                 }
3642
3643                 if (*p == 'C')
3644                 {
3645                         mergeRight.push(valueLabel.top());
3646                         res << "\tOpBranch %m" << currId << "\n";
3647                         res << "%m" << currId << " = OpLabel\n";
3648                         if (*(p + 1) == 0)
3649                                 res << "%res"; // last result goes to %res
3650                         else
3651                                 res << "%rm" << currId;
3652                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3653                         std::ostringstream tag;
3654                         tag << "%rm" << currId;
3655                         value.pop();
3656                         value.push(tag.str());
3657                         tag << " %m" << currId;
3658                         valueLabel.pop();
3659                         valueLabel.push(tag.str());
3660                         mergeLeft.pop();
3661                         mergeRight.pop();
3662                         depth--;
3663                         idStack.pop();
3664                         currId = idStack.top();
3665                 }
3666                 p++;
3667                 iter++;
3668         }
3669         return res.str();
3670 }
3671
3672 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3673 {
3674         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3675         ComputeShaderSpec                               spec1;
3676         ComputeShaderSpec                               spec2;
3677         ComputeShaderSpec                               spec3;
3678         ComputeShaderSpec                               spec4;
3679         ComputeShaderSpec                               spec5;
3680         de::Random                                              rnd                             (deStringHash(group->getName()));
3681         const int                                               numElements             = 100;
3682         vector<float>                                   inputFloats             (numElements, 0);
3683         vector<float>                                   outputFloats1   (numElements, 0);
3684         vector<float>                                   outputFloats2   (numElements, 0);
3685         vector<float>                                   outputFloats3   (numElements, 0);
3686         vector<float>                                   outputFloats4   (numElements, 0);
3687         vector<float>                                   outputFloats5   (numElements, 0);
3688         std::string                                             codestring              = "ABC";
3689         const int                                               test4Width              = 1024;
3690
3691         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3692         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3693         // shader code.
3694         for (int i = 0, acc = 0; i < 9; i++)
3695                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3696
3697         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3698
3699         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3700         floorAll(inputFloats);
3701
3702         for (size_t ndx = 0; ndx < numElements; ++ndx)
3703         {
3704                 switch (ndx % 3)
3705                 {
3706                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3707                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3708                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3709                         default:        break;
3710                 }
3711                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3712                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3713
3714                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3715                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3716
3717                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3718         }
3719
3720         spec1.assembly =
3721                 string(getComputeAsmShaderPreamble()) +
3722
3723                 "OpSource GLSL 430\n"
3724                 "OpName %main \"main\"\n"
3725                 "OpName %id \"gl_GlobalInvocationID\"\n"
3726
3727                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3728
3729                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3730
3731                 "%id = OpVariable %uvec3ptr Input\n"
3732                 "%zero       = OpConstant %i32 0\n"
3733                 "%three      = OpConstant %u32 3\n"
3734                 "%constf5p5  = OpConstant %f32 5.5\n"
3735                 "%constf20p5 = OpConstant %f32 20.5\n"
3736                 "%constf1p75 = OpConstant %f32 1.75\n"
3737                 "%constf8p5  = OpConstant %f32 8.5\n"
3738                 "%constf6p5  = OpConstant %f32 6.5\n"
3739
3740                 "%main     = OpFunction %void None %voidf\n"
3741                 "%entry    = OpLabel\n"
3742                 "%idval    = OpLoad %uvec3 %id\n"
3743                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3744                 "%selector = OpUMod %u32 %x %three\n"
3745                 "            OpSelectionMerge %phi None\n"
3746                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3747
3748                 // Case 1 before OpPhi.
3749                 "%case1    = OpLabel\n"
3750                 "            OpBranch %phi\n"
3751
3752                 "%default  = OpLabel\n"
3753                 "            OpUnreachable\n"
3754
3755                 "%phi      = OpLabel\n"
3756                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3757                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3758                 "%inval    = OpLoad %f32 %inloc\n"
3759                 "%add      = OpFAdd %f32 %inval %operand\n"
3760                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3761                 "            OpStore %outloc %add\n"
3762                 "            OpReturn\n"
3763
3764                 // Case 0 after OpPhi.
3765                 "%case0    = OpLabel\n"
3766                 "            OpBranch %phi\n"
3767
3768
3769                 // Case 2 after OpPhi.
3770                 "%case2    = OpLabel\n"
3771                 "            OpBranch %phi\n"
3772
3773                 "            OpFunctionEnd\n";
3774         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3775         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3776         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3777
3778         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3779
3780         spec2.assembly =
3781                 string(getComputeAsmShaderPreamble()) +
3782
3783                 "OpName %main \"main\"\n"
3784                 "OpName %id \"gl_GlobalInvocationID\"\n"
3785
3786                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3787
3788                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3789
3790                 "%id         = OpVariable %uvec3ptr Input\n"
3791                 "%zero       = OpConstant %i32 0\n"
3792                 "%one        = OpConstant %i32 1\n"
3793                 "%three      = OpConstant %i32 3\n"
3794                 "%constf6p5  = OpConstant %f32 6.5\n"
3795
3796                 "%main       = OpFunction %void None %voidf\n"
3797                 "%entry      = OpLabel\n"
3798                 "%idval      = OpLoad %uvec3 %id\n"
3799                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3800                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3801                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3802                 "%inval      = OpLoad %f32 %inloc\n"
3803                 "              OpBranch %phi\n"
3804
3805                 "%phi        = OpLabel\n"
3806                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3807                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3808                 "%step_next  = OpIAdd %i32 %step %one\n"
3809                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3810                 "%still_loop = OpSLessThan %bool %step %three\n"
3811                 "              OpLoopMerge %exit %phi None\n"
3812                 "              OpBranchConditional %still_loop %phi %exit\n"
3813
3814                 "%exit       = OpLabel\n"
3815                 "              OpStore %outloc %accum\n"
3816                 "              OpReturn\n"
3817                 "              OpFunctionEnd\n";
3818         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3819         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3820         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3821
3822         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3823
3824         spec3.assembly =
3825                 string(getComputeAsmShaderPreamble()) +
3826
3827                 "OpName %main \"main\"\n"
3828                 "OpName %id \"gl_GlobalInvocationID\"\n"
3829
3830                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3831
3832                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3833
3834                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3835                 "%id         = OpVariable %uvec3ptr Input\n"
3836                 "%true       = OpConstantTrue %bool\n"
3837                 "%false      = OpConstantFalse %bool\n"
3838                 "%zero       = OpConstant %i32 0\n"
3839                 "%constf8p5  = OpConstant %f32 8.5\n"
3840
3841                 "%main       = OpFunction %void None %voidf\n"
3842                 "%entry      = OpLabel\n"
3843                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3844                 "%idval      = OpLoad %uvec3 %id\n"
3845                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3846                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3847                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3848                 "%a_init     = OpLoad %f32 %inloc\n"
3849                 "%b_init     = OpLoad %f32 %b\n"
3850                 "              OpBranch %phi\n"
3851
3852                 "%phi        = OpLabel\n"
3853                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3854                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3855                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3856                 "              OpLoopMerge %exit %phi None\n"
3857                 "              OpBranchConditional %still_loop %phi %exit\n"
3858
3859                 "%exit       = OpLabel\n"
3860                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3861                 "              OpStore %outloc %sub\n"
3862                 "              OpReturn\n"
3863                 "              OpFunctionEnd\n";
3864         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3865         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3866         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3867
3868         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3869
3870         spec4.assembly =
3871                 "OpCapability Shader\n"
3872                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3873                 "OpMemoryModel Logical GLSL450\n"
3874                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3875                 "OpExecutionMode %main LocalSize 1 1 1\n"
3876
3877                 "OpSource GLSL 430\n"
3878                 "OpName %main \"main\"\n"
3879                 "OpName %id \"gl_GlobalInvocationID\"\n"
3880
3881                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3882
3883                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3884
3885                 "%id       = OpVariable %uvec3ptr Input\n"
3886                 "%zero     = OpConstant %i32 0\n"
3887                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3888
3889                 + generateConstantDefinitions(test4Width) +
3890
3891                 "%main     = OpFunction %void None %voidf\n"
3892                 "%entry    = OpLabel\n"
3893                 "%idval    = OpLoad %uvec3 %id\n"
3894                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3895                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3896                 "%inval    = OpLoad %f32 %inloc\n"
3897                 "%xf       = OpConvertUToF %f32 %x\n"
3898                 "%xm       = OpFMul %f32 %xf %inval\n"
3899                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3900                 "%xi       = OpConvertFToU %u32 %xa\n"
3901                 "%selector = OpUMod %u32 %xi %cimod\n"
3902                 "            OpSelectionMerge %phi None\n"
3903                 "            OpSwitch %selector %default "
3904
3905                 + generateSwitchCases(test4Width) +
3906
3907                 "%default  = OpLabel\n"
3908                 "            OpUnreachable\n"
3909
3910                 + generateSwitchTargets(test4Width) +
3911
3912                 "%phi      = OpLabel\n"
3913                 "%result   = OpPhi %f32"
3914
3915                 + generateOpPhiParams(test4Width) +
3916
3917                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3918                 "            OpStore %outloc %result\n"
3919                 "            OpReturn\n"
3920
3921                 "            OpFunctionEnd\n";
3922         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3923         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3924         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3925
3926         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3927
3928         spec5.assembly =
3929                 "OpCapability Shader\n"
3930                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3931                 "OpMemoryModel Logical GLSL450\n"
3932                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3933                 "OpExecutionMode %main LocalSize 1 1 1\n"
3934                 "%code     = OpString \"" + codestring + "\"\n"
3935
3936                 "OpSource GLSL 430\n"
3937                 "OpName %main \"main\"\n"
3938                 "OpName %id \"gl_GlobalInvocationID\"\n"
3939
3940                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3941
3942                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3943
3944                 "%id       = OpVariable %uvec3ptr Input\n"
3945                 "%zero     = OpConstant %i32 0\n"
3946                 "%f32_0    = OpConstant %f32 0.0\n"
3947                 "%f32_0_5  = OpConstant %f32 0.5\n"
3948                 "%f32_1    = OpConstant %f32 1.0\n"
3949                 "%f32_1_5  = OpConstant %f32 1.5\n"
3950                 "%f32_2    = OpConstant %f32 2.0\n"
3951                 "%f32_3_5  = OpConstant %f32 3.5\n"
3952                 "%f32_4    = OpConstant %f32 4.0\n"
3953                 "%f32_7_5  = OpConstant %f32 7.5\n"
3954                 "%f32_8    = OpConstant %f32 8.0\n"
3955                 "%f32_15_5 = OpConstant %f32 15.5\n"
3956                 "%f32_16   = OpConstant %f32 16.0\n"
3957                 "%f32_31_5 = OpConstant %f32 31.5\n"
3958                 "%f32_32   = OpConstant %f32 32.0\n"
3959                 "%f32_63_5 = OpConstant %f32 63.5\n"
3960                 "%f32_64   = OpConstant %f32 64.0\n"
3961                 "%f32_127_5 = OpConstant %f32 127.5\n"
3962                 "%f32_128  = OpConstant %f32 128.0\n"
3963                 "%f32_256  = OpConstant %f32 256.0\n"
3964
3965                 "%main     = OpFunction %void None %voidf\n"
3966                 "%entry    = OpLabel\n"
3967                 "%idval    = OpLoad %uvec3 %id\n"
3968                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3969                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3970                 "%inval    = OpLoad %f32 %inloc\n"
3971
3972                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3973                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3974                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3975                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3976                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3977                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3978                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3979                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3980                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3981
3982                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3983                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3984                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3985                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3986                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3987                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3988                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3989                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3990
3991                 + generateOpPhiCase5(codestring) +
3992
3993                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3994                 "            OpStore %outloc %res\n"
3995                 "            OpReturn\n"
3996
3997                 "            OpFunctionEnd\n";
3998         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3999         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
4000         spec5.numWorkGroups = IVec3(numElements, 1, 1);
4001
4002         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
4003
4004         createOpPhiVartypeTests(group, testCtx);
4005
4006         return group.release();
4007 }
4008
4009 // Assembly code used for testing block order is based on GLSL source code:
4010 //
4011 // #version 430
4012 //
4013 // layout(std140, set = 0, binding = 0) readonly buffer Input {
4014 //   float elements[];
4015 // } input_data;
4016 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
4017 //   float elements[];
4018 // } output_data;
4019 //
4020 // void main() {
4021 //   uint x = gl_GlobalInvocationID.x;
4022 //   output_data.elements[x] = input_data.elements[x];
4023 //   if (x > uint(50)) {
4024 //     switch (x % uint(3)) {
4025 //       case 0: output_data.elements[x] += 1.5f; break;
4026 //       case 1: output_data.elements[x] += 42.f; break;
4027 //       case 2: output_data.elements[x] -= 27.f; break;
4028 //       default: break;
4029 //     }
4030 //   } else {
4031 //     output_data.elements[x] = -input_data.elements[x];
4032 //   }
4033 // }
4034 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
4035 {
4036         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
4037         ComputeShaderSpec                               spec;
4038         de::Random                                              rnd                             (deStringHash(group->getName()));
4039         const int                                               numElements             = 100;
4040         vector<float>                                   inputFloats             (numElements, 0);
4041         vector<float>                                   outputFloats    (numElements, 0);
4042
4043         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4044
4045         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
4046         floorAll(inputFloats);
4047
4048         for (size_t ndx = 0; ndx <= 50; ++ndx)
4049                 outputFloats[ndx] = -inputFloats[ndx];
4050
4051         for (size_t ndx = 51; ndx < numElements; ++ndx)
4052         {
4053                 switch (ndx % 3)
4054                 {
4055                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
4056                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
4057                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
4058                         default:        break;
4059                 }
4060         }
4061
4062         spec.assembly =
4063                 string(getComputeAsmShaderPreamble()) +
4064
4065                 "OpSource GLSL 430\n"
4066                 "OpName %main \"main\"\n"
4067                 "OpName %id \"gl_GlobalInvocationID\"\n"
4068
4069                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4070
4071                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4072
4073                 "%u32ptr       = OpTypePointer Function %u32\n"
4074                 "%u32ptr_input = OpTypePointer Input %u32\n"
4075
4076                 + string(getComputeAsmInputOutputBuffer()) +
4077
4078                 "%id        = OpVariable %uvec3ptr Input\n"
4079                 "%zero      = OpConstant %i32 0\n"
4080                 "%const3    = OpConstant %u32 3\n"
4081                 "%const50   = OpConstant %u32 50\n"
4082                 "%constf1p5 = OpConstant %f32 1.5\n"
4083                 "%constf27  = OpConstant %f32 27.0\n"
4084                 "%constf42  = OpConstant %f32 42.0\n"
4085
4086                 "%main = OpFunction %void None %voidf\n"
4087
4088                 // entry block.
4089                 "%entry    = OpLabel\n"
4090
4091                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
4092                 "%xvar     = OpVariable %u32ptr Function\n"
4093                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
4094                 "%x        = OpLoad %u32 %xptr\n"
4095                 "            OpStore %xvar %x\n"
4096
4097                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
4098                 "            OpSelectionMerge %if_merge None\n"
4099                 "            OpBranchConditional %cmp %if_true %if_false\n"
4100
4101                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
4102                 "%if_false = OpLabel\n"
4103                 "%x_f      = OpLoad %u32 %xvar\n"
4104                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
4105                 "%inval_f  = OpLoad %f32 %inloc_f\n"
4106                 "%negate   = OpFNegate %f32 %inval_f\n"
4107                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
4108                 "            OpStore %outloc_f %negate\n"
4109                 "            OpBranch %if_merge\n"
4110
4111                 // Merge block for if-statement: placed in the middle of true and false branch.
4112                 "%if_merge = OpLabel\n"
4113                 "            OpReturn\n"
4114
4115                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
4116                 "%if_true  = OpLabel\n"
4117                 "%xval_t   = OpLoad %u32 %xvar\n"
4118                 "%mod      = OpUMod %u32 %xval_t %const3\n"
4119                 "            OpSelectionMerge %switch_merge None\n"
4120                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
4121
4122                 // Merge block for switch-statement: placed before the case
4123                 // bodies.  But it must follow OpSwitch which dominates it.
4124                 "%switch_merge = OpLabel\n"
4125                 "                OpBranch %if_merge\n"
4126
4127                 // Case 1 for switch-statement: placed before case 0.
4128                 // It must follow the OpSwitch that dominates it.
4129                 "%case1    = OpLabel\n"
4130                 "%x_1      = OpLoad %u32 %xvar\n"
4131                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
4132                 "%inval_1  = OpLoad %f32 %inloc_1\n"
4133                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
4134                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
4135                 "            OpStore %outloc_1 %addf42\n"
4136                 "            OpBranch %switch_merge\n"
4137
4138                 // Case 2 for switch-statement.
4139                 "%case2    = OpLabel\n"
4140                 "%x_2      = OpLoad %u32 %xvar\n"
4141                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
4142                 "%inval_2  = OpLoad %f32 %inloc_2\n"
4143                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
4144                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
4145                 "            OpStore %outloc_2 %subf27\n"
4146                 "            OpBranch %switch_merge\n"
4147
4148                 // Default case for switch-statement: placed in the middle of normal cases.
4149                 "%default = OpLabel\n"
4150                 "           OpBranch %switch_merge\n"
4151
4152                 // Case 0 for switch-statement: out of order.
4153                 "%case0    = OpLabel\n"
4154                 "%x_0      = OpLoad %u32 %xvar\n"
4155                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4156                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4157                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4158                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4159                 "            OpStore %outloc_0 %addf1p5\n"
4160                 "            OpBranch %switch_merge\n"
4161
4162                 "            OpFunctionEnd\n";
4163         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4164         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4165         spec.numWorkGroups = IVec3(numElements, 1, 1);
4166
4167         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4168
4169         return group.release();
4170 }
4171
4172 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4173 {
4174         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4175         ComputeShaderSpec                               spec1;
4176         ComputeShaderSpec                               spec2;
4177         de::Random                                              rnd                             (deStringHash(group->getName()));
4178         const int                                               numElements             = 100;
4179         vector<float>                                   inputFloats             (numElements, 0);
4180         vector<float>                                   outputFloats1   (numElements, 0);
4181         vector<float>                                   outputFloats2   (numElements, 0);
4182         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4183
4184         for (size_t ndx = 0; ndx < numElements; ++ndx)
4185         {
4186                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4187                 outputFloats2[ndx] = -inputFloats[ndx];
4188         }
4189
4190         const string assembly(
4191                 "OpCapability Shader\n"
4192                 "OpMemoryModel Logical GLSL450\n"
4193                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4194                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4195                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4196                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4197                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4198                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4199
4200                 "OpName %comp_main1              \"entrypoint1\"\n"
4201                 "OpName %comp_main2              \"entrypoint2\"\n"
4202                 "OpName %vert_main               \"entrypoint2\"\n"
4203                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4204                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4205                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4206                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4207                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4208                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4209                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4210
4211                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4212                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4213                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4214                 "OpDecorate %vert_builtin_st         Block\n"
4215                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4216                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4217                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4218
4219                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4220
4221                 "%zero       = OpConstant %i32 0\n"
4222                 "%one        = OpConstant %u32 1\n"
4223                 "%c_f32_1    = OpConstant %f32 1\n"
4224
4225                 "%i32inputptr         = OpTypePointer Input %i32\n"
4226                 "%vec4                = OpTypeVector %f32 4\n"
4227                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4228                 "%f32arr1             = OpTypeArray %f32 %one\n"
4229                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4230                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4231                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4232
4233                 "%id         = OpVariable %uvec3ptr Input\n"
4234                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4235                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4236                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4237
4238                 // gl_Position = vec4(1.);
4239                 "%vert_main  = OpFunction %void None %voidf\n"
4240                 "%vert_entry = OpLabel\n"
4241                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4242                 "              OpStore %position %c_vec4_1\n"
4243                 "              OpReturn\n"
4244                 "              OpFunctionEnd\n"
4245
4246                 // Double inputs.
4247                 "%comp_main1  = OpFunction %void None %voidf\n"
4248                 "%comp1_entry = OpLabel\n"
4249                 "%idval1      = OpLoad %uvec3 %id\n"
4250                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4251                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4252                 "%inval1      = OpLoad %f32 %inloc1\n"
4253                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4254                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4255                 "               OpStore %outloc1 %add\n"
4256                 "               OpReturn\n"
4257                 "               OpFunctionEnd\n"
4258
4259                 // Negate inputs.
4260                 "%comp_main2  = OpFunction %void None %voidf\n"
4261                 "%comp2_entry = OpLabel\n"
4262                 "%idval2      = OpLoad %uvec3 %id\n"
4263                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4264                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4265                 "%inval2      = OpLoad %f32 %inloc2\n"
4266                 "%neg         = OpFNegate %f32 %inval2\n"
4267                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4268                 "               OpStore %outloc2 %neg\n"
4269                 "               OpReturn\n"
4270                 "               OpFunctionEnd\n");
4271
4272         spec1.assembly = assembly;
4273         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4274         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4275         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4276         spec1.entryPoint = "entrypoint1";
4277
4278         spec2.assembly = assembly;
4279         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4280         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4281         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4282         spec2.entryPoint = "entrypoint2";
4283
4284         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4285         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4286
4287         return group.release();
4288 }
4289
4290 inline std::string makeLongUTF8String (size_t num4ByteChars)
4291 {
4292         // An example of a longest valid UTF-8 character.  Be explicit about the
4293         // character type because Microsoft compilers can otherwise interpret the
4294         // character string as being over wide (16-bit) characters. Ideally, we
4295         // would just use a C++11 UTF-8 string literal, but we want to support older
4296         // Microsoft compilers.
4297         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4298         std::string longString;
4299         longString.reserve(num4ByteChars * 4);
4300         for (size_t count = 0; count < num4ByteChars; count++)
4301         {
4302                 longString += earthAfrica;
4303         }
4304         return longString;
4305 }
4306
4307 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4308 {
4309         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4310         vector<CaseParameter>                   cases;
4311         de::Random                                              rnd                             (deStringHash(group->getName()));
4312         const int                                               numElements             = 100;
4313         vector<float>                                   positiveFloats  (numElements, 0);
4314         vector<float>                                   negativeFloats  (numElements, 0);
4315         const StringTemplate                    shaderTemplate  (
4316                 "OpCapability Shader\n"
4317                 "OpMemoryModel Logical GLSL450\n"
4318
4319                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4320                 "OpExecutionMode %main LocalSize 1 1 1\n"
4321
4322                 "${SOURCE}\n"
4323
4324                 "OpName %main           \"main\"\n"
4325                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4326
4327                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4328
4329                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4330
4331                 "%id        = OpVariable %uvec3ptr Input\n"
4332                 "%zero      = OpConstant %i32 0\n"
4333
4334                 "%main      = OpFunction %void None %voidf\n"
4335                 "%label     = OpLabel\n"
4336                 "%idval     = OpLoad %uvec3 %id\n"
4337                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4338                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4339                 "%inval     = OpLoad %f32 %inloc\n"
4340                 "%neg       = OpFNegate %f32 %inval\n"
4341                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4342                 "             OpStore %outloc %neg\n"
4343                 "             OpReturn\n"
4344                 "             OpFunctionEnd\n");
4345
4346         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4347         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4348         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4349                                                                                                                                                         "OpSource GLSL 430 %fname"));
4350         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4351                                                                                                                                                         "OpSource GLSL 430 %fname"));
4352         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4353                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4354         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4355                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4356         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4357                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4358         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4359                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4360         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4361                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4362                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4363         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4364                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4365                                                                                                                                                         "OpSourceContinued \"\""));
4366         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4367                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4368                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4369         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4370                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4371                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4372         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4373                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4374                                                                                                                                                         "OpSourceContinued \"void\"\n"
4375                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4376                                                                                                                                                         "OpSourceContinued \"{}\""));
4377         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4378                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4379                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4380
4381         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4382
4383         for (size_t ndx = 0; ndx < numElements; ++ndx)
4384                 negativeFloats[ndx] = -positiveFloats[ndx];
4385
4386         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4387         {
4388                 map<string, string>             specializations;
4389                 ComputeShaderSpec               spec;
4390
4391                 specializations["SOURCE"] = cases[caseNdx].param;
4392                 spec.assembly = shaderTemplate.specialize(specializations);
4393                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4394                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4395                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4396
4397                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4398         }
4399
4400         return group.release();
4401 }
4402
4403 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4404 {
4405         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4406         vector<CaseParameter>                   cases;
4407         de::Random                                              rnd                             (deStringHash(group->getName()));
4408         const int                                               numElements             = 100;
4409         vector<float>                                   inputFloats             (numElements, 0);
4410         vector<float>                                   outputFloats    (numElements, 0);
4411         const StringTemplate                    shaderTemplate  (
4412                 string(getComputeAsmShaderPreamble()) +
4413
4414                 "OpSourceExtension \"${EXTENSION}\"\n"
4415
4416                 "OpName %main           \"main\"\n"
4417                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4418
4419                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4420
4421                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4422
4423                 "%id        = OpVariable %uvec3ptr Input\n"
4424                 "%zero      = OpConstant %i32 0\n"
4425
4426                 "%main      = OpFunction %void None %voidf\n"
4427                 "%label     = OpLabel\n"
4428                 "%idval     = OpLoad %uvec3 %id\n"
4429                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4430                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4431                 "%inval     = OpLoad %f32 %inloc\n"
4432                 "%neg       = OpFNegate %f32 %inval\n"
4433                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4434                 "             OpStore %outloc %neg\n"
4435                 "             OpReturn\n"
4436                 "             OpFunctionEnd\n");
4437
4438         cases.push_back(CaseParameter("empty_extension",        ""));
4439         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4440         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4441         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4442         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4443
4444         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4445
4446         for (size_t ndx = 0; ndx < numElements; ++ndx)
4447                 outputFloats[ndx] = -inputFloats[ndx];
4448
4449         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4450         {
4451                 map<string, string>             specializations;
4452                 ComputeShaderSpec               spec;
4453
4454                 specializations["EXTENSION"] = cases[caseNdx].param;
4455                 spec.assembly = shaderTemplate.specialize(specializations);
4456                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4457                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4458                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4459
4460                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4461         }
4462
4463         return group.release();
4464 }
4465
4466 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4467 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4468 {
4469         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4470         vector<CaseParameter>                   cases;
4471         de::Random                                              rnd                             (deStringHash(group->getName()));
4472         const int                                               numElements             = 100;
4473         vector<float>                                   positiveFloats  (numElements, 0);
4474         vector<float>                                   negativeFloats  (numElements, 0);
4475         const StringTemplate                    shaderTemplate  (
4476                 string(getComputeAsmShaderPreamble()) +
4477
4478                 "OpSource GLSL 430\n"
4479                 "OpName %main           \"main\"\n"
4480                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4481
4482                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4483
4484                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4485                 "%uvec2     = OpTypeVector %u32 2\n"
4486                 "%bvec3     = OpTypeVector %bool 3\n"
4487                 "%fvec4     = OpTypeVector %f32 4\n"
4488                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4489                 "%const100  = OpConstant %u32 100\n"
4490                 "%uarr100   = OpTypeArray %i32 %const100\n"
4491                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4492                 "%pointer   = OpTypePointer Function %i32\n"
4493                 + string(getComputeAsmInputOutputBuffer()) +
4494
4495                 "%null      = OpConstantNull ${TYPE}\n"
4496
4497                 "%id        = OpVariable %uvec3ptr Input\n"
4498                 "%zero      = OpConstant %i32 0\n"
4499
4500                 "%main      = OpFunction %void None %voidf\n"
4501                 "%label     = OpLabel\n"
4502                 "%idval     = OpLoad %uvec3 %id\n"
4503                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4504                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4505                 "%inval     = OpLoad %f32 %inloc\n"
4506                 "%neg       = OpFNegate %f32 %inval\n"
4507                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4508                 "             OpStore %outloc %neg\n"
4509                 "             OpReturn\n"
4510                 "             OpFunctionEnd\n");
4511
4512         cases.push_back(CaseParameter("bool",                   "%bool"));
4513         cases.push_back(CaseParameter("sint32",                 "%i32"));
4514         cases.push_back(CaseParameter("uint32",                 "%u32"));
4515         cases.push_back(CaseParameter("float32",                "%f32"));
4516         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4517         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4518         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4519         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4520         cases.push_back(CaseParameter("array",                  "%uarr100"));
4521         cases.push_back(CaseParameter("struct",                 "%struct"));
4522         cases.push_back(CaseParameter("pointer",                "%pointer"));
4523
4524         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4525
4526         for (size_t ndx = 0; ndx < numElements; ++ndx)
4527                 negativeFloats[ndx] = -positiveFloats[ndx];
4528
4529         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4530         {
4531                 map<string, string>             specializations;
4532                 ComputeShaderSpec               spec;
4533
4534                 specializations["TYPE"] = cases[caseNdx].param;
4535                 spec.assembly = shaderTemplate.specialize(specializations);
4536                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4537                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4538                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4539
4540                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4541         }
4542
4543         return group.release();
4544 }
4545
4546 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4547 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4548 {
4549         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4550         vector<CaseParameter>                   cases;
4551         de::Random                                              rnd                             (deStringHash(group->getName()));
4552         const int                                               numElements             = 100;
4553         vector<float>                                   positiveFloats  (numElements, 0);
4554         vector<float>                                   negativeFloats  (numElements, 0);
4555         const StringTemplate                    shaderTemplate  (
4556                 string(getComputeAsmShaderPreamble()) +
4557
4558                 "OpSource GLSL 430\n"
4559                 "OpName %main           \"main\"\n"
4560                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4561
4562                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4563
4564                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4565
4566                 "%id        = OpVariable %uvec3ptr Input\n"
4567                 "%zero      = OpConstant %i32 0\n"
4568
4569                 "${CONSTANT}\n"
4570
4571                 "%main      = OpFunction %void None %voidf\n"
4572                 "%label     = OpLabel\n"
4573                 "%idval     = OpLoad %uvec3 %id\n"
4574                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4575                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4576                 "%inval     = OpLoad %f32 %inloc\n"
4577                 "%neg       = OpFNegate %f32 %inval\n"
4578                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4579                 "             OpStore %outloc %neg\n"
4580                 "             OpReturn\n"
4581                 "             OpFunctionEnd\n");
4582
4583         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4584                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4585         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4586                                                                                                         "%ten = OpConstant %f32 10.\n"
4587                                                                                                         "%fzero = OpConstant %f32 0.\n"
4588                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4589                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4590         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4591                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4592                                                                                                         "%fzero = OpConstant %f32 0.\n"
4593                                                                                                         "%one = OpConstant %f32 1.\n"
4594                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4595                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4596                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4597                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4598         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4599                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4600                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4601                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4602                                                                                                         "%one = OpConstant %u32 1\n"
4603                                                                                                         "%ten = OpConstant %i32 10\n"
4604                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4605                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4606                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4607
4608         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4609
4610         for (size_t ndx = 0; ndx < numElements; ++ndx)
4611                 negativeFloats[ndx] = -positiveFloats[ndx];
4612
4613         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4614         {
4615                 map<string, string>             specializations;
4616                 ComputeShaderSpec               spec;
4617
4618                 specializations["CONSTANT"] = cases[caseNdx].param;
4619                 spec.assembly = shaderTemplate.specialize(specializations);
4620                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4621                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4622                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4623
4624                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4625         }
4626
4627         return group.release();
4628 }
4629
4630 // Creates a floating point number with the given exponent, and significand
4631 // bits set. It can only create normalized numbers. Only the least significant
4632 // 24 bits of the significand will be examined. The final bit of the
4633 // significand will also be ignored. This allows alignment to be written
4634 // similarly to C99 hex-floats.
4635 // For example if you wanted to write 0x1.7f34p-12 you would call
4636 // constructNormalizedFloat(-12, 0x7f3400)
4637 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4638 {
4639         float f = 1.0f;
4640
4641         for (deInt32 idx = 0; idx < 23; ++idx)
4642         {
4643                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4644                 significand <<= 1;
4645         }
4646
4647         return std::ldexp(f, exponent);
4648 }
4649
4650 // Compare instruction for the OpQuantizeF16 compute exact case.
4651 // Returns true if the output is what is expected from the test case.
4652 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4653 {
4654         if (outputAllocs.size() != 1)
4655                 return false;
4656
4657         // Only size is needed because we cannot compare Nans.
4658         size_t byteSize = expectedOutputs[0].getByteSize();
4659
4660         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4661
4662         if (byteSize != 4*sizeof(float)) {
4663                 return false;
4664         }
4665
4666         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4667                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4668                 return false;
4669         }
4670         outputAsFloat++;
4671
4672         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4673                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4674                 return false;
4675         }
4676         outputAsFloat++;
4677
4678         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4679                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4680                 return false;
4681         }
4682         outputAsFloat++;
4683
4684         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4685                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4686                 return false;
4687         }
4688
4689         return true;
4690 }
4691
4692 // Checks that every output from a test-case is a float NaN.
4693 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4694 {
4695         if (outputAllocs.size() != 1)
4696                 return false;
4697
4698         // Only size is needed because we cannot compare Nans.
4699         size_t byteSize = expectedOutputs[0].getByteSize();
4700
4701         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4702
4703         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4704         {
4705                 if (!deFloatIsNaN(output_as_float[idx]))
4706                 {
4707                         return false;
4708                 }
4709         }
4710
4711         return true;
4712 }
4713
4714 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4715 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4716 {
4717         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4718
4719         const std::string shader (
4720                 string(getComputeAsmShaderPreamble()) +
4721
4722                 "OpSource GLSL 430\n"
4723                 "OpName %main           \"main\"\n"
4724                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4725
4726                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4727
4728                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4729
4730                 "%id        = OpVariable %uvec3ptr Input\n"
4731                 "%zero      = OpConstant %i32 0\n"
4732
4733                 "%main      = OpFunction %void None %voidf\n"
4734                 "%label     = OpLabel\n"
4735                 "%idval     = OpLoad %uvec3 %id\n"
4736                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4737                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4738                 "%inval     = OpLoad %f32 %inloc\n"
4739                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4740                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4741                 "             OpStore %outloc %quant\n"
4742                 "             OpReturn\n"
4743                 "             OpFunctionEnd\n");
4744
4745         {
4746                 ComputeShaderSpec       spec;
4747                 const deUint32          numElements             = 100;
4748                 vector<float>           infinities;
4749                 vector<float>           results;
4750
4751                 infinities.reserve(numElements);
4752                 results.reserve(numElements);
4753
4754                 for (size_t idx = 0; idx < numElements; ++idx)
4755                 {
4756                         switch(idx % 4)
4757                         {
4758                                 case 0:
4759                                         infinities.push_back(std::numeric_limits<float>::infinity());
4760                                         results.push_back(std::numeric_limits<float>::infinity());
4761                                         break;
4762                                 case 1:
4763                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4764                                         results.push_back(-std::numeric_limits<float>::infinity());
4765                                         break;
4766                                 case 2:
4767                                         infinities.push_back(std::ldexp(1.0f, 16));
4768                                         results.push_back(std::numeric_limits<float>::infinity());
4769                                         break;
4770                                 case 3:
4771                                         infinities.push_back(std::ldexp(-1.0f, 32));
4772                                         results.push_back(-std::numeric_limits<float>::infinity());
4773                                         break;
4774                         }
4775                 }
4776
4777                 spec.assembly = shader;
4778                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4779                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4780                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4781
4782                 group->addChild(new SpvAsmComputeShaderCase(
4783                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4784         }
4785
4786         {
4787                 ComputeShaderSpec       spec;
4788                 vector<float>           nans;
4789                 const deUint32          numElements             = 100;
4790
4791                 nans.reserve(numElements);
4792
4793                 for (size_t idx = 0; idx < numElements; ++idx)
4794                 {
4795                         if (idx % 2 == 0)
4796                         {
4797                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4798                         }
4799                         else
4800                         {
4801                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4802                         }
4803                 }
4804
4805                 spec.assembly = shader;
4806                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4807                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4808                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4809                 spec.verifyIO = &compareNan;
4810
4811                 group->addChild(new SpvAsmComputeShaderCase(
4812                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4813         }
4814
4815         {
4816                 ComputeShaderSpec       spec;
4817                 vector<float>           small;
4818                 vector<float>           zeros;
4819                 const deUint32          numElements             = 100;
4820
4821                 small.reserve(numElements);
4822                 zeros.reserve(numElements);
4823
4824                 for (size_t idx = 0; idx < numElements; ++idx)
4825                 {
4826                         switch(idx % 6)
4827                         {
4828                                 case 0:
4829                                         small.push_back(0.f);
4830                                         zeros.push_back(0.f);
4831                                         break;
4832                                 case 1:
4833                                         small.push_back(-0.f);
4834                                         zeros.push_back(-0.f);
4835                                         break;
4836                                 case 2:
4837                                         small.push_back(std::ldexp(1.0f, -16));
4838                                         zeros.push_back(0.f);
4839                                         break;
4840                                 case 3:
4841                                         small.push_back(std::ldexp(-1.0f, -32));
4842                                         zeros.push_back(-0.f);
4843                                         break;
4844                                 case 4:
4845                                         small.push_back(std::ldexp(1.0f, -127));
4846                                         zeros.push_back(0.f);
4847                                         break;
4848                                 case 5:
4849                                         small.push_back(-std::ldexp(1.0f, -128));
4850                                         zeros.push_back(-0.f);
4851                                         break;
4852                         }
4853                 }
4854
4855                 spec.assembly = shader;
4856                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4857                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4858                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4859
4860                 group->addChild(new SpvAsmComputeShaderCase(
4861                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4862         }
4863
4864         {
4865                 ComputeShaderSpec       spec;
4866                 vector<float>           exact;
4867                 const deUint32          numElements             = 200;
4868
4869                 exact.reserve(numElements);
4870
4871                 for (size_t idx = 0; idx < numElements; ++idx)
4872                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4873
4874                 spec.assembly = shader;
4875                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4876                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4877                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4878
4879                 group->addChild(new SpvAsmComputeShaderCase(
4880                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4881         }
4882
4883         {
4884                 ComputeShaderSpec       spec;
4885                 vector<float>           inputs;
4886                 const deUint32          numElements             = 4;
4887
4888                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4889                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4890                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4891                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4892
4893                 spec.assembly = shader;
4894                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4895                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4896                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4897                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4898
4899                 group->addChild(new SpvAsmComputeShaderCase(
4900                         testCtx, "rounded", "Check that are rounded when needed", spec));
4901         }
4902
4903         return group.release();
4904 }
4905
4906 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4907 {
4908         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4909
4910         const std::string shader (
4911                 string(getComputeAsmShaderPreamble()) +
4912
4913                 "OpName %main           \"main\"\n"
4914                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4915
4916                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4917
4918                 "OpDecorate %sc_0  SpecId 0\n"
4919                 "OpDecorate %sc_1  SpecId 1\n"
4920                 "OpDecorate %sc_2  SpecId 2\n"
4921                 "OpDecorate %sc_3  SpecId 3\n"
4922                 "OpDecorate %sc_4  SpecId 4\n"
4923                 "OpDecorate %sc_5  SpecId 5\n"
4924
4925                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4926
4927                 "%id        = OpVariable %uvec3ptr Input\n"
4928                 "%zero      = OpConstant %i32 0\n"
4929                 "%c_u32_6   = OpConstant %u32 6\n"
4930
4931                 "%sc_0      = OpSpecConstant %f32 0.\n"
4932                 "%sc_1      = OpSpecConstant %f32 0.\n"
4933                 "%sc_2      = OpSpecConstant %f32 0.\n"
4934                 "%sc_3      = OpSpecConstant %f32 0.\n"
4935                 "%sc_4      = OpSpecConstant %f32 0.\n"
4936                 "%sc_5      = OpSpecConstant %f32 0.\n"
4937
4938                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4939                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4940                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4941                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4942                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4943                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4944
4945                 "%main      = OpFunction %void None %voidf\n"
4946                 "%label     = OpLabel\n"
4947                 "%idval     = OpLoad %uvec3 %id\n"
4948                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4949                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4950                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4951                 "            OpSelectionMerge %exit None\n"
4952                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4953
4954                 "%case0     = OpLabel\n"
4955                 "             OpStore %outloc %sc_0_quant\n"
4956                 "             OpBranch %exit\n"
4957
4958                 "%case1     = OpLabel\n"
4959                 "             OpStore %outloc %sc_1_quant\n"
4960                 "             OpBranch %exit\n"
4961
4962                 "%case2     = OpLabel\n"
4963                 "             OpStore %outloc %sc_2_quant\n"
4964                 "             OpBranch %exit\n"
4965
4966                 "%case3     = OpLabel\n"
4967                 "             OpStore %outloc %sc_3_quant\n"
4968                 "             OpBranch %exit\n"
4969
4970                 "%case4     = OpLabel\n"
4971                 "             OpStore %outloc %sc_4_quant\n"
4972                 "             OpBranch %exit\n"
4973
4974                 "%case5     = OpLabel\n"
4975                 "             OpStore %outloc %sc_5_quant\n"
4976                 "             OpBranch %exit\n"
4977
4978                 "%exit      = OpLabel\n"
4979                 "             OpReturn\n"
4980
4981                 "             OpFunctionEnd\n");
4982
4983         {
4984                 ComputeShaderSpec       spec;
4985                 const deUint8           numCases        = 4;
4986                 vector<float>           inputs          (numCases, 0.f);
4987                 vector<float>           outputs;
4988
4989                 spec.assembly           = shader;
4990                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4991
4992                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4993                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4994                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4995                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4996
4997                 outputs.push_back(std::numeric_limits<float>::infinity());
4998                 outputs.push_back(-std::numeric_limits<float>::infinity());
4999                 outputs.push_back(std::numeric_limits<float>::infinity());
5000                 outputs.push_back(-std::numeric_limits<float>::infinity());
5001
5002                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5003                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5004
5005                 group->addChild(new SpvAsmComputeShaderCase(
5006                         testCtx, "infinities", "Check that infinities propagated and created", spec));
5007         }
5008
5009         {
5010                 ComputeShaderSpec       spec;
5011                 const deUint8           numCases        = 2;
5012                 vector<float>           inputs          (numCases, 0.f);
5013                 vector<float>           outputs;
5014
5015                 spec.assembly           = shader;
5016                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5017                 spec.verifyIO           = &compareNan;
5018
5019                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
5020                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
5021
5022                 for (deUint8 idx = 0; idx < numCases; ++idx)
5023                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
5024
5025                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5026                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5027
5028                 group->addChild(new SpvAsmComputeShaderCase(
5029                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
5030         }
5031
5032         {
5033                 ComputeShaderSpec       spec;
5034                 const deUint8           numCases        = 6;
5035                 vector<float>           inputs          (numCases, 0.f);
5036                 vector<float>           outputs;
5037
5038                 spec.assembly           = shader;
5039                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5040
5041                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
5042                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
5043                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
5044                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
5045                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
5046                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
5047
5048                 outputs.push_back(0.f);
5049                 outputs.push_back(-0.f);
5050                 outputs.push_back(0.f);
5051                 outputs.push_back(-0.f);
5052                 outputs.push_back(0.f);
5053                 outputs.push_back(-0.f);
5054
5055                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5056                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5057
5058                 group->addChild(new SpvAsmComputeShaderCase(
5059                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
5060         }
5061
5062         {
5063                 ComputeShaderSpec       spec;
5064                 const deUint8           numCases        = 6;
5065                 vector<float>           inputs          (numCases, 0.f);
5066                 vector<float>           outputs;
5067
5068                 spec.assembly           = shader;
5069                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5070
5071                 for (deUint8 idx = 0; idx < 6; ++idx)
5072                 {
5073                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
5074                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
5075                         outputs.push_back(f);
5076                 }
5077
5078                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5079                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5080
5081                 group->addChild(new SpvAsmComputeShaderCase(
5082                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
5083         }
5084
5085         {
5086                 ComputeShaderSpec       spec;
5087                 const deUint8           numCases        = 4;
5088                 vector<float>           inputs          (numCases, 0.f);
5089                 vector<float>           outputs;
5090
5091                 spec.assembly           = shader;
5092                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5093                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
5094
5095                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
5096                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
5097                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
5098                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
5099
5100                 for (deUint8 idx = 0; idx < numCases; ++idx)
5101                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
5102
5103                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5104                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5105
5106                 group->addChild(new SpvAsmComputeShaderCase(
5107                         testCtx, "rounded", "Check that are rounded when needed", spec));
5108         }
5109
5110         return group.release();
5111 }
5112
5113 // Checks that constant null/composite values can be used in computation.
5114 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
5115 {
5116         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
5117         ComputeShaderSpec                               spec;
5118         de::Random                                              rnd                             (deStringHash(group->getName()));
5119         const int                                               numElements             = 100;
5120         vector<float>                                   positiveFloats  (numElements, 0);
5121         vector<float>                                   negativeFloats  (numElements, 0);
5122
5123         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5124
5125         for (size_t ndx = 0; ndx < numElements; ++ndx)
5126                 negativeFloats[ndx] = -positiveFloats[ndx];
5127
5128         spec.assembly =
5129                 "OpCapability Shader\n"
5130                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
5131                 "OpMemoryModel Logical GLSL450\n"
5132                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5133                 "OpExecutionMode %main LocalSize 1 1 1\n"
5134
5135                 "OpSource GLSL 430\n"
5136                 "OpName %main           \"main\"\n"
5137                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5138
5139                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5140
5141                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5142
5143                 "%fmat      = OpTypeMatrix %fvec3 3\n"
5144                 "%ten       = OpConstant %u32 10\n"
5145                 "%f32arr10  = OpTypeArray %f32 %ten\n"
5146                 "%fst       = OpTypeStruct %f32 %f32\n"
5147
5148                 + string(getComputeAsmInputOutputBuffer()) +
5149
5150                 "%id        = OpVariable %uvec3ptr Input\n"
5151                 "%zero      = OpConstant %i32 0\n"
5152
5153                 // Create a bunch of null values
5154                 "%unull     = OpConstantNull %u32\n"
5155                 "%fnull     = OpConstantNull %f32\n"
5156                 "%vnull     = OpConstantNull %fvec3\n"
5157                 "%mnull     = OpConstantNull %fmat\n"
5158                 "%anull     = OpConstantNull %f32arr10\n"
5159                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5160
5161                 "%main      = OpFunction %void None %voidf\n"
5162                 "%label     = OpLabel\n"
5163                 "%idval     = OpLoad %uvec3 %id\n"
5164                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5165                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5166                 "%inval     = OpLoad %f32 %inloc\n"
5167                 "%neg       = OpFNegate %f32 %inval\n"
5168
5169                 // Get the abs() of (a certain element of) those null values
5170                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5171                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5172                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5173                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5174                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5175                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5176                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5177                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5178                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5179                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5180                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5181
5182                 // Add them all
5183                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5184                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5185                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5186                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5187                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5188                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5189
5190                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5191                 "             OpStore %outloc %final\n" // write to output
5192                 "             OpReturn\n"
5193                 "             OpFunctionEnd\n";
5194         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5195         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5196         spec.numWorkGroups = IVec3(numElements, 1, 1);
5197
5198         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5199
5200         return group.release();
5201 }
5202
5203 // Assembly code used for testing loop control is based on GLSL source code:
5204 // #version 430
5205 //
5206 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5207 //   float elements[];
5208 // } input_data;
5209 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5210 //   float elements[];
5211 // } output_data;
5212 //
5213 // void main() {
5214 //   uint x = gl_GlobalInvocationID.x;
5215 //   output_data.elements[x] = input_data.elements[x];
5216 //   for (uint i = 0; i < 4; ++i)
5217 //     output_data.elements[x] += 1.f;
5218 // }
5219 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5220 {
5221         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5222         vector<CaseParameter>                   cases;
5223         de::Random                                              rnd                             (deStringHash(group->getName()));
5224         const int                                               numElements             = 100;
5225         vector<float>                                   inputFloats             (numElements, 0);
5226         vector<float>                                   outputFloats    (numElements, 0);
5227         const StringTemplate                    shaderTemplate  (
5228                 string(getComputeAsmShaderPreamble()) +
5229
5230                 "OpSource GLSL 430\n"
5231                 "OpName %main \"main\"\n"
5232                 "OpName %id \"gl_GlobalInvocationID\"\n"
5233
5234                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5235
5236                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5237
5238                 "%u32ptr      = OpTypePointer Function %u32\n"
5239
5240                 "%id          = OpVariable %uvec3ptr Input\n"
5241                 "%zero        = OpConstant %i32 0\n"
5242                 "%uzero       = OpConstant %u32 0\n"
5243                 "%one         = OpConstant %i32 1\n"
5244                 "%constf1     = OpConstant %f32 1.0\n"
5245                 "%four        = OpConstant %u32 4\n"
5246
5247                 "%main        = OpFunction %void None %voidf\n"
5248                 "%entry       = OpLabel\n"
5249                 "%i           = OpVariable %u32ptr Function\n"
5250                 "               OpStore %i %uzero\n"
5251
5252                 "%idval       = OpLoad %uvec3 %id\n"
5253                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5254                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5255                 "%inval       = OpLoad %f32 %inloc\n"
5256                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5257                 "               OpStore %outloc %inval\n"
5258                 "               OpBranch %loop_entry\n"
5259
5260                 "%loop_entry  = OpLabel\n"
5261                 "%i_val       = OpLoad %u32 %i\n"
5262                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5263                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5264                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5265                 "%loop_body   = OpLabel\n"
5266                 "%outval      = OpLoad %f32 %outloc\n"
5267                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5268                 "               OpStore %outloc %addf1\n"
5269                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5270                 "               OpStore %i %new_i\n"
5271                 "               OpBranch %loop_entry\n"
5272                 "%loop_merge  = OpLabel\n"
5273                 "               OpReturn\n"
5274                 "               OpFunctionEnd\n");
5275
5276         cases.push_back(CaseParameter("none",                           "None"));
5277         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5278         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5279
5280         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5281
5282         for (size_t ndx = 0; ndx < numElements; ++ndx)
5283                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5284
5285         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5286         {
5287                 map<string, string>             specializations;
5288                 ComputeShaderSpec               spec;
5289
5290                 specializations["CONTROL"] = cases[caseNdx].param;
5291                 spec.assembly = shaderTemplate.specialize(specializations);
5292                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5293                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5294                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5295
5296                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5297         }
5298
5299         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5300         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5301
5302         return group.release();
5303 }
5304
5305 // Assembly code used for testing selection control is based on GLSL source code:
5306 // #version 430
5307 //
5308 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5309 //   float elements[];
5310 // } input_data;
5311 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5312 //   float elements[];
5313 // } output_data;
5314 //
5315 // void main() {
5316 //   uint x = gl_GlobalInvocationID.x;
5317 //   float val = input_data.elements[x];
5318 //   if (val > 10.f)
5319 //     output_data.elements[x] = val + 1.f;
5320 //   else
5321 //     output_data.elements[x] = val - 1.f;
5322 // }
5323 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5324 {
5325         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5326         vector<CaseParameter>                   cases;
5327         de::Random                                              rnd                             (deStringHash(group->getName()));
5328         const int                                               numElements             = 100;
5329         vector<float>                                   inputFloats             (numElements, 0);
5330         vector<float>                                   outputFloats    (numElements, 0);
5331         const StringTemplate                    shaderTemplate  (
5332                 string(getComputeAsmShaderPreamble()) +
5333
5334                 "OpSource GLSL 430\n"
5335                 "OpName %main \"main\"\n"
5336                 "OpName %id \"gl_GlobalInvocationID\"\n"
5337
5338                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5339
5340                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5341
5342                 "%id       = OpVariable %uvec3ptr Input\n"
5343                 "%zero     = OpConstant %i32 0\n"
5344                 "%constf1  = OpConstant %f32 1.0\n"
5345                 "%constf10 = OpConstant %f32 10.0\n"
5346
5347                 "%main     = OpFunction %void None %voidf\n"
5348                 "%entry    = OpLabel\n"
5349                 "%idval    = OpLoad %uvec3 %id\n"
5350                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5351                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5352                 "%inval    = OpLoad %f32 %inloc\n"
5353                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5354                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5355
5356                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5357                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5358                 "%if_true  = OpLabel\n"
5359                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5360                 "            OpStore %outloc %addf1\n"
5361                 "            OpBranch %if_end\n"
5362                 "%if_false = OpLabel\n"
5363                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5364                 "            OpStore %outloc %subf1\n"
5365                 "            OpBranch %if_end\n"
5366                 "%if_end   = OpLabel\n"
5367                 "            OpReturn\n"
5368                 "            OpFunctionEnd\n");
5369
5370         cases.push_back(CaseParameter("none",                                   "None"));
5371         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5372         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5373         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5374
5375         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5376
5377         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5378         floorAll(inputFloats);
5379
5380         for (size_t ndx = 0; ndx < numElements; ++ndx)
5381                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5382
5383         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5384         {
5385                 map<string, string>             specializations;
5386                 ComputeShaderSpec               spec;
5387
5388                 specializations["CONTROL"] = cases[caseNdx].param;
5389                 spec.assembly = shaderTemplate.specialize(specializations);
5390                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5391                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5392                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5393
5394                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5395         }
5396
5397         return group.release();
5398 }
5399
5400 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5401 {
5402         // Generate a long name.
5403         std::string longname;
5404         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5405
5406         // Some bad names, abusing utf-8 encoding. This may also cause problems
5407         // with the logs.
5408         // 1. Various illegal code points in utf-8
5409         std::string utf8illegal =
5410                 "Illegal bytes in UTF-8: "
5411                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5412                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5413
5414         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5415         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5416
5417         // 3. Some overlong encodings
5418         std::string utf8overlong =
5419                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5420                 "\xf0\x8f\xbf\xbf";
5421
5422         // 4. Internet "zalgo" meme "bleeding text"
5423         std::string utf8zalgo =
5424                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5425                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5426                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5427                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5428                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5429                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5430                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5431                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5432                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5433                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5434                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5435                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5436                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5437                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5438                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5439                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5440                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5441                 "\x93\xcd\x96\xcc\x97\xff";
5442
5443         // General name abuses
5444         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5445         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5446         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5447         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5448         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5449
5450         // GL keywords
5451         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5452         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5453         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5454         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5455         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5456         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5457         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5458         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5459         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5460         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5461         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5462         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5463         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5464         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5465         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5466         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5467         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5468         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5469         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5470         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5471         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5472 }
5473
5474 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5475 {
5476         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5477         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5478         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5479         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5480         vector<CaseParameter>                   cases;
5481         vector<CaseParameter>                   abuseCases;
5482         vector<string>                                  testFunc;
5483         de::Random                                              rnd                             (deStringHash(group->getName()));
5484         const int                                               numElements             = 128;
5485         vector<float>                                   inputFloats             (numElements, 0);
5486         vector<float>                                   outputFloats    (numElements, 0);
5487
5488         getOpNameAbuseCases(abuseCases);
5489
5490         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5491
5492         for(size_t ndx = 0; ndx < numElements; ++ndx)
5493                 outputFloats[ndx] = -inputFloats[ndx];
5494
5495         const string commonShaderHeader =
5496                 "OpCapability Shader\n"
5497                 "OpMemoryModel Logical GLSL450\n"
5498                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5499                 "OpExecutionMode %main LocalSize 1 1 1\n";
5500
5501         const string commonShaderFooter =
5502                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5503
5504                 + string(getComputeAsmInputOutputBufferTraits())
5505                 + string(getComputeAsmCommonTypes())
5506                 + string(getComputeAsmInputOutputBuffer()) +
5507
5508                 "%id        = OpVariable %uvec3ptr Input\n"
5509                 "%zero      = OpConstant %i32 0\n"
5510
5511                 "%func      = OpFunction %void None %voidf\n"
5512                 "%5         = OpLabel\n"
5513                 "             OpReturn\n"
5514                 "             OpFunctionEnd\n"
5515
5516                 "%main      = OpFunction %void None %voidf\n"
5517                 "%entry     = OpLabel\n"
5518                 "%7         = OpFunctionCall %void %func\n"
5519
5520                 "%idval     = OpLoad %uvec3 %id\n"
5521                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5522
5523                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5524                 "%inval     = OpLoad %f32 %inloc\n"
5525                 "%neg       = OpFNegate %f32 %inval\n"
5526                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5527                 "             OpStore %outloc %neg\n"
5528
5529                 "             OpReturn\n"
5530                 "             OpFunctionEnd\n";
5531
5532         const StringTemplate shaderTemplate (
5533                 "OpCapability Shader\n"
5534                 "OpMemoryModel Logical GLSL450\n"
5535                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5536                 "OpExecutionMode %main LocalSize 1 1 1\n"
5537                 "OpName %${ID} \"${NAME}\"\n" +
5538                 commonShaderFooter);
5539
5540         const std::string multipleNames =
5541                 commonShaderHeader +
5542                 "OpName %main \"to_be\"\n"
5543                 "OpName %id   \"or_not\"\n"
5544                 "OpName %main \"to_be\"\n"
5545                 "OpName %main \"makes_no\"\n"
5546                 "OpName %func \"difference\"\n"
5547                 "OpName %5    \"to_me\"\n" +
5548                 commonShaderFooter;
5549
5550         {
5551                 ComputeShaderSpec       spec;
5552
5553                 spec.assembly           = multipleNames;
5554                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5555                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5556                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5557
5558                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5559         }
5560
5561         const std::string everythingNamed =
5562                 commonShaderHeader +
5563                 "OpName %main   \"name1\"\n"
5564                 "OpName %id     \"name2\"\n"
5565                 "OpName %zero   \"name3\"\n"
5566                 "OpName %entry  \"name4\"\n"
5567                 "OpName %func   \"name5\"\n"
5568                 "OpName %5      \"name6\"\n"
5569                 "OpName %7      \"name7\"\n"
5570                 "OpName %idval  \"name8\"\n"
5571                 "OpName %inloc  \"name9\"\n"
5572                 "OpName %inval  \"name10\"\n"
5573                 "OpName %neg    \"name11\"\n"
5574                 "OpName %outloc \"name12\"\n"+
5575                 commonShaderFooter;
5576         {
5577                 ComputeShaderSpec       spec;
5578
5579                 spec.assembly           = everythingNamed;
5580                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5581                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5582                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5583
5584                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5585         }
5586
5587         const std::string everythingNamedTheSame =
5588                 commonShaderHeader +
5589                 "OpName %main   \"the_same\"\n"
5590                 "OpName %id     \"the_same\"\n"
5591                 "OpName %zero   \"the_same\"\n"
5592                 "OpName %entry  \"the_same\"\n"
5593                 "OpName %func   \"the_same\"\n"
5594                 "OpName %5      \"the_same\"\n"
5595                 "OpName %7      \"the_same\"\n"
5596                 "OpName %idval  \"the_same\"\n"
5597                 "OpName %inloc  \"the_same\"\n"
5598                 "OpName %inval  \"the_same\"\n"
5599                 "OpName %neg    \"the_same\"\n"
5600                 "OpName %outloc \"the_same\"\n"+
5601                 commonShaderFooter;
5602         {
5603                 ComputeShaderSpec       spec;
5604
5605                 spec.assembly           = everythingNamedTheSame;
5606                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5607                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5608                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5609
5610                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5611         }
5612
5613         // main_is_...
5614         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5615         {
5616                 map<string, string>     specializations;
5617                 ComputeShaderSpec       spec;
5618
5619                 specializations["ENTRY"]        = "main";
5620                 specializations["ID"]           = "main";
5621                 specializations["NAME"]         = abuseCases[ndx].param;
5622                 spec.assembly                           = shaderTemplate.specialize(specializations);
5623                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5624                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5625                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5626
5627                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5628         }
5629
5630         // x_is_....
5631         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5632         {
5633                 map<string, string>     specializations;
5634                 ComputeShaderSpec       spec;
5635
5636                 specializations["ENTRY"]        = "main";
5637                 specializations["ID"]           = "x";
5638                 specializations["NAME"]         = abuseCases[ndx].param;
5639                 spec.assembly                           = shaderTemplate.specialize(specializations);
5640                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5641                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5642                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5643
5644                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5645         }
5646
5647         cases.push_back(CaseParameter("_is_main", "main"));
5648         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5649         testFunc.push_back("main");
5650         testFunc.push_back("func");
5651
5652         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5653         {
5654                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5655                 {
5656                         map<string, string>     specializations;
5657                         ComputeShaderSpec       spec;
5658
5659                         specializations["ENTRY"]        = "main";
5660                         specializations["ID"]           = testFunc[fNdx];
5661                         specializations["NAME"]         = cases[ndx].param;
5662                         spec.assembly                           = shaderTemplate.specialize(specializations);
5663                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5664                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5665                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5666
5667                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5668                 }
5669         }
5670
5671         cases.push_back(CaseParameter("_is_entry", "rdc"));
5672
5673         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5674         {
5675                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5676                 {
5677                         map<string, string>     specializations;
5678                         ComputeShaderSpec       spec;
5679
5680                         specializations["ENTRY"]        = "rdc";
5681                         specializations["ID"]           = testFunc[fNdx];
5682                         specializations["NAME"]         = cases[ndx].param;
5683                         spec.assembly                           = shaderTemplate.specialize(specializations);
5684                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5685                         spec.entryPoint                         = "rdc";
5686                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5687                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5688
5689                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5690                 }
5691         }
5692
5693         group->addChild(entryMainGroup.release());
5694         group->addChild(entryNotGroup.release());
5695         group->addChild(abuseGroup.release());
5696
5697         return group.release();
5698 }
5699
5700 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5701 {
5702         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5703         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5704         vector<CaseParameter>                   abuseCases;
5705         vector<string>                                  testFunc;
5706         de::Random                                              rnd(deStringHash(group->getName()));
5707         const int                                               numElements = 128;
5708         vector<float>                                   inputFloats(numElements, 0);
5709         vector<float>                                   outputFloats(numElements, 0);
5710
5711         getOpNameAbuseCases(abuseCases);
5712
5713         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5714
5715         for (size_t ndx = 0; ndx < numElements; ++ndx)
5716                 outputFloats[ndx] = -inputFloats[ndx];
5717
5718         const string commonShaderHeader =
5719                 "OpCapability Shader\n"
5720                 "OpMemoryModel Logical GLSL450\n"
5721                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5722                 "OpExecutionMode %main LocalSize 1 1 1\n";
5723
5724         const string commonShaderFooter =
5725                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5726
5727                 + string(getComputeAsmInputOutputBufferTraits())
5728                 + string(getComputeAsmCommonTypes())
5729                 + string(getComputeAsmInputOutputBuffer()) +
5730
5731                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5732
5733                 "%id        = OpVariable %uvec3ptr Input\n"
5734                 "%zero      = OpConstant %i32 0\n"
5735
5736                 "%main      = OpFunction %void None %voidf\n"
5737                 "%entry     = OpLabel\n"
5738
5739                 "%idval     = OpLoad %uvec3 %id\n"
5740                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5741
5742                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5743                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5744
5745                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5746                 "%inval     = OpLoad %f32 %inloc\n"
5747                 "%neg       = OpFNegate %f32 %inval\n"
5748                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5749                 "             OpStore %outloc %neg\n"
5750
5751                 "             OpReturn\n"
5752                 "             OpFunctionEnd\n";
5753
5754         const StringTemplate shaderTemplate(
5755                 commonShaderHeader +
5756                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5757                 commonShaderFooter);
5758
5759         const std::string multipleNames =
5760                 commonShaderHeader +
5761                 "OpMemberName %u3str 0 \"to_be\"\n"
5762                 "OpMemberName %u3str 1 \"or_not\"\n"
5763                 "OpMemberName %u3str 0 \"to_be\"\n"
5764                 "OpMemberName %u3str 2 \"makes_no\"\n"
5765                 "OpMemberName %u3str 0 \"difference\"\n"
5766                 "OpMemberName %u3str 0 \"to_me\"\n" +
5767                 commonShaderFooter;
5768         {
5769                 ComputeShaderSpec       spec;
5770
5771                 spec.assembly = multipleNames;
5772                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5773                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5774                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5775
5776                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5777         }
5778
5779         const std::string everythingNamedTheSame =
5780                 commonShaderHeader +
5781                 "OpMemberName %u3str 0 \"the_same\"\n"
5782                 "OpMemberName %u3str 1 \"the_same\"\n"
5783                 "OpMemberName %u3str 2 \"the_same\"\n" +
5784                 commonShaderFooter;
5785
5786         {
5787                 ComputeShaderSpec       spec;
5788
5789                 spec.assembly = everythingNamedTheSame;
5790                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5791                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5792                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5793
5794                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5795         }
5796
5797         // u3str_x_is_....
5798         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5799         {
5800                 map<string, string>     specializations;
5801                 ComputeShaderSpec       spec;
5802
5803                 specializations["NAME"] = abuseCases[ndx].param;
5804                 spec.assembly = shaderTemplate.specialize(specializations);
5805                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5806                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5807                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5808
5809                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5810         }
5811
5812         group->addChild(abuseGroup.release());
5813
5814         return group.release();
5815 }
5816
5817 // Assembly code used for testing function control is based on GLSL source code:
5818 //
5819 // #version 430
5820 //
5821 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5822 //   float elements[];
5823 // } input_data;
5824 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5825 //   float elements[];
5826 // } output_data;
5827 //
5828 // float const10() { return 10.f; }
5829 //
5830 // void main() {
5831 //   uint x = gl_GlobalInvocationID.x;
5832 //   output_data.elements[x] = input_data.elements[x] + const10();
5833 // }
5834 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5835 {
5836         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5837         vector<CaseParameter>                   cases;
5838         de::Random                                              rnd                             (deStringHash(group->getName()));
5839         const int                                               numElements             = 100;
5840         vector<float>                                   inputFloats             (numElements, 0);
5841         vector<float>                                   outputFloats    (numElements, 0);
5842         const StringTemplate                    shaderTemplate  (
5843                 string(getComputeAsmShaderPreamble()) +
5844
5845                 "OpSource GLSL 430\n"
5846                 "OpName %main \"main\"\n"
5847                 "OpName %func_const10 \"const10(\"\n"
5848                 "OpName %id \"gl_GlobalInvocationID\"\n"
5849
5850                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5851
5852                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5853
5854                 "%f32f = OpTypeFunction %f32\n"
5855                 "%id = OpVariable %uvec3ptr Input\n"
5856                 "%zero = OpConstant %i32 0\n"
5857                 "%constf10 = OpConstant %f32 10.0\n"
5858
5859                 "%main         = OpFunction %void None %voidf\n"
5860                 "%entry        = OpLabel\n"
5861                 "%idval        = OpLoad %uvec3 %id\n"
5862                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5863                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5864                 "%inval        = OpLoad %f32 %inloc\n"
5865                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5866                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5867                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5868                 "                OpStore %outloc %fadd\n"
5869                 "                OpReturn\n"
5870                 "                OpFunctionEnd\n"
5871
5872                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5873                 "%label        = OpLabel\n"
5874                 "                OpReturnValue %constf10\n"
5875                 "                OpFunctionEnd\n");
5876
5877         cases.push_back(CaseParameter("none",                                           "None"));
5878         cases.push_back(CaseParameter("inline",                                         "Inline"));
5879         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5880         cases.push_back(CaseParameter("pure",                                           "Pure"));
5881         cases.push_back(CaseParameter("const",                                          "Const"));
5882         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5883         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5884         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5885         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5886
5887         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5888
5889         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5890         floorAll(inputFloats);
5891
5892         for (size_t ndx = 0; ndx < numElements; ++ndx)
5893                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5894
5895         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5896         {
5897                 map<string, string>             specializations;
5898                 ComputeShaderSpec               spec;
5899
5900                 specializations["CONTROL"] = cases[caseNdx].param;
5901                 spec.assembly = shaderTemplate.specialize(specializations);
5902                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5903                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5904                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5905
5906                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5907         }
5908
5909         return group.release();
5910 }
5911
5912 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5913 {
5914         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5915         vector<CaseParameter>                   cases;
5916         de::Random                                              rnd                             (deStringHash(group->getName()));
5917         const int                                               numElements             = 100;
5918         vector<float>                                   inputFloats             (numElements, 0);
5919         vector<float>                                   outputFloats    (numElements, 0);
5920         const StringTemplate                    shaderTemplate  (
5921                 string(getComputeAsmShaderPreamble()) +
5922
5923                 "OpSource GLSL 430\n"
5924                 "OpName %main           \"main\"\n"
5925                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5926
5927                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5928
5929                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5930
5931                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5932
5933                 "%id        = OpVariable %uvec3ptr Input\n"
5934                 "%zero      = OpConstant %i32 0\n"
5935                 "%four      = OpConstant %i32 4\n"
5936
5937                 "%main      = OpFunction %void None %voidf\n"
5938                 "%label     = OpLabel\n"
5939                 "%copy      = OpVariable %f32ptr_f Function\n"
5940                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5941                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5942                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5943                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5944                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5945                 "%val1      = OpLoad %f32 %copy\n"
5946                 "%val2      = OpLoad %f32 %inloc\n"
5947                 "%add       = OpFAdd %f32 %val1 %val2\n"
5948                 "             OpStore %outloc %add ${ACCESS}\n"
5949                 "             OpReturn\n"
5950                 "             OpFunctionEnd\n");
5951
5952         cases.push_back(CaseParameter("null",                                   ""));
5953         cases.push_back(CaseParameter("none",                                   "None"));
5954         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5955         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5956         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5957         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5958         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5959
5960         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5961
5962         for (size_t ndx = 0; ndx < numElements; ++ndx)
5963                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5964
5965         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5966         {
5967                 map<string, string>             specializations;
5968                 ComputeShaderSpec               spec;
5969
5970                 specializations["ACCESS"] = cases[caseNdx].param;
5971                 spec.assembly = shaderTemplate.specialize(specializations);
5972                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5973                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5974                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5975
5976                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5977         }
5978
5979         return group.release();
5980 }
5981
5982 // Checks that we can get undefined values for various types, without exercising a computation with it.
5983 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5984 {
5985         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5986         vector<CaseParameter>                   cases;
5987         de::Random                                              rnd                             (deStringHash(group->getName()));
5988         const int                                               numElements             = 100;
5989         vector<float>                                   positiveFloats  (numElements, 0);
5990         vector<float>                                   negativeFloats  (numElements, 0);
5991         const StringTemplate                    shaderTemplate  (
5992                 string(getComputeAsmShaderPreamble()) +
5993
5994                 "OpSource GLSL 430\n"
5995                 "OpName %main           \"main\"\n"
5996                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5997
5998                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5999
6000                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
6001                 "%uvec2     = OpTypeVector %u32 2\n"
6002                 "%fvec4     = OpTypeVector %f32 4\n"
6003                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
6004                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
6005                 "%sampler   = OpTypeSampler\n"
6006                 "%simage    = OpTypeSampledImage %image\n"
6007                 "%const100  = OpConstant %u32 100\n"
6008                 "%uarr100   = OpTypeArray %i32 %const100\n"
6009                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
6010                 "%pointer   = OpTypePointer Function %i32\n"
6011                 + string(getComputeAsmInputOutputBuffer()) +
6012
6013                 "%id        = OpVariable %uvec3ptr Input\n"
6014                 "%zero      = OpConstant %i32 0\n"
6015
6016                 "%main      = OpFunction %void None %voidf\n"
6017                 "%label     = OpLabel\n"
6018
6019                 "%undef     = OpUndef ${TYPE}\n"
6020
6021                 "%idval     = OpLoad %uvec3 %id\n"
6022                 "%x         = OpCompositeExtract %u32 %idval 0\n"
6023
6024                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
6025                 "%inval     = OpLoad %f32 %inloc\n"
6026                 "%neg       = OpFNegate %f32 %inval\n"
6027                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6028                 "             OpStore %outloc %neg\n"
6029                 "             OpReturn\n"
6030                 "             OpFunctionEnd\n");
6031
6032         cases.push_back(CaseParameter("bool",                   "%bool"));
6033         cases.push_back(CaseParameter("sint32",                 "%i32"));
6034         cases.push_back(CaseParameter("uint32",                 "%u32"));
6035         cases.push_back(CaseParameter("float32",                "%f32"));
6036         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
6037         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
6038         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
6039         cases.push_back(CaseParameter("image",                  "%image"));
6040         cases.push_back(CaseParameter("sampler",                "%sampler"));
6041         cases.push_back(CaseParameter("sampledimage",   "%simage"));
6042         cases.push_back(CaseParameter("array",                  "%uarr100"));
6043         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
6044         cases.push_back(CaseParameter("struct",                 "%struct"));
6045         cases.push_back(CaseParameter("pointer",                "%pointer"));
6046
6047         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6048
6049         for (size_t ndx = 0; ndx < numElements; ++ndx)
6050                 negativeFloats[ndx] = -positiveFloats[ndx];
6051
6052         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6053         {
6054                 map<string, string>             specializations;
6055                 ComputeShaderSpec               spec;
6056
6057                 specializations["TYPE"] = cases[caseNdx].param;
6058                 spec.assembly = shaderTemplate.specialize(specializations);
6059                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6060                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6061                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6062
6063                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6064         }
6065
6066                 return group.release();
6067 }
6068
6069 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
6070 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
6071 {
6072         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
6073         vector<CaseParameter>                   cases;
6074         de::Random                                              rnd                             (deStringHash(group->getName()));
6075         const int                                               numElements             = 100;
6076         vector<float>                                   positiveFloats  (numElements, 0);
6077         vector<float>                                   negativeFloats  (numElements, 0);
6078         const StringTemplate                    shaderTemplate  (
6079                 "OpCapability Shader\n"
6080                 "OpCapability Float16\n"
6081                 "OpMemoryModel Logical GLSL450\n"
6082                 "OpEntryPoint GLCompute %main \"main\" %id\n"
6083                 "OpExecutionMode %main LocalSize 1 1 1\n"
6084                 "OpSource GLSL 430\n"
6085                 "OpName %main           \"main\"\n"
6086                 "OpName %id             \"gl_GlobalInvocationID\"\n"
6087
6088                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
6089
6090                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
6091
6092                 "%id        = OpVariable %uvec3ptr Input\n"
6093                 "%zero      = OpConstant %i32 0\n"
6094                 "%f16       = OpTypeFloat 16\n"
6095                 "%c_f16_0   = OpConstant %f16 0.0\n"
6096                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
6097                 "%c_f16_1   = OpConstant %f16 1.0\n"
6098                 "%v2f16     = OpTypeVector %f16 2\n"
6099                 "%v3f16     = OpTypeVector %f16 3\n"
6100                 "%v4f16     = OpTypeVector %f16 4\n"
6101
6102                 "${CONSTANT}\n"
6103
6104                 "%main      = OpFunction %void None %voidf\n"
6105                 "%label     = OpLabel\n"
6106                 "%idval     = OpLoad %uvec3 %id\n"
6107                 "%x         = OpCompositeExtract %u32 %idval 0\n"
6108                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
6109                 "%inval     = OpLoad %f32 %inloc\n"
6110                 "%neg       = OpFNegate %f32 %inval\n"
6111                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6112                 "             OpStore %outloc %neg\n"
6113                 "             OpReturn\n"
6114                 "             OpFunctionEnd\n");
6115
6116
6117         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
6118         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
6119                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6120                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
6121         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
6122                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
6123                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6124                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
6125                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
6126         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
6127                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
6128                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
6129                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
6130                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
6131                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
6132
6133         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6134
6135         for (size_t ndx = 0; ndx < numElements; ++ndx)
6136                 negativeFloats[ndx] = -positiveFloats[ndx];
6137
6138         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6139         {
6140                 map<string, string>             specializations;
6141                 ComputeShaderSpec               spec;
6142
6143                 specializations["CONSTANT"] = cases[caseNdx].param;
6144                 spec.assembly = shaderTemplate.specialize(specializations);
6145                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6146                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6147                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6148
6149                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6150
6151                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6152
6153                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6154         }
6155
6156         return group.release();
6157 }
6158
6159 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6160 {
6161         const size_t            inDataLength    = inData.size();
6162         vector<deFloat16>       result;
6163
6164         result.reserve(inDataLength * inDataLength);
6165
6166         if (argNo == 0)
6167         {
6168                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6169                         result.insert(result.end(), inData.begin(), inData.end());
6170         }
6171
6172         if (argNo == 1)
6173         {
6174                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6175                 {
6176                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6177
6178                         result.insert(result.end(), tmp.begin(), tmp.end());
6179                 }
6180         }
6181
6182         return result;
6183 }
6184
6185 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6186 {
6187         vector<deFloat16>       vec;
6188         vector<deFloat16>       result;
6189
6190         // Create vectors. vec will contain each possible pair from inData
6191         {
6192                 const size_t    inDataLength    = inData.size();
6193
6194                 DE_ASSERT(inDataLength <= 64);
6195
6196                 vec.reserve(2 * inDataLength * inDataLength);
6197
6198                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6199                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6200                 {
6201                         vec.push_back(inData[numIdxX]);
6202                         vec.push_back(inData[numIdxY]);
6203                 }
6204         }
6205
6206         // Create vector pairs. result will contain each possible pair from vec
6207         {
6208                 const size_t    coordsPerVector = 2;
6209                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6210
6211                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6212
6213                 if (argNo == 0)
6214                 {
6215                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6216                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6217                         {
6218                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6219                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6220                         }
6221                 }
6222
6223                 if (argNo == 1)
6224                 {
6225                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6226                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6227                         {
6228                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6229                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6230                         }
6231                 }
6232         }
6233
6234         return result;
6235 }
6236
6237 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6238 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6239 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6240 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6241 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6242 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6243 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6244 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6245
6246 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6247 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6248 {
6249         if (inputs.size() != 2 || outputAllocs.size() != 1)
6250                 return false;
6251
6252         vector<deUint8> input1Bytes;
6253         vector<deUint8> input2Bytes;
6254
6255         inputs[0].getBytes(input1Bytes);
6256         inputs[1].getBytes(input2Bytes);
6257
6258         const deUint32                  denormModesCount                        = 2;
6259         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6260         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6261         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6262         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6263         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6264         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6265         deUint32                                successfulRuns                          = denormModesCount;
6266         std::string                             results[denormModesCount];
6267         TestedLogicalFunction   testedLogicalFunction;
6268
6269         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6270         {
6271                 const bool flushToZero = (denormMode == 1);
6272
6273                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6274                 {
6275                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6276                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6277                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6278                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6279                         deFloat16                       expectedOutput  = float16zero;
6280
6281                         if (onlyTestFunc)
6282                         {
6283                                 if (testedLogicalFunction(f1, f2))
6284                                         expectedOutput = float16one;
6285                         }
6286                         else
6287                         {
6288                                 const bool      f1nan   = f1.isNaN();
6289                                 const bool      f2nan   = f2.isNaN();
6290
6291                                 // Skip NaN floats if not supported by implementation
6292                                 if (!nanSupported && (f1nan || f2nan))
6293                                         continue;
6294
6295                                 if (unationModeAnd)
6296                                 {
6297                                         const bool      ordered         = !f1nan && !f2nan;
6298
6299                                         if (ordered && testedLogicalFunction(f1, f2))
6300                                                 expectedOutput = float16one;
6301                                 }
6302                                 else
6303                                 {
6304                                         const bool      unordered       = f1nan || f2nan;
6305
6306                                         if (unordered || testedLogicalFunction(f1, f2))
6307                                                 expectedOutput = float16one;
6308                                 }
6309                         }
6310
6311                         if (outputAsFP16[idx] != expectedOutput)
6312                         {
6313                                 std::ostringstream str;
6314
6315                                 str << "ERROR: Sub-case #" << idx
6316                                         << " flushToZero:" << flushToZero
6317                                         << std::hex
6318                                         << " failed, inputs: 0x" << f1.bits()
6319                                         << ";0x" << f2.bits()
6320                                         << " output: 0x" << outputAsFP16[idx]
6321                                         << " expected output: 0x" << expectedOutput;
6322
6323                                 results[denormMode] = str.str();
6324
6325                                 successfulRuns--;
6326
6327                                 break;
6328                         }
6329                 }
6330         }
6331
6332         if (successfulRuns == 0)
6333                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6334                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6335
6336         return successfulRuns > 0;
6337 }
6338
6339 } // anonymous
6340
6341 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6342 {
6343         struct NameCodePair { string name, code; };
6344         RGBA                                                    defaultColors[4];
6345         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6346         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6347         map<string, string>                             fragments                               = passthruFragments();
6348         const NameCodePair                              tests[]                                 =
6349         {
6350                 {"unknown", "OpSource Unknown 321"},
6351                 {"essl", "OpSource ESSL 310"},
6352                 {"glsl", "OpSource GLSL 450"},
6353                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6354                 {"opencl_c", "OpSource OpenCL_C 120"},
6355                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6356                 {"file", opsourceGLSLWithFile},
6357                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6358                 // Longest possible source string: SPIR-V limits instructions to 65535
6359                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6360                 // contain 65530 UTF8 characters (one word each) plus one last word
6361                 // containing 3 ASCII characters and \0.
6362                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6363         };
6364
6365         getDefaultColors(defaultColors);
6366         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6367         {
6368                 fragments["debug"] = tests[testNdx].code;
6369                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6370         }
6371
6372         return opSourceTests.release();
6373 }
6374
6375 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6376 {
6377         struct NameCodePair { string name, code; };
6378         RGBA                                                            defaultColors[4];
6379         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6380         map<string, string>                                     fragments                       = passthruFragments();
6381         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6382         const NameCodePair                                      tests[]                         =
6383         {
6384                 {"empty", opsource + "OpSourceContinued \"\""},
6385                 {"short", opsource + "OpSourceContinued \"abcde\""},
6386                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6387                 // Longest possible source string: SPIR-V limits instructions to 65535
6388                 // words, of which the first one is OpSourceContinued/length; the rest
6389                 // will contain 65533 UTF8 characters (one word each) plus one last word
6390                 // containing 3 ASCII characters and \0.
6391                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6392         };
6393
6394         getDefaultColors(defaultColors);
6395         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6396         {
6397                 fragments["debug"] = tests[testNdx].code;
6398                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6399         }
6400
6401         return opSourceTests.release();
6402 }
6403 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6404 {
6405         RGBA                                                             defaultColors[4];
6406         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6407         map<string, string>                                      fragments;
6408         getDefaultColors(defaultColors);
6409         fragments["debug"]                      =
6410                 "%name = OpString \"name\"\n";
6411
6412         fragments["pre_main"]   =
6413                 "OpNoLine\n"
6414                 "OpNoLine\n"
6415                 "OpLine %name 1 1\n"
6416                 "OpNoLine\n"
6417                 "OpLine %name 1 1\n"
6418                 "OpLine %name 1 1\n"
6419                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6420                 "OpNoLine\n"
6421                 "OpLine %name 1 1\n"
6422                 "OpNoLine\n"
6423                 "OpLine %name 1 1\n"
6424                 "OpLine %name 1 1\n"
6425                 "%second_param1 = OpFunctionParameter %v4f32\n"
6426                 "OpNoLine\n"
6427                 "OpNoLine\n"
6428                 "%label_secondfunction = OpLabel\n"
6429                 "OpNoLine\n"
6430                 "OpReturnValue %second_param1\n"
6431                 "OpFunctionEnd\n"
6432                 "OpNoLine\n"
6433                 "OpNoLine\n";
6434
6435         fragments["testfun"]            =
6436                 // A %test_code function that returns its argument unchanged.
6437                 "OpNoLine\n"
6438                 "OpNoLine\n"
6439                 "OpLine %name 1 1\n"
6440                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6441                 "OpNoLine\n"
6442                 "%param1 = OpFunctionParameter %v4f32\n"
6443                 "OpNoLine\n"
6444                 "OpNoLine\n"
6445                 "%label_testfun = OpLabel\n"
6446                 "OpNoLine\n"
6447                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6448                 "OpReturnValue %val1\n"
6449                 "OpFunctionEnd\n"
6450                 "OpLine %name 1 1\n"
6451                 "OpNoLine\n";
6452
6453         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6454
6455         return opLineTests.release();
6456 }
6457
6458 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6459 {
6460         RGBA                                                            defaultColors[4];
6461         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6462         map<string, string>                                     fragments;
6463         std::vector<std::string>                        noExtensions;
6464         GraphicsResources                                       resources;
6465
6466         getDefaultColors(defaultColors);
6467         resources.verifyBinary = veryfiBinaryShader;
6468         resources.spirvVersion = SPIRV_VERSION_1_3;
6469
6470         fragments["moduleprocessed"]                                                    =
6471                 "OpModuleProcessed \"VULKAN CTS\"\n"
6472                 "OpModuleProcessed \"Negative values\"\n"
6473                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6474
6475         fragments["pre_main"]   =
6476                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6477                 "%second_param1 = OpFunctionParameter %v4f32\n"
6478                 "%label_secondfunction = OpLabel\n"
6479                 "OpReturnValue %second_param1\n"
6480                 "OpFunctionEnd\n";
6481
6482         fragments["testfun"]            =
6483                 // A %test_code function that returns its argument unchanged.
6484                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6485                 "%param1 = OpFunctionParameter %v4f32\n"
6486                 "%label_testfun = OpLabel\n"
6487                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6488                 "OpReturnValue %val1\n"
6489                 "OpFunctionEnd\n";
6490
6491         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6492
6493         return opModuleProcessedTests.release();
6494 }
6495
6496
6497 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6498 {
6499         RGBA                                                                                                    defaultColors[4];
6500         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6501         map<string, string>                                                                             fragments;
6502         std::vector<std::pair<std::string, std::string> >               problemStrings;
6503
6504         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6505         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6506         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6507         getDefaultColors(defaultColors);
6508
6509         fragments["debug"]                      =
6510                 "%other_name = OpString \"other_name\"\n";
6511
6512         fragments["pre_main"]   =
6513                 "OpLine %file_name 32 0\n"
6514                 "OpLine %file_name 32 32\n"
6515                 "OpLine %file_name 32 40\n"
6516                 "OpLine %other_name 32 40\n"
6517                 "OpLine %other_name 0 100\n"
6518                 "OpLine %other_name 0 4294967295\n"
6519                 "OpLine %other_name 4294967295 0\n"
6520                 "OpLine %other_name 32 40\n"
6521                 "OpLine %file_name 0 0\n"
6522                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6523                 "OpLine %file_name 1 0\n"
6524                 "%second_param1 = OpFunctionParameter %v4f32\n"
6525                 "OpLine %file_name 1 3\n"
6526                 "OpLine %file_name 1 2\n"
6527                 "%label_secondfunction = OpLabel\n"
6528                 "OpLine %file_name 0 2\n"
6529                 "OpReturnValue %second_param1\n"
6530                 "OpFunctionEnd\n"
6531                 "OpLine %file_name 0 2\n"
6532                 "OpLine %file_name 0 2\n";
6533
6534         fragments["testfun"]            =
6535                 // A %test_code function that returns its argument unchanged.
6536                 "OpLine %file_name 1 0\n"
6537                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6538                 "OpLine %file_name 16 330\n"
6539                 "%param1 = OpFunctionParameter %v4f32\n"
6540                 "OpLine %file_name 14 442\n"
6541                 "%label_testfun = OpLabel\n"
6542                 "OpLine %file_name 11 1024\n"
6543                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6544                 "OpLine %file_name 2 97\n"
6545                 "OpReturnValue %val1\n"
6546                 "OpFunctionEnd\n"
6547                 "OpLine %file_name 5 32\n";
6548
6549         for (size_t i = 0; i < problemStrings.size(); ++i)
6550         {
6551                 map<string, string> testFragments = fragments;
6552                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6553                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6554         }
6555
6556         return opLineTests.release();
6557 }
6558
6559 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6560 {
6561         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6562         RGBA                                                    colors[4];
6563
6564
6565         const char                                              functionStart[] =
6566                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6567                 "%param1 = OpFunctionParameter %v4f32\n"
6568                 "%lbl    = OpLabel\n";
6569
6570         const char                                              functionEnd[]   =
6571                 "OpReturnValue %transformed_param\n"
6572                 "OpFunctionEnd\n";
6573
6574         struct NameConstantsCode
6575         {
6576                 string name;
6577                 string constants;
6578                 string code;
6579         };
6580
6581         NameConstantsCode tests[] =
6582         {
6583                 {
6584                         "vec4",
6585                         "%cnull = OpConstantNull %v4f32\n",
6586                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6587                 },
6588                 {
6589                         "float",
6590                         "%cnull = OpConstantNull %f32\n",
6591                         "%vp = OpVariable %fp_v4f32 Function\n"
6592                         "%v  = OpLoad %v4f32 %vp\n"
6593                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6594                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6595                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6596                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6597                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6598                 },
6599                 {
6600                         "bool",
6601                         "%cnull             = OpConstantNull %bool\n",
6602                         "%v                 = OpVariable %fp_v4f32 Function\n"
6603                         "                     OpStore %v %param1\n"
6604                         "                     OpSelectionMerge %false_label None\n"
6605                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6606                         "%true_label        = OpLabel\n"
6607                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6608                         "                     OpBranch %false_label\n"
6609                         "%false_label       = OpLabel\n"
6610                         "%transformed_param = OpLoad %v4f32 %v\n"
6611                 },
6612                 {
6613                         "i32",
6614                         "%cnull             = OpConstantNull %i32\n",
6615                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6616                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6617                         "                     OpSelectionMerge %false_label None\n"
6618                         "                     OpBranchConditional %b %true_label %false_label\n"
6619                         "%true_label        = OpLabel\n"
6620                         "                     OpStore %v %param1\n"
6621                         "                     OpBranch %false_label\n"
6622                         "%false_label       = OpLabel\n"
6623                         "%transformed_param = OpLoad %v4f32 %v\n"
6624                 },
6625                 {
6626                         "struct",
6627                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6628                         "%fp_stype          = OpTypePointer Function %stype\n"
6629                         "%cnull             = OpConstantNull %stype\n",
6630                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6631                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6632                         "%f_val             = OpLoad %v4f32 %f\n"
6633                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6634                 },
6635                 {
6636                         "array",
6637                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6638                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6639                         "%cnull             = OpConstantNull %a4_v4f32\n",
6640                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6641                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6642                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6643                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6644                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6645                         "%f_val             = OpLoad %v4f32 %f\n"
6646                         "%f1_val            = OpLoad %v4f32 %f1\n"
6647                         "%f2_val            = OpLoad %v4f32 %f2\n"
6648                         "%f3_val            = OpLoad %v4f32 %f3\n"
6649                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6650                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6651                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6652                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6653                 },
6654                 {
6655                         "matrix",
6656                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6657                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6658                         // Our null matrix * any vector should result in a zero vector.
6659                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6660                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6661                 }
6662         };
6663
6664         getHalfColorsFullAlpha(colors);
6665
6666         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6667         {
6668                 map<string, string> fragments;
6669                 fragments["pre_main"] = tests[testNdx].constants;
6670                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6671                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6672         }
6673         return opConstantNullTests.release();
6674 }
6675 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6676 {
6677         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6678         RGBA                                                    inputColors[4];
6679         RGBA                                                    outputColors[4];
6680
6681
6682         const char                                              functionStart[]  =
6683                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6684                 "%param1 = OpFunctionParameter %v4f32\n"
6685                 "%lbl    = OpLabel\n";
6686
6687         const char                                              functionEnd[]           =
6688                 "OpReturnValue %transformed_param\n"
6689                 "OpFunctionEnd\n";
6690
6691         struct NameConstantsCode
6692         {
6693                 string name;
6694                 string constants;
6695                 string code;
6696         };
6697
6698         NameConstantsCode tests[] =
6699         {
6700                 {
6701                         "vec4",
6702
6703                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6704                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6705                 },
6706                 {
6707                         "struct",
6708
6709                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6710                         "%fp_stype          = OpTypePointer Function %stype\n"
6711                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6712                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6713                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6714                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6715
6716                         "%v                 = OpVariable %fp_stype Function %cval\n"
6717                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6718                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6719                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6720                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6721                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6722                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6723                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6724                 },
6725                 {
6726                         // [1|0|0|0.5] [x] = x + 0.5
6727                         // [0|1|0|0.5] [y] = y + 0.5
6728                         // [0|0|1|0.5] [z] = z + 0.5
6729                         // [0|0|0|1  ] [1] = 1
6730                         "matrix",
6731
6732                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6733                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6734                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6735                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6736                         "%v4f32_0_5_0_5_0_5_1 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_1\n"
6737                         "%cval                = OpConstantComposite %mat4x4_f32 %v4f32_1_0_0_0 %v4f32_0_1_0_0 %v4f32_0_0_1_0 %v4f32_0_5_0_5_0_5_1\n",
6738
6739                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6740                 },
6741                 {
6742                         "array",
6743
6744                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6745                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6746                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6747                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6748                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6749
6750                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6751                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6752                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6753                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6754                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6755                         "%f_val               = OpLoad %f32 %f\n"
6756                         "%f1_val              = OpLoad %f32 %f1\n"
6757                         "%f2_val              = OpLoad %f32 %f2\n"
6758                         "%f3_val              = OpLoad %f32 %f3\n"
6759                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6760                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6761                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6762                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6763                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6764                 },
6765                 {
6766                         //
6767                         // [
6768                         //   {
6769                         //      0.0,
6770                         //      [ 1.0, 1.0, 1.0, 1.0]
6771                         //   },
6772                         //   {
6773                         //      1.0,
6774                         //      [ 0.0, 0.5, 0.0, 0.0]
6775                         //   }, //     ^^^
6776                         //   {
6777                         //      0.0,
6778                         //      [ 1.0, 1.0, 1.0, 1.0]
6779                         //   }
6780                         // ]
6781                         "array_of_struct_of_array",
6782
6783                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6784                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6785                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6786                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6787                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6788                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6789                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6790                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6791                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6792                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6793
6794                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6795                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6796                         "%f_l                 = OpLoad %f32 %f\n"
6797                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6798                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6799                 }
6800         };
6801
6802         getHalfColorsFullAlpha(inputColors);
6803         outputColors[0] = RGBA(255, 255, 255, 255);
6804         outputColors[1] = RGBA(255, 127, 127, 255);
6805         outputColors[2] = RGBA(127, 255, 127, 255);
6806         outputColors[3] = RGBA(127, 127, 255, 255);
6807
6808         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6809         {
6810                 map<string, string> fragments;
6811                 fragments["pre_main"] = tests[testNdx].constants;
6812                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6813                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6814         }
6815         return opConstantCompositeTests.release();
6816 }
6817
6818 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6819 {
6820         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6821         RGBA                                                    inputColors[4];
6822         RGBA                                                    outputColors[4];
6823         map<string, string>                             fragments;
6824
6825         // vec4 test_code(vec4 param) {
6826         //   vec4 result = param;
6827         //   for (int i = 0; i < 4; ++i) {
6828         //     if (i == 0) result[i] = 0.;
6829         //     else        result[i] = 1. - result[i];
6830         //   }
6831         //   return result;
6832         // }
6833         const char                                              function[]                      =
6834                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6835                 "%param1    = OpFunctionParameter %v4f32\n"
6836                 "%lbl       = OpLabel\n"
6837                 "%iptr      = OpVariable %fp_i32 Function\n"
6838                 "%result    = OpVariable %fp_v4f32 Function\n"
6839                 "             OpStore %iptr %c_i32_0\n"
6840                 "             OpStore %result %param1\n"
6841                 "             OpBranch %loop\n"
6842
6843                 // Loop entry block.
6844                 "%loop      = OpLabel\n"
6845                 "%ival      = OpLoad %i32 %iptr\n"
6846                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6847                 "             OpLoopMerge %exit %if_entry None\n"
6848                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6849
6850                 // Merge block for loop.
6851                 "%exit      = OpLabel\n"
6852                 "%ret       = OpLoad %v4f32 %result\n"
6853                 "             OpReturnValue %ret\n"
6854
6855                 // If-statement entry block.
6856                 "%if_entry  = OpLabel\n"
6857                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6858                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6859                 "             OpSelectionMerge %if_exit None\n"
6860                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6861
6862                 // False branch for if-statement.
6863                 "%if_false  = OpLabel\n"
6864                 "%val       = OpLoad %f32 %loc\n"
6865                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6866                 "             OpStore %loc %sub\n"
6867                 "             OpBranch %if_exit\n"
6868
6869                 // Merge block for if-statement.
6870                 "%if_exit   = OpLabel\n"
6871                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6872                 "             OpStore %iptr %ival_next\n"
6873                 "             OpBranch %loop\n"
6874
6875                 // True branch for if-statement.
6876                 "%if_true   = OpLabel\n"
6877                 "             OpStore %loc %c_f32_0\n"
6878                 "             OpBranch %if_exit\n"
6879
6880                 "             OpFunctionEnd\n";
6881
6882         fragments["testfun"]    = function;
6883
6884         inputColors[0]                  = RGBA(127, 127, 127, 0);
6885         inputColors[1]                  = RGBA(127, 0,   0,   0);
6886         inputColors[2]                  = RGBA(0,   127, 0,   0);
6887         inputColors[3]                  = RGBA(0,   0,   127, 0);
6888
6889         outputColors[0]                 = RGBA(0, 128, 128, 255);
6890         outputColors[1]                 = RGBA(0, 255, 255, 255);
6891         outputColors[2]                 = RGBA(0, 128, 255, 255);
6892         outputColors[3]                 = RGBA(0, 255, 128, 255);
6893
6894         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6895
6896         return group.release();
6897 }
6898
6899 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6900 {
6901         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6902         RGBA                                                    inputColors[4];
6903         RGBA                                                    outputColors[4];
6904         map<string, string>                             fragments;
6905
6906         const char                                              typesAndConstants[]     =
6907                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6908                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6909                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6910                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6911
6912         // vec4 test_code(vec4 param) {
6913         //   vec4 result = param;
6914         //   for (int i = 0; i < 4; ++i) {
6915         //     switch (i) {
6916         //       case 0: result[i] += .2; break;
6917         //       case 1: result[i] += .6; break;
6918         //       case 2: result[i] += .4; break;
6919         //       case 3: result[i] += .8; break;
6920         //       default: break; // unreachable
6921         //     }
6922         //   }
6923         //   return result;
6924         // }
6925         const char                                              function[]                      =
6926                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6927                 "%param1    = OpFunctionParameter %v4f32\n"
6928                 "%lbl       = OpLabel\n"
6929                 "%iptr      = OpVariable %fp_i32 Function\n"
6930                 "%result    = OpVariable %fp_v4f32 Function\n"
6931                 "             OpStore %iptr %c_i32_0\n"
6932                 "             OpStore %result %param1\n"
6933                 "             OpBranch %loop\n"
6934
6935                 // Loop entry block.
6936                 "%loop      = OpLabel\n"
6937                 "%ival      = OpLoad %i32 %iptr\n"
6938                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6939                 "             OpLoopMerge %exit %switch_exit None\n"
6940                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6941
6942                 // Merge block for loop.
6943                 "%exit      = OpLabel\n"
6944                 "%ret       = OpLoad %v4f32 %result\n"
6945                 "             OpReturnValue %ret\n"
6946
6947                 // Switch-statement entry block.
6948                 "%switch_entry   = OpLabel\n"
6949                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6950                 "%val            = OpLoad %f32 %loc\n"
6951                 "                  OpSelectionMerge %switch_exit None\n"
6952                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6953
6954                 "%case2          = OpLabel\n"
6955                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6956                 "                  OpStore %loc %addp4\n"
6957                 "                  OpBranch %switch_exit\n"
6958
6959                 "%switch_default = OpLabel\n"
6960                 "                  OpUnreachable\n"
6961
6962                 "%case3          = OpLabel\n"
6963                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6964                 "                  OpStore %loc %addp8\n"
6965                 "                  OpBranch %switch_exit\n"
6966
6967                 "%case0          = OpLabel\n"
6968                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6969                 "                  OpStore %loc %addp2\n"
6970                 "                  OpBranch %switch_exit\n"
6971
6972                 // Merge block for switch-statement.
6973                 "%switch_exit    = OpLabel\n"
6974                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6975                 "                  OpStore %iptr %ival_next\n"
6976                 "                  OpBranch %loop\n"
6977
6978                 "%case1          = OpLabel\n"
6979                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6980                 "                  OpStore %loc %addp6\n"
6981                 "                  OpBranch %switch_exit\n"
6982
6983                 "                  OpFunctionEnd\n";
6984
6985         fragments["pre_main"]   = typesAndConstants;
6986         fragments["testfun"]    = function;
6987
6988         inputColors[0]                  = RGBA(127, 27,  127, 51);
6989         inputColors[1]                  = RGBA(127, 0,   0,   51);
6990         inputColors[2]                  = RGBA(0,   27,  0,   51);
6991         inputColors[3]                  = RGBA(0,   0,   127, 51);
6992
6993         outputColors[0]                 = RGBA(178, 180, 229, 255);
6994         outputColors[1]                 = RGBA(178, 153, 102, 255);
6995         outputColors[2]                 = RGBA(51,  180, 102, 255);
6996         outputColors[3]                 = RGBA(51,  153, 229, 255);
6997
6998         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6999
7000         return group.release();
7001 }
7002
7003 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
7004 {
7005         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
7006         RGBA                                                    inputColors[4];
7007         RGBA                                                    outputColors[4];
7008         map<string, string>                             fragments;
7009
7010         const char                                              decorations[]           =
7011                 "OpDecorate %array_group         ArrayStride 4\n"
7012                 "OpDecorate %struct_member_group Offset 0\n"
7013                 "%array_group         = OpDecorationGroup\n"
7014                 "%struct_member_group = OpDecorationGroup\n"
7015
7016                 "OpDecorate %group1 RelaxedPrecision\n"
7017                 "OpDecorate %group3 RelaxedPrecision\n"
7018                 "OpDecorate %group3 Invariant\n"
7019                 "OpDecorate %group3 Restrict\n"
7020                 "%group0 = OpDecorationGroup\n"
7021                 "%group1 = OpDecorationGroup\n"
7022                 "%group3 = OpDecorationGroup\n";
7023
7024         const char                                              typesAndConstants[]     =
7025                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
7026                 "%struct1   = OpTypeStruct %a3f32\n"
7027                 "%struct2   = OpTypeStruct %a3f32\n"
7028                 "%fp_struct1 = OpTypePointer Function %struct1\n"
7029                 "%fp_struct2 = OpTypePointer Function %struct2\n"
7030                 "%c_f32_2    = OpConstant %f32 2.\n"
7031                 "%c_f32_n2   = OpConstant %f32 -2.\n"
7032
7033                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
7034                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
7035                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
7036                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
7037
7038         const char                                              function[]                      =
7039                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7040                 "%param     = OpFunctionParameter %v4f32\n"
7041                 "%entry     = OpLabel\n"
7042                 "%result    = OpVariable %fp_v4f32 Function\n"
7043                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
7044                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
7045                 "             OpStore %result %param\n"
7046                 "             OpStore %v_struct1 %c_struct1\n"
7047                 "             OpStore %v_struct2 %c_struct2\n"
7048                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
7049                 "%val1      = OpLoad %f32 %ptr1\n"
7050                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
7051                 "%val2      = OpLoad %f32 %ptr2\n"
7052                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
7053                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7054                 "%val       = OpLoad %f32 %ptr\n"
7055                 "%addresult = OpFAdd %f32 %addvalues %val\n"
7056                 "             OpStore %ptr %addresult\n"
7057                 "%ret       = OpLoad %v4f32 %result\n"
7058                 "             OpReturnValue %ret\n"
7059                 "             OpFunctionEnd\n";
7060
7061         struct CaseNameDecoration
7062         {
7063                 string name;
7064                 string decoration;
7065         };
7066
7067         CaseNameDecoration tests[] =
7068         {
7069                 {
7070                         "same_decoration_group_on_multiple_types",
7071                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
7072                 },
7073                 {
7074                         "empty_decoration_group",
7075                         "OpGroupDecorate %group0      %a3f32\n"
7076                         "OpGroupDecorate %group0      %result\n"
7077                 },
7078                 {
7079                         "one_element_decoration_group",
7080                         "OpGroupDecorate %array_group %a3f32\n"
7081                 },
7082                 {
7083                         "multiple_elements_decoration_group",
7084                         "OpGroupDecorate %group3      %v_struct1\n"
7085                 },
7086                 {
7087                         "multiple_decoration_groups_on_same_variable",
7088                         "OpGroupDecorate %group0      %v_struct2\n"
7089                         "OpGroupDecorate %group1      %v_struct2\n"
7090                         "OpGroupDecorate %group3      %v_struct2\n"
7091                 },
7092                 {
7093                         "same_decoration_group_multiple_times",
7094                         "OpGroupDecorate %group1      %addvalues\n"
7095                         "OpGroupDecorate %group1      %addvalues\n"
7096                         "OpGroupDecorate %group1      %addvalues\n"
7097                 },
7098
7099         };
7100
7101         getHalfColorsFullAlpha(inputColors);
7102         getHalfColorsFullAlpha(outputColors);
7103
7104         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
7105         {
7106                 fragments["decoration"] = decorations + tests[idx].decoration;
7107                 fragments["pre_main"]   = typesAndConstants;
7108                 fragments["testfun"]    = function;
7109
7110                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
7111         }
7112
7113         return group.release();
7114 }
7115
7116 struct SpecConstantTwoIntGraphicsCase
7117 {
7118         const char*             caseName;
7119         const char*             scDefinition0;
7120         const char*             scDefinition1;
7121         const char*             scResultType;
7122         const char*             scOperation;
7123         deInt32                 scActualValue0;
7124         deInt32                 scActualValue1;
7125         const char*             resultOperation;
7126         RGBA                    expectedColors[4];
7127         deInt32                 scActualValueLength;
7128
7129                                         SpecConstantTwoIntGraphicsCase (const char*             name,
7130                                                                                                         const char*             definition0,
7131                                                                                                         const char*             definition1,
7132                                                                                                         const char*             resultType,
7133                                                                                                         const char*             operation,
7134                                                                                                         const deInt32   value0,
7135                                                                                                         const deInt32   value1,
7136                                                                                                         const char*             resultOp,
7137                                                                                                         const RGBA              (&output)[4],
7138                                                                                                         const deInt32   valueLength = sizeof(deInt32))
7139                                                 : caseName                              (name)
7140                                                 , scDefinition0                 (definition0)
7141                                                 , scDefinition1                 (definition1)
7142                                                 , scResultType                  (resultType)
7143                                                 , scOperation                   (operation)
7144                                                 , scActualValue0                (value0)
7145                                                 , scActualValue1                (value1)
7146                                                 , resultOperation               (resultOp)
7147                                                 , scActualValueLength   (valueLength)
7148         {
7149                 expectedColors[0] = output[0];
7150                 expectedColors[1] = output[1];
7151                 expectedColors[2] = output[2];
7152                 expectedColors[3] = output[3];
7153         }
7154 };
7155
7156 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7157 {
7158         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7159         vector<SpecConstantTwoIntGraphicsCase>  cases;
7160         RGBA                                                    inputColors[4];
7161         RGBA                                                    outputColors0[4];
7162         RGBA                                                    outputColors1[4];
7163         RGBA                                                    outputColors2[4];
7164
7165         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7166
7167         const char      decorations1[]                  =
7168                 "OpDecorate %sc_0  SpecId 0\n"
7169                 "OpDecorate %sc_1  SpecId 1\n";
7170
7171         const char      typesAndConstants1[]    =
7172                 "${OPTYPE_DEFINITIONS:opt}"
7173                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7174                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7175                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7176
7177         const char      function1[]                             =
7178                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7179                 "%param     = OpFunctionParameter %v4f32\n"
7180                 "%label     = OpLabel\n"
7181                 "%result    = OpVariable %fp_v4f32 Function\n"
7182                 "${TYPE_CONVERT:opt}"
7183                 "             OpStore %result %param\n"
7184                 "%gen       = ${GEN_RESULT}\n"
7185                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7186                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7187                 "%val       = OpLoad %f32 %loc\n"
7188                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7189                 "             OpStore %loc %add\n"
7190                 "%ret       = OpLoad %v4f32 %result\n"
7191                 "             OpReturnValue %ret\n"
7192                 "             OpFunctionEnd\n";
7193
7194         inputColors[0] = RGBA(127, 127, 127, 255);
7195         inputColors[1] = RGBA(127, 0,   0,   255);
7196         inputColors[2] = RGBA(0,   127, 0,   255);
7197         inputColors[3] = RGBA(0,   0,   127, 255);
7198
7199         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7200         outputColors0[0] = RGBA(255, 127, 127, 255);
7201         outputColors0[1] = RGBA(255, 0,   0,   255);
7202         outputColors0[2] = RGBA(128, 127, 0,   255);
7203         outputColors0[3] = RGBA(128, 0,   127, 255);
7204
7205         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7206         outputColors1[0] = RGBA(127, 255, 127, 255);
7207         outputColors1[1] = RGBA(127, 128, 0,   255);
7208         outputColors1[2] = RGBA(0,   255, 0,   255);
7209         outputColors1[3] = RGBA(0,   128, 127, 255);
7210
7211         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7212         outputColors2[0] = RGBA(127, 127, 255, 255);
7213         outputColors2[1] = RGBA(127, 0,   128, 255);
7214         outputColors2[2] = RGBA(0,   127, 128, 255);
7215         outputColors2[3] = RGBA(0,   0,   255, 255);
7216
7217         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7218         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7219         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7220         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7221
7222         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7223         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7224         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7225         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7226         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7227         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7228         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7229         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7230         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7231         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7232         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7233         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7234         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7235         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7236         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7237         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7238         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7239         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7240         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7241         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7242         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7243         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7244         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7245         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7246         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7247         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7248         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7249         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7250         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7251         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7252         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7253         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7254         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7255         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7256         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7257         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7258         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7259
7260         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7261         {
7262                 map<string, string>                     specializations;
7263                 map<string, string>                     fragments;
7264                 SpecConstants                           specConstants;
7265                 PushConstants                           noPushConstants;
7266                 GraphicsResources                       noResources;
7267                 GraphicsInterfaces                      noInterfaces;
7268                 vector<string>                          extensions;
7269                 VulkanFeatures                          requiredFeatures;
7270
7271                 // Special SPIR-V code for SConvert-case
7272                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7273                 {
7274                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7275                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7276                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7277                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7278                 }
7279
7280                 // Special SPIR-V code for FConvert-case
7281                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7282                 {
7283                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7284                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7285                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7286                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7287                 }
7288
7289                 // Special SPIR-V code for FConvert-case for 16-bit floats
7290                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7291                 {
7292                         extensions.push_back("VK_KHR_shader_float16_int8");
7293                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7294                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7295                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7296                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7297                 }
7298
7299                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7300                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7301                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7302                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7303                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7304
7305                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7306                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7307                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7308
7309                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7310                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7311
7312                 createTestsForAllStages(
7313                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7314                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7315         }
7316
7317         const char      decorations2[]                  =
7318                 "OpDecorate %sc_0  SpecId 0\n"
7319                 "OpDecorate %sc_1  SpecId 1\n"
7320                 "OpDecorate %sc_2  SpecId 2\n";
7321
7322         const char      typesAndConstants2[]    =
7323                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7324                 "%vec3_undef  = OpUndef %v3i32\n"
7325
7326                 "%sc_0        = OpSpecConstant %i32 0\n"
7327                 "%sc_1        = OpSpecConstant %i32 0\n"
7328                 "%sc_2        = OpSpecConstant %i32 0\n"
7329                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7330                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7331                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7332                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7333                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7334                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7335                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7336                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7337                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7338                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7339                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7340                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7341                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7342
7343         const char      function2[]                             =
7344                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7345                 "%param     = OpFunctionParameter %v4f32\n"
7346                 "%label     = OpLabel\n"
7347                 "%result    = OpVariable %fp_v4f32 Function\n"
7348                 "             OpStore %result %param\n"
7349                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7350                 "%val       = OpLoad %f32 %loc\n"
7351                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7352                 "             OpStore %loc %add\n"
7353                 "%ret       = OpLoad %v4f32 %result\n"
7354                 "             OpReturnValue %ret\n"
7355                 "             OpFunctionEnd\n";
7356
7357         map<string, string>     fragments;
7358         SpecConstants           specConstants;
7359
7360         fragments["decoration"] = decorations2;
7361         fragments["pre_main"]   = typesAndConstants2;
7362         fragments["testfun"]    = function2;
7363
7364         specConstants.append<deInt32>(56789);
7365         specConstants.append<deInt32>(-2);
7366         specConstants.append<deInt32>(56788);
7367
7368         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7369
7370         return group.release();
7371 }
7372
7373 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7374 {
7375         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7376         RGBA                                                    inputColors[4];
7377         RGBA                                                    outputColors1[4];
7378         RGBA                                                    outputColors2[4];
7379         RGBA                                                    outputColors3[4];
7380         RGBA                                                    outputColors4[4];
7381         map<string, string>                             fragments1;
7382         map<string, string>                             fragments2;
7383         map<string, string>                             fragments3;
7384         map<string, string>                             fragments4;
7385         std::vector<std::string>                extensions4;
7386         GraphicsResources                               resources4;
7387         VulkanFeatures                                  vulkanFeatures4;
7388
7389         const char      typesAndConstants1[]    =
7390                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7391                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7392                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7393                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7394
7395         // vec4 test_code(vec4 param) {
7396         //   vec4 result = param;
7397         //   for (int i = 0; i < 4; ++i) {
7398         //     float operand;
7399         //     switch (i) {
7400         //       case 0: operand = .2; break;
7401         //       case 1: operand = .5; break;
7402         //       case 2: operand = .4; break;
7403         //       case 3: operand = .0; break;
7404         //       default: break; // unreachable
7405         //     }
7406         //     result[i] += operand;
7407         //   }
7408         //   return result;
7409         // }
7410         const char      function1[]                             =
7411                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7412                 "%param1    = OpFunctionParameter %v4f32\n"
7413                 "%lbl       = OpLabel\n"
7414                 "%iptr      = OpVariable %fp_i32 Function\n"
7415                 "%result    = OpVariable %fp_v4f32 Function\n"
7416                 "             OpStore %iptr %c_i32_0\n"
7417                 "             OpStore %result %param1\n"
7418                 "             OpBranch %loop\n"
7419
7420                 "%loop      = OpLabel\n"
7421                 "%ival      = OpLoad %i32 %iptr\n"
7422                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7423                 "             OpLoopMerge %exit %phi None\n"
7424                 "             OpBranchConditional %lt_4 %entry %exit\n"
7425
7426                 "%entry     = OpLabel\n"
7427                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7428                 "%val       = OpLoad %f32 %loc\n"
7429                 "             OpSelectionMerge %phi None\n"
7430                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7431
7432                 "%case0     = OpLabel\n"
7433                 "             OpBranch %phi\n"
7434                 "%case1     = OpLabel\n"
7435                 "             OpBranch %phi\n"
7436                 "%case2     = OpLabel\n"
7437                 "             OpBranch %phi\n"
7438                 "%case3     = OpLabel\n"
7439                 "             OpBranch %phi\n"
7440
7441                 "%default   = OpLabel\n"
7442                 "             OpUnreachable\n"
7443
7444                 "%phi       = OpLabel\n"
7445                 "%operand   = OpPhi %f32 %c_f32_p4 %case2 %c_f32_p5 %case1 %c_f32_p2 %case0 %c_f32_0 %case3\n" // not in the order of blocks
7446                 "%add       = OpFAdd %f32 %val %operand\n"
7447                 "             OpStore %loc %add\n"
7448                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7449                 "             OpStore %iptr %ival_next\n"
7450                 "             OpBranch %loop\n"
7451
7452                 "%exit      = OpLabel\n"
7453                 "%ret       = OpLoad %v4f32 %result\n"
7454                 "             OpReturnValue %ret\n"
7455
7456                 "             OpFunctionEnd\n";
7457
7458         fragments1["pre_main"]  = typesAndConstants1;
7459         fragments1["testfun"]   = function1;
7460
7461         getHalfColorsFullAlpha(inputColors);
7462
7463         outputColors1[0]                = RGBA(178, 255, 229, 255);
7464         outputColors1[1]                = RGBA(178, 127, 102, 255);
7465         outputColors1[2]                = RGBA(51,  255, 102, 255);
7466         outputColors1[3]                = RGBA(51,  127, 229, 255);
7467
7468         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7469
7470         const char      typesAndConstants2[]    =
7471                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7472
7473         // Add .4 to the second element of the given parameter.
7474         const char      function2[]                             =
7475                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7476                 "%param     = OpFunctionParameter %v4f32\n"
7477                 "%entry     = OpLabel\n"
7478                 "%result    = OpVariable %fp_v4f32 Function\n"
7479                 "             OpStore %result %param\n"
7480                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7481                 "%val       = OpLoad %f32 %loc\n"
7482                 "             OpBranch %phi\n"
7483
7484                 "%phi        = OpLabel\n"
7485                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7486                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7487                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7488                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7489                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7490                 "              OpLoopMerge %exit %phi None\n"
7491                 "              OpBranchConditional %still_loop %phi %exit\n"
7492
7493                 "%exit       = OpLabel\n"
7494                 "              OpStore %loc %accum\n"
7495                 "%ret        = OpLoad %v4f32 %result\n"
7496                 "              OpReturnValue %ret\n"
7497
7498                 "              OpFunctionEnd\n";
7499
7500         fragments2["pre_main"]  = typesAndConstants2;
7501         fragments2["testfun"]   = function2;
7502
7503         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7504         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7505         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7506         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7507
7508         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7509
7510         const char      typesAndConstants3[]    =
7511                 "%true      = OpConstantTrue %bool\n"
7512                 "%false     = OpConstantFalse %bool\n"
7513                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7514
7515         // Swap the second and the third element of the given parameter.
7516         const char      function3[]                             =
7517                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7518                 "%param     = OpFunctionParameter %v4f32\n"
7519                 "%entry     = OpLabel\n"
7520                 "%result    = OpVariable %fp_v4f32 Function\n"
7521                 "             OpStore %result %param\n"
7522                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7523                 "%a_init    = OpLoad %f32 %a_loc\n"
7524                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7525                 "%b_init    = OpLoad %f32 %b_loc\n"
7526                 "             OpBranch %phi\n"
7527
7528                 "%phi        = OpLabel\n"
7529                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7530                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7531                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7532                 "              OpLoopMerge %exit %phi None\n"
7533                 "              OpBranchConditional %still_loop %phi %exit\n"
7534
7535                 "%exit       = OpLabel\n"
7536                 "              OpStore %a_loc %a_next\n"
7537                 "              OpStore %b_loc %b_next\n"
7538                 "%ret        = OpLoad %v4f32 %result\n"
7539                 "              OpReturnValue %ret\n"
7540
7541                 "              OpFunctionEnd\n";
7542
7543         fragments3["pre_main"]  = typesAndConstants3;
7544         fragments3["testfun"]   = function3;
7545
7546         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7547         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7548         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7549         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7550
7551         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7552
7553         const char      typesAndConstants4[]    =
7554                 "%f16        = OpTypeFloat 16\n"
7555                 "%v4f16      = OpTypeVector %f16 4\n"
7556                 "%fp_f16     = OpTypePointer Function %f16\n"
7557                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7558                 "%true       = OpConstantTrue %bool\n"
7559                 "%false      = OpConstantFalse %bool\n"
7560                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7561
7562         // Swap the second and the third element of the given parameter.
7563         const char      function4[]                             =
7564                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7565                 "%param      = OpFunctionParameter %v4f32\n"
7566                 "%entry      = OpLabel\n"
7567                 "%result     = OpVariable %fp_v4f16 Function\n"
7568                 "%param16    = OpFConvert %v4f16 %param\n"
7569                 "              OpStore %result %param16\n"
7570                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7571                 "%a_init     = OpLoad %f16 %a_loc\n"
7572                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7573                 "%b_init     = OpLoad %f16 %b_loc\n"
7574                 "              OpBranch %phi\n"
7575
7576                 "%phi        = OpLabel\n"
7577                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7578                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7579                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7580                 "              OpLoopMerge %exit %phi None\n"
7581                 "              OpBranchConditional %still_loop %phi %exit\n"
7582
7583                 "%exit       = OpLabel\n"
7584                 "              OpStore %a_loc %a_next\n"
7585                 "              OpStore %b_loc %b_next\n"
7586                 "%ret16      = OpLoad %v4f16 %result\n"
7587                 "%ret        = OpFConvert %v4f32 %ret16\n"
7588                 "              OpReturnValue %ret\n"
7589
7590                 "              OpFunctionEnd\n";
7591
7592         fragments4["pre_main"]          = typesAndConstants4;
7593         fragments4["testfun"]           = function4;
7594         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
7595         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7596
7597         extensions4.push_back("VK_KHR_16bit_storage");
7598         extensions4.push_back("VK_KHR_shader_float16_int8");
7599
7600         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7601         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7602
7603         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7604         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7605         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7606         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7607
7608         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7609
7610         return group.release();
7611 }
7612
7613 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7614 {
7615         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7616         RGBA                                                    inputColors[4];
7617         RGBA                                                    outputColors[4];
7618
7619         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7620         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7621         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7622         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7623         const char                                              constantsAndTypes[]      =
7624                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7625                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7626                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7627                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7628                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7629
7630         const char                                              function[]       =
7631                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7632                 "%param          = OpFunctionParameter %v4f32\n"
7633                 "%label          = OpLabel\n"
7634                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7635                 "%var2           = OpVariable %fp_f32 Function\n"
7636                 "%red            = OpCompositeExtract %f32 %param 0\n"
7637                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7638                 "                  OpStore %var2 %plus_red\n"
7639                 "%val1           = OpLoad %f32 %var1\n"
7640                 "%val2           = OpLoad %f32 %var2\n"
7641                 "%mul            = OpFMul %f32 %val1 %val2\n"
7642                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7643                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7644                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7645                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7646                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7647                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7648                 "                  OpReturnValue %ret\n"
7649                 "                  OpFunctionEnd\n";
7650
7651         struct CaseNameDecoration
7652         {
7653                 string name;
7654                 string decoration;
7655         };
7656
7657
7658         CaseNameDecoration tests[] = {
7659                 {"multiplication",      "OpDecorate %mul NoContraction"},
7660                 {"addition",            "OpDecorate %add NoContraction"},
7661                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7662         };
7663
7664         getHalfColorsFullAlpha(inputColors);
7665
7666         for (deUint8 idx = 0; idx < 4; ++idx)
7667         {
7668                 inputColors[idx].setRed(0);
7669                 outputColors[idx] = RGBA(0, 0, 0, 255);
7670         }
7671
7672         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7673         {
7674                 map<string, string> fragments;
7675
7676                 fragments["decoration"] = tests[testNdx].decoration;
7677                 fragments["pre_main"] = constantsAndTypes;
7678                 fragments["testfun"] = function;
7679
7680                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7681         }
7682
7683         return group.release();
7684 }
7685
7686 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7687 {
7688         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7689         RGBA                                                    colors[4];
7690
7691         const char                                              constantsAndTypes[]      =
7692                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7693                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7694                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7695                 "%fp_stype          = OpTypePointer Function %stype\n";
7696
7697         const char                                              function[]       =
7698                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7699                 "%param1            = OpFunctionParameter %v4f32\n"
7700                 "%lbl               = OpLabel\n"
7701                 "%v1                = OpVariable %fp_v4f32 Function\n"
7702                 "%v2                = OpVariable %fp_a2f32 Function\n"
7703                 "%v3                = OpVariable %fp_f32 Function\n"
7704                 "%v                 = OpVariable %fp_stype Function\n"
7705                 "%vv                = OpVariable %fp_stype Function\n"
7706                 "%vvv               = OpVariable %fp_f32 Function\n"
7707
7708                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7709                 "                     OpStore %v2 %c_a2f32_1\n"
7710                 "                     OpStore %v3 %c_f32_1\n"
7711
7712                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7713                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7714                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7715                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7716                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7717                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7718
7719                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7720                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7721                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7722
7723                 "                    OpCopyMemory %vv %v ${access_type}\n"
7724                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7725
7726                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7727                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7728                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7729
7730                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7731                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7732                 "                    OpReturnValue %ret2\n"
7733                 "                    OpFunctionEnd\n";
7734
7735         struct NameMemoryAccess
7736         {
7737                 string name;
7738                 string accessType;
7739         };
7740
7741
7742         NameMemoryAccess tests[] =
7743         {
7744                 { "none", "" },
7745                 { "volatile", "Volatile" },
7746                 { "aligned",  "Aligned 1" },
7747                 { "volatile_aligned",  "Volatile|Aligned 1" },
7748                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7749                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7750                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7751         };
7752
7753         getHalfColorsFullAlpha(colors);
7754
7755         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7756         {
7757                 map<string, string> fragments;
7758                 map<string, string> memoryAccess;
7759                 memoryAccess["access_type"] = tests[testNdx].accessType;
7760
7761                 fragments["pre_main"] = constantsAndTypes;
7762                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7763                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7764         }
7765         return memoryAccessTests.release();
7766 }
7767 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7768 {
7769         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7770         RGBA                                                            defaultColors[4];
7771         map<string, string>                                     fragments;
7772         getDefaultColors(defaultColors);
7773
7774         // First, simple cases that don't do anything with the OpUndef result.
7775         struct NameCodePair { string name, decl, type; };
7776         const NameCodePair tests[] =
7777         {
7778                 {"bool", "", "%bool"},
7779                 {"vec2uint32", "", "%v2u32"},
7780                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7781                 {"sampler", "%type = OpTypeSampler", "%type"},
7782                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7783                 {"pointer", "", "%fp_i32"},
7784                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7785                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7786                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7787         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7788         {
7789                 fragments["undef_type"] = tests[testNdx].type;
7790                 fragments["testfun"] = StringTemplate(
7791                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7792                         "%param1 = OpFunctionParameter %v4f32\n"
7793                         "%label_testfun = OpLabel\n"
7794                         "%undef = OpUndef ${undef_type}\n"
7795                         "OpReturnValue %param1\n"
7796                         "OpFunctionEnd\n").specialize(fragments);
7797                 fragments["pre_main"] = tests[testNdx].decl;
7798                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7799         }
7800         fragments.clear();
7801
7802         fragments["testfun"] =
7803                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7804                 "%param1 = OpFunctionParameter %v4f32\n"
7805                 "%label_testfun = OpLabel\n"
7806                 "%undef = OpUndef %f32\n"
7807                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7808                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7809                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7810                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7811                 "%b = OpFAdd %f32 %a %actually_zero\n"
7812                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7813                 "OpReturnValue %ret\n"
7814                 "OpFunctionEnd\n";
7815
7816         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7817
7818         fragments["testfun"] =
7819                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7820                 "%param1 = OpFunctionParameter %v4f32\n"
7821                 "%label_testfun = OpLabel\n"
7822                 "%undef = OpUndef %i32\n"
7823                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7824                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7825                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7826                 "OpReturnValue %ret\n"
7827                 "OpFunctionEnd\n";
7828
7829         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7830
7831         fragments["testfun"] =
7832                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7833                 "%param1 = OpFunctionParameter %v4f32\n"
7834                 "%label_testfun = OpLabel\n"
7835                 "%undef = OpUndef %u32\n"
7836                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7837                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7838                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7839                 "OpReturnValue %ret\n"
7840                 "OpFunctionEnd\n";
7841
7842         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7843
7844         fragments["testfun"] =
7845                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7846                 "%param1 = OpFunctionParameter %v4f32\n"
7847                 "%label_testfun = OpLabel\n"
7848                 "%undef = OpUndef %v4f32\n"
7849                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7850                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7851                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7852                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7853                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7854                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7855                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7856                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7857                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7858                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7859                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7860                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7861                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7862                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7863                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7864                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7865                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7866                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7867                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7868                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7869                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7870                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7871                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7872                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7873                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7874                 "OpReturnValue %ret\n"
7875                 "OpFunctionEnd\n";
7876
7877         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7878
7879         fragments["pre_main"] =
7880                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7881         fragments["testfun"] =
7882                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7883                 "%param1 = OpFunctionParameter %v4f32\n"
7884                 "%label_testfun = OpLabel\n"
7885                 "%undef = OpUndef %m2x2f32\n"
7886                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7887                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7888                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7889                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7890                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7891                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7892                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7893                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7894                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7895                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7896                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7897                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7898                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7899                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7900                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7901                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7902                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7903                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7904                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7905                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7906                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7907                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7908                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7909                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7910                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7911                 "OpReturnValue %ret\n"
7912                 "OpFunctionEnd\n";
7913
7914         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7915
7916         return opUndefTests.release();
7917 }
7918
7919 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7920 {
7921         const RGBA              inputColors[4]          =
7922         {
7923                 RGBA(0,         0,              0,              255),
7924                 RGBA(0,         0,              255,    255),
7925                 RGBA(0,         255,    0,              255),
7926                 RGBA(0,         255,    255,    255)
7927         };
7928
7929         const RGBA              expectedColors[4]       =
7930         {
7931                 RGBA(255,        0,              0,              255),
7932                 RGBA(255,        0,              0,              255),
7933                 RGBA(255,        0,              0,              255),
7934                 RGBA(255,        0,              0,              255)
7935         };
7936
7937         const struct SingleFP16Possibility
7938         {
7939                 const char* name;
7940                 const char* constant;  // Value to assign to %test_constant.
7941                 float           valueAsFloat;
7942                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7943         }                               tests[]                         =
7944         {
7945                 {
7946                         "negative",
7947                         "-0x1.3p1\n",
7948                         -constructNormalizedFloat(1, 0x300000),
7949                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7950                 }, // -19
7951                 {
7952                         "positive",
7953                         "0x1.0p7\n",
7954                         constructNormalizedFloat(7, 0x000000),
7955                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7956                 },  // +128
7957                 // SPIR-V requires that OpQuantizeToF16 flushes
7958                 // any numbers that would end up denormalized in F16 to zero.
7959                 {
7960                         "denorm",
7961                         "0x0.0006p-126\n",
7962                         std::ldexp(1.5f, -140),
7963                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7964                 },  // denorm
7965                 {
7966                         "negative_denorm",
7967                         "-0x0.0006p-126\n",
7968                         -std::ldexp(1.5f, -140),
7969                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7970                 }, // -denorm
7971                 {
7972                         "too_small",
7973                         "0x1.0p-16\n",
7974                         std::ldexp(1.0f, -16),
7975                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7976                 },     // too small positive
7977                 {
7978                         "negative_too_small",
7979                         "-0x1.0p-32\n",
7980                         -std::ldexp(1.0f, -32),
7981                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7982                 },      // too small negative
7983                 {
7984                         "negative_inf",
7985                         "-0x1.0p128\n",
7986                         -std::ldexp(1.0f, 128),
7987
7988                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7989                         "%inf = OpIsInf %bool %c\n"
7990                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7991                 },     // -inf to -inf
7992                 {
7993                         "inf",
7994                         "0x1.0p128\n",
7995                         std::ldexp(1.0f, 128),
7996
7997                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7998                         "%inf = OpIsInf %bool %c\n"
7999                         "%cond = OpLogicalAnd %bool %gz %inf\n"
8000                 },     // +inf to +inf
8001                 {
8002                         "round_to_negative_inf",
8003                         "-0x1.0p32\n",
8004                         -std::ldexp(1.0f, 32),
8005
8006                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
8007                         "%inf = OpIsInf %bool %c\n"
8008                         "%cond = OpLogicalAnd %bool %gz %inf\n"
8009                 },     // round to -inf
8010                 {
8011                         "round_to_inf",
8012                         "0x1.0p16\n",
8013                         std::ldexp(1.0f, 16),
8014
8015                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
8016                         "%inf = OpIsInf %bool %c\n"
8017                         "%cond = OpLogicalAnd %bool %gz %inf\n"
8018                 },     // round to +inf
8019                 {
8020                         "nan",
8021                         "0x1.1p128\n",
8022                         std::numeric_limits<float>::quiet_NaN(),
8023
8024                         // Test for any NaN value, as NaNs are not preserved
8025                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8026                         "%cond = OpIsNan %bool %direct_quant\n"
8027                 }, // nan
8028                 {
8029                         "negative_nan",
8030                         "-0x1.0001p128\n",
8031                         std::numeric_limits<float>::quiet_NaN(),
8032
8033                         // Test for any NaN value, as NaNs are not preserved
8034                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8035                         "%cond = OpIsNan %bool %direct_quant\n"
8036                 } // -nan
8037         };
8038         const char*             constants                       =
8039                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
8040
8041         StringTemplate  function                        (
8042                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8043                 "%param1        = OpFunctionParameter %v4f32\n"
8044                 "%label_testfun = OpLabel\n"
8045                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8046                 "%b             = OpFAdd %f32 %test_constant %a\n"
8047                 "%c             = OpQuantizeToF16 %f32 %b\n"
8048                 "${condition}\n"
8049                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8050                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8051                 "                 OpReturnValue %retval\n"
8052                 "OpFunctionEnd\n"
8053         );
8054
8055         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
8056         const char*             specConstants           =
8057                         "%test_constant = OpSpecConstant %f32 0.\n"
8058                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
8059
8060         StringTemplate  specConstantFunction(
8061                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8062                 "%param1        = OpFunctionParameter %v4f32\n"
8063                 "%label_testfun = OpLabel\n"
8064                 "${condition}\n"
8065                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8066                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8067                 "                 OpReturnValue %retval\n"
8068                 "OpFunctionEnd\n"
8069         );
8070
8071         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8072         {
8073                 map<string, string>                                                             codeSpecialization;
8074                 map<string, string>                                                             fragments;
8075                 codeSpecialization["condition"]                                 = tests[idx].condition;
8076                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
8077                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
8078                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8079         }
8080
8081         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8082         {
8083                 map<string, string>                                                             codeSpecialization;
8084                 map<string, string>                                                             fragments;
8085                 SpecConstants                                                                   passConstants;
8086
8087                 codeSpecialization["condition"]                                 = tests[idx].condition;
8088                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
8089                 fragments["decoration"]                                                 = specDecorations;
8090                 fragments["pre_main"]                                                   = specConstants;
8091
8092                 passConstants.append<float>(tests[idx].valueAsFloat);
8093
8094                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8095         }
8096 }
8097
8098 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
8099 {
8100         RGBA inputColors[4] =  {
8101                 RGBA(0,         0,              0,              255),
8102                 RGBA(0,         0,              255,    255),
8103                 RGBA(0,         255,    0,              255),
8104                 RGBA(0,         255,    255,    255)
8105         };
8106
8107         RGBA expectedColors[4] =
8108         {
8109                 RGBA(255,        0,              0,              255),
8110                 RGBA(255,        0,              0,              255),
8111                 RGBA(255,        0,              0,              255),
8112                 RGBA(255,        0,              0,              255)
8113         };
8114
8115         struct DualFP16Possibility
8116         {
8117                 const char* name;
8118                 const char* input;
8119                 float           inputAsFloat;
8120                 const char* possibleOutput1;
8121                 const char* possibleOutput2;
8122         } tests[] = {
8123                 {
8124                         "positive_round_up_or_round_down",
8125                         "0x1.3003p8",
8126                         constructNormalizedFloat(8, 0x300300),
8127                         "0x1.304p8",
8128                         "0x1.3p8"
8129                 },
8130                 {
8131                         "negative_round_up_or_round_down",
8132                         "-0x1.6008p-7",
8133                         -constructNormalizedFloat(-7, 0x600800),
8134                         "-0x1.6p-7",
8135                         "-0x1.604p-7"
8136                 },
8137                 {
8138                         "carry_bit",
8139                         "0x1.01ep2",
8140                         constructNormalizedFloat(2, 0x01e000),
8141                         "0x1.01cp2",
8142                         "0x1.02p2"
8143                 },
8144                 {
8145                         "carry_to_exponent",
8146                         "0x1.ffep1",
8147                         constructNormalizedFloat(1, 0xffe000),
8148                         "0x1.ffcp1",
8149                         "0x1.0p2"
8150                 },
8151         };
8152         StringTemplate constants (
8153                 "%input_const = OpConstant %f32 ${input}\n"
8154                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8155                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8156                 );
8157
8158         StringTemplate specConstants (
8159                 "%input_const = OpSpecConstant %f32 0.\n"
8160                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8161                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8162         );
8163
8164         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8165
8166         const char* function  =
8167                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8168                 "%param1        = OpFunctionParameter %v4f32\n"
8169                 "%label_testfun = OpLabel\n"
8170                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8171                 // For the purposes of this test we assume that 0.f will always get
8172                 // faithfully passed through the pipeline stages.
8173                 "%b             = OpFAdd %f32 %input_const %a\n"
8174                 "%c             = OpQuantizeToF16 %f32 %b\n"
8175                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8176                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8177                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8178                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8179                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8180                 "                 OpReturnValue %retval\n"
8181                 "OpFunctionEnd\n";
8182
8183         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8184                 map<string, string>                                                                     fragments;
8185                 map<string, string>                                                                     constantSpecialization;
8186
8187                 constantSpecialization["input"]                                         = tests[idx].input;
8188                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8189                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8190                 fragments["testfun"]                                                            = function;
8191                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8192                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8193         }
8194
8195         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8196                 map<string, string>                                                                     fragments;
8197                 map<string, string>                                                                     constantSpecialization;
8198                 SpecConstants                                                                           passConstants;
8199
8200                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8201                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8202                 fragments["testfun"]                                                            = function;
8203                 fragments["decoration"]                                                         = specDecorations;
8204                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8205
8206                 passConstants.append<float>(tests[idx].inputAsFloat);
8207
8208                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8209         }
8210 }
8211
8212 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8213 {
8214         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8215         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8216         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8217         return opQuantizeTests.release();
8218 }
8219
8220 struct ShaderPermutation
8221 {
8222         deUint8 vertexPermutation;
8223         deUint8 geometryPermutation;
8224         deUint8 tesscPermutation;
8225         deUint8 tessePermutation;
8226         deUint8 fragmentPermutation;
8227 };
8228
8229 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8230 {
8231         ShaderPermutation       permutation =
8232         {
8233                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8234                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8235                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8236                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8237                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8238         };
8239         return permutation;
8240 }
8241
8242 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8243 {
8244         RGBA                                                            defaultColors[4];
8245         RGBA                                                            invertedColors[4];
8246         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8247
8248         getDefaultColors(defaultColors);
8249         getInvertedDefaultColors(invertedColors);
8250
8251         // Combined module tests
8252         {
8253                 // Shader stages: vertex and fragment
8254                 {
8255                         const ShaderElement combinedPipeline[]  =
8256                         {
8257                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8258                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8259                         };
8260
8261                         addFunctionCaseWithPrograms<InstanceContext>(
8262                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8263                                 createInstanceContext(combinedPipeline, map<string, string>()));
8264                 }
8265
8266                 // Shader stages: vertex, geometry and fragment
8267                 {
8268                         const ShaderElement combinedPipeline[]  =
8269                         {
8270                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8271                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8272                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8273                         };
8274
8275                         addFunctionCaseWithPrograms<InstanceContext>(
8276                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8277                                 createInstanceContext(combinedPipeline, map<string, string>()));
8278                 }
8279
8280                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8281                 {
8282                         const ShaderElement combinedPipeline[]  =
8283                         {
8284                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8285                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8286                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8287                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8288                         };
8289
8290                         addFunctionCaseWithPrograms<InstanceContext>(
8291                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8292                                 createInstanceContext(combinedPipeline, map<string, string>()));
8293                 }
8294
8295                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8296                 {
8297                         const ShaderElement combinedPipeline[]  =
8298                         {
8299                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8300                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8301                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8302                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8303                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8304                         };
8305
8306                         addFunctionCaseWithPrograms<InstanceContext>(
8307                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8308                                 createInstanceContext(combinedPipeline, map<string, string>()));
8309                 }
8310         }
8311
8312         const char* numbers[] =
8313         {
8314                 "1", "2"
8315         };
8316
8317         for (deInt8 idx = 0; idx < 32; ++idx)
8318         {
8319                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8320                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8321                 const ShaderElement                     pipeline[]              =
8322                 {
8323                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8324                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8325                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8326                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8327                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8328                 };
8329
8330                 // If there are an even number of swaps, then it should be no-op.
8331                 // If there are an odd number, the color should be flipped.
8332                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8333                 {
8334                         addFunctionCaseWithPrograms<InstanceContext>(
8335                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8336                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8337                 }
8338                 else
8339                 {
8340                         addFunctionCaseWithPrograms<InstanceContext>(
8341                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8342                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8343                 }
8344         }
8345         return moduleTests.release();
8346 }
8347
8348 std::string getUnusedVarTestNamePiece(const std::string& prefix, ShaderTask task)
8349 {
8350         switch (task)
8351         {
8352                 case SHADER_TASK_NONE:                  return "";
8353                 case SHADER_TASK_NORMAL:                return prefix + "_normal";
8354                 case SHADER_TASK_UNUSED_VAR:    return prefix + "_unused_var";
8355                 case SHADER_TASK_UNUSED_FUNC:   return prefix + "_unused_func";
8356                 default:                                                DE_ASSERT(DE_FALSE);
8357         }
8358         // unreachable
8359         return "";
8360 }
8361
8362 std::string getShaderTaskIndexName(ShaderTaskIndex index)
8363 {
8364         switch (index)
8365         {
8366         case SHADER_TASK_INDEX_VERTEX:                  return "vertex";
8367         case SHADER_TASK_INDEX_GEOMETRY:                return "geom";
8368         case SHADER_TASK_INDEX_TESS_CONTROL:    return "tessc";
8369         case SHADER_TASK_INDEX_TESS_EVAL:               return "tesse";
8370         case SHADER_TASK_INDEX_FRAGMENT:                return "frag";
8371         default:                                                                DE_ASSERT(DE_FALSE);
8372         }
8373         // unreachable
8374         return "";
8375 }
8376
8377 std::string getUnusedVarTestName(const ShaderTaskArray& shaderTasks, const VariableLocation& location)
8378 {
8379         std::string testName = location.toString();
8380
8381         for (size_t i = 0; i < DE_LENGTH_OF_ARRAY(shaderTasks); ++i)
8382         {
8383                 if (shaderTasks[i] != SHADER_TASK_NONE)
8384                 {
8385                         testName += "_" + getUnusedVarTestNamePiece(getShaderTaskIndexName((ShaderTaskIndex)i), shaderTasks[i]);
8386                 }
8387         }
8388
8389         return testName;
8390 }
8391
8392 tcu::TestCaseGroup* createUnusedVariableTests(tcu::TestContext& testCtx)
8393 {
8394         de::MovePtr<tcu::TestCaseGroup>         moduleTests                             (new tcu::TestCaseGroup(testCtx, "unused_variables", "Graphics shaders with unused variables"));
8395
8396         ShaderTaskArray                                         shaderCombinations[]    =
8397         {
8398                 // Vertex                                       Geometry                                        Tess. Control                           Tess. Evaluation                        Fragment
8399                 { SHADER_TASK_UNUSED_VAR,       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8400                 { SHADER_TASK_UNUSED_FUNC,      SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8401                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR  },
8402                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC },
8403                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8404                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8405                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8406                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8407                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL      },
8408                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL      }
8409         };
8410
8411         const VariableLocation                          testLocations[] =
8412         {
8413                 // Set          Binding
8414                 { 0,            5                       },
8415                 { 5,            5                       },
8416         };
8417
8418         for (size_t combNdx = 0; combNdx < DE_LENGTH_OF_ARRAY(shaderCombinations); ++combNdx)
8419         {
8420                 for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
8421                 {
8422                         const ShaderTaskArray&  shaderTasks             = shaderCombinations[combNdx];
8423                         const VariableLocation& location                = testLocations[locationNdx];
8424                         std::string                             testName                = getUnusedVarTestName(shaderTasks, location);
8425
8426                         addFunctionCaseWithPrograms<UnusedVariableContext>(
8427                                 moduleTests.get(), testName, "", createUnusedVariableModules, runAndVerifyUnusedVariablePipeline,
8428                                 createUnusedVariableContext(shaderTasks, location));
8429                 }
8430         }
8431
8432         return moduleTests.release();
8433 }
8434
8435 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8436 {
8437         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8438         RGBA defaultColors[4];
8439         getDefaultColors(defaultColors);
8440         map<string, string> fragments;
8441         fragments["pre_main"] =
8442                 "%c_f32_5 = OpConstant %f32 5.\n";
8443
8444         // A loop with a single block. The Continue Target is the loop block
8445         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8446         // -- the "continue construct" forms the entire loop.
8447         fragments["testfun"] =
8448                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8449                 "%param1 = OpFunctionParameter %v4f32\n"
8450
8451                 "%entry = OpLabel\n"
8452                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8453                 "OpBranch %loop\n"
8454
8455                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8456                 "%loop = OpLabel\n"
8457                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8458                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8459                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8460                 "%val = OpFAdd %f32 %val1 %delta\n"
8461                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8462                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8463                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8464                 "OpLoopMerge %exit %loop None\n"
8465                 "OpBranchConditional %again %loop %exit\n"
8466
8467                 "%exit = OpLabel\n"
8468                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8469                 "OpReturnValue %result\n"
8470
8471                 "OpFunctionEnd\n";
8472
8473         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8474
8475         // Body comprised of multiple basic blocks.
8476         const StringTemplate multiBlock(
8477                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8478                 "%param1 = OpFunctionParameter %v4f32\n"
8479
8480                 "%entry = OpLabel\n"
8481                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8482                 "OpBranch %loop\n"
8483
8484                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8485                 "%loop = OpLabel\n"
8486                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8487                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8488                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8489                 // There are several possibilities for the Continue Target below.  Each
8490                 // will be specialized into a separate test case.
8491                 "OpLoopMerge %exit ${continue_target} None\n"
8492                 "OpBranch %if\n"
8493
8494                 "%if = OpLabel\n"
8495                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8496                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8497                 "OpSelectionMerge %gather DontFlatten\n"
8498                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8499
8500                 "%odd = OpLabel\n"
8501                 "OpBranch %gather\n"
8502
8503                 "%even = OpLabel\n"
8504                 "OpBranch %gather\n"
8505
8506                 "%gather = OpLabel\n"
8507                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8508                 "%val = OpFAdd %f32 %val1 %delta\n"
8509                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8510                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8511                 "OpBranchConditional %again %loop %exit\n"
8512
8513                 "%exit = OpLabel\n"
8514                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8515                 "OpReturnValue %result\n"
8516
8517                 "OpFunctionEnd\n");
8518
8519         map<string, string> continue_target;
8520
8521         // The Continue Target is the loop block itself.
8522         continue_target["continue_target"] = "%loop";
8523         fragments["testfun"] = multiBlock.specialize(continue_target);
8524         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8525
8526         // The Continue Target is at the end of the loop.
8527         continue_target["continue_target"] = "%gather";
8528         fragments["testfun"] = multiBlock.specialize(continue_target);
8529         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8530
8531         // A loop with continue statement.
8532         fragments["testfun"] =
8533                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8534                 "%param1 = OpFunctionParameter %v4f32\n"
8535
8536                 "%entry = OpLabel\n"
8537                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8538                 "OpBranch %loop\n"
8539
8540                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8541                 "%loop = OpLabel\n"
8542                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8543                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8544                 "OpLoopMerge %exit %continue None\n"
8545                 "OpBranch %if\n"
8546
8547                 "%if = OpLabel\n"
8548                 ";skip if %count==2\n"
8549                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8550                 "OpSelectionMerge %continue DontFlatten\n"
8551                 "OpBranchConditional %eq2 %continue %body\n"
8552
8553                 "%body = OpLabel\n"
8554                 "%fcount = OpConvertSToF %f32 %count\n"
8555                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8556                 "OpBranch %continue\n"
8557
8558                 "%continue = OpLabel\n"
8559                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8560                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8561                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8562                 "OpBranchConditional %again %loop %exit\n"
8563
8564                 "%exit = OpLabel\n"
8565                 "%same = OpFSub %f32 %val %c_f32_8\n"
8566                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8567                 "OpReturnValue %result\n"
8568                 "OpFunctionEnd\n";
8569         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8570
8571         // A loop with break.
8572         fragments["testfun"] =
8573                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8574                 "%param1 = OpFunctionParameter %v4f32\n"
8575
8576                 "%entry = OpLabel\n"
8577                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8578                 "%dot = OpDot %f32 %param1 %param1\n"
8579                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8580                 "%zero = OpConvertFToU %u32 %div\n"
8581                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8582                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8583                 "OpBranch %loop\n"
8584
8585                 ";adds 4 and 3 to %val0 (exits early)\n"
8586                 "%loop = OpLabel\n"
8587                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8588                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8589                 "OpLoopMerge %exit %continue None\n"
8590                 "OpBranch %if\n"
8591
8592                 "%if = OpLabel\n"
8593                 ";end loop if %count==%two\n"
8594                 "%above2 = OpSGreaterThan %bool %count %two\n"
8595                 "OpSelectionMerge %continue DontFlatten\n"
8596                 "OpBranchConditional %above2 %body %exit\n"
8597
8598                 "%body = OpLabel\n"
8599                 "%fcount = OpConvertSToF %f32 %count\n"
8600                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8601                 "OpBranch %continue\n"
8602
8603                 "%continue = OpLabel\n"
8604                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8605                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8606                 "OpBranchConditional %again %loop %exit\n"
8607
8608                 "%exit = OpLabel\n"
8609                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8610                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8611                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8612                 "OpReturnValue %result\n"
8613                 "OpFunctionEnd\n";
8614         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8615
8616         // A loop with return.
8617         fragments["testfun"] =
8618                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8619                 "%param1 = OpFunctionParameter %v4f32\n"
8620
8621                 "%entry = OpLabel\n"
8622                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8623                 "%dot = OpDot %f32 %param1 %param1\n"
8624                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8625                 "%zero = OpConvertFToU %u32 %div\n"
8626                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8627                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8628                 "OpBranch %loop\n"
8629
8630                 ";returns early without modifying %param1\n"
8631                 "%loop = OpLabel\n"
8632                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8633                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8634                 "OpLoopMerge %exit %continue None\n"
8635                 "OpBranch %if\n"
8636
8637                 "%if = OpLabel\n"
8638                 ";return if %count==%two\n"
8639                 "%above2 = OpSGreaterThan %bool %count %two\n"
8640                 "OpSelectionMerge %continue DontFlatten\n"
8641                 "OpBranchConditional %above2 %body %early_exit\n"
8642
8643                 "%early_exit = OpLabel\n"
8644                 "OpReturnValue %param1\n"
8645
8646                 "%body = OpLabel\n"
8647                 "%fcount = OpConvertSToF %f32 %count\n"
8648                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8649                 "OpBranch %continue\n"
8650
8651                 "%continue = OpLabel\n"
8652                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8653                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8654                 "OpBranchConditional %again %loop %exit\n"
8655
8656                 "%exit = OpLabel\n"
8657                 ";should never get here, so return an incorrect result\n"
8658                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8659                 "OpReturnValue %result\n"
8660                 "OpFunctionEnd\n";
8661         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8662
8663         // Continue inside a switch block to break to enclosing loop's merge block.
8664         // Matches roughly the following GLSL code:
8665         // for (; keep_going; keep_going = false)
8666         // {
8667         //     switch (int(param1.x))
8668         //     {
8669         //         case 0: continue;
8670         //         case 1: continue;
8671         //         default: continue;
8672         //     }
8673         //     dead code: modify return value to invalid result.
8674         // }
8675         fragments["pre_main"] =
8676                 "%fp_bool = OpTypePointer Function %bool\n"
8677                 "%true = OpConstantTrue %bool\n"
8678                 "%false = OpConstantFalse %bool\n";
8679
8680         fragments["testfun"] =
8681                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8682                 "%param1 = OpFunctionParameter %v4f32\n"
8683
8684                 "%entry = OpLabel\n"
8685                 "%keep_going = OpVariable %fp_bool Function\n"
8686                 "%val_ptr = OpVariable %fp_f32 Function\n"
8687                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8688                 "OpStore %keep_going %true\n"
8689                 "OpBranch %forloop_begin\n"
8690
8691                 "%forloop_begin = OpLabel\n"
8692                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8693                 "OpBranch %forloop\n"
8694
8695                 "%forloop = OpLabel\n"
8696                 "%for_condition = OpLoad %bool %keep_going\n"
8697                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8698
8699                 "%forloop_body = OpLabel\n"
8700                 "OpStore %val_ptr %param1_x\n"
8701                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8702
8703                 "OpSelectionMerge %switch_merge None\n"
8704                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8705                 "%case_0 = OpLabel\n"
8706                 "OpBranch %forloop_continue\n"
8707                 "%case_1 = OpLabel\n"
8708                 "OpBranch %forloop_continue\n"
8709                 "%default = OpLabel\n"
8710                 "OpBranch %forloop_continue\n"
8711                 "%switch_merge = OpLabel\n"
8712                 ";should never get here, so change the return value to invalid result\n"
8713                 "OpStore %val_ptr %c_f32_1\n"
8714                 "OpBranch %forloop_continue\n"
8715
8716                 "%forloop_continue = OpLabel\n"
8717                 "OpStore %keep_going %false\n"
8718                 "OpBranch %forloop_begin\n"
8719                 "%forloop_merge = OpLabel\n"
8720
8721                 "%val = OpLoad %f32 %val_ptr\n"
8722                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8723                 "OpReturnValue %result\n"
8724                 "OpFunctionEnd\n";
8725         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8726
8727         return testGroup.release();
8728 }
8729
8730 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8731 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8732 {
8733         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8734         map<string, string> fragments;
8735
8736         // A barrier inside a function body.
8737         fragments["pre_main"] =
8738                 "%Workgroup = OpConstant %i32 2\n"
8739                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8740         fragments["testfun"] =
8741                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8742                 "%param1 = OpFunctionParameter %v4f32\n"
8743                 "%label_testfun = OpLabel\n"
8744                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8745                 "OpReturnValue %param1\n"
8746                 "OpFunctionEnd\n";
8747         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8748
8749         // Common setup code for the following tests.
8750         fragments["pre_main"] =
8751                 "%Workgroup = OpConstant %i32 2\n"
8752                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8753                 "%c_f32_5 = OpConstant %f32 5.\n";
8754         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8755                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8756                 "%param1 = OpFunctionParameter %v4f32\n"
8757                 "%entry = OpLabel\n"
8758                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8759                 "%dot = OpDot %f32 %param1 %param1\n"
8760                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8761                 "%zero = OpConvertFToU %u32 %div\n";
8762
8763         // Barriers inside OpSwitch branches.
8764         fragments["testfun"] =
8765                 setupPercentZero +
8766                 "OpSelectionMerge %switch_exit None\n"
8767                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8768
8769                 "%case1 = OpLabel\n"
8770                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8771                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8772                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8773                 "OpBranch %switch_exit\n"
8774
8775                 "%switch_default = OpLabel\n"
8776                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8777                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8778                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8779                 "OpBranch %switch_exit\n"
8780
8781                 "%case0 = OpLabel\n"
8782                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8783                 "OpBranch %switch_exit\n"
8784
8785                 "%switch_exit = OpLabel\n"
8786                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8787                 "OpReturnValue %ret\n"
8788                 "OpFunctionEnd\n";
8789         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8790
8791         // Barriers inside if-then-else.
8792         fragments["testfun"] =
8793                 setupPercentZero +
8794                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8795                 "OpSelectionMerge %exit DontFlatten\n"
8796                 "OpBranchConditional %eq0 %then %else\n"
8797
8798                 "%else = OpLabel\n"
8799                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8800                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8801                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8802                 "OpBranch %exit\n"
8803
8804                 "%then = OpLabel\n"
8805                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8806                 "OpBranch %exit\n"
8807                 "%exit = OpLabel\n"
8808                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8809                 "OpReturnValue %ret\n"
8810                 "OpFunctionEnd\n";
8811         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8812
8813         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8814         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8815         fragments["testfun"] =
8816                 setupPercentZero +
8817                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8818                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8819                 "OpSelectionMerge %exit DontFlatten\n"
8820                 "OpBranchConditional %thread0 %then %else\n"
8821
8822                 "%else = OpLabel\n"
8823                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8824                 "OpBranch %exit\n"
8825
8826                 "%then = OpLabel\n"
8827                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8828                 "OpBranch %exit\n"
8829
8830                 "%exit = OpLabel\n"
8831                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8832                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8833                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8834                 "OpReturnValue %ret\n"
8835                 "OpFunctionEnd\n";
8836         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8837
8838         // A barrier inside a loop.
8839         fragments["pre_main"] =
8840                 "%Workgroup = OpConstant %i32 2\n"
8841                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8842                 "%c_f32_10 = OpConstant %f32 10.\n";
8843         fragments["testfun"] =
8844                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8845                 "%param1 = OpFunctionParameter %v4f32\n"
8846                 "%entry = OpLabel\n"
8847                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8848                 "OpBranch %loop\n"
8849
8850                 ";adds 4, 3, 2, and 1 to %val0\n"
8851                 "%loop = OpLabel\n"
8852                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8853                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8854                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8855                 "%fcount = OpConvertSToF %f32 %count\n"
8856                 "%val = OpFAdd %f32 %val1 %fcount\n"
8857                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8858                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8859                 "OpLoopMerge %exit %loop None\n"
8860                 "OpBranchConditional %again %loop %exit\n"
8861
8862                 "%exit = OpLabel\n"
8863                 "%same = OpFSub %f32 %val %c_f32_10\n"
8864                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8865                 "OpReturnValue %ret\n"
8866                 "OpFunctionEnd\n";
8867         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8868
8869         return testGroup.release();
8870 }
8871
8872 // Test for the OpFRem instruction.
8873 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8874 {
8875         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8876         map<string, string>                                     fragments;
8877         RGBA                                                            inputColors[4];
8878         RGBA                                                            outputColors[4];
8879
8880         fragments["pre_main"]                            =
8881                 "%c_f32_3 = OpConstant %f32 3.0\n"
8882                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8883                 "%c_f32_4 = OpConstant %f32 4.0\n"
8884                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8885                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8886                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8887                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8888
8889         // The test does the following.
8890         // vec4 result = (param1 * 8.0) - 4.0;
8891         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8892         fragments["testfun"]                             =
8893                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8894                 "%param1 = OpFunctionParameter %v4f32\n"
8895                 "%label_testfun = OpLabel\n"
8896                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8897                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8898                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8899                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8900                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8901                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8902                 "OpReturnValue %xy_0_1\n"
8903                 "OpFunctionEnd\n";
8904
8905
8906         inputColors[0]          = RGBA(16,      16,             0, 255);
8907         inputColors[1]          = RGBA(232, 232,        0, 255);
8908         inputColors[2]          = RGBA(232, 16,         0, 255);
8909         inputColors[3]          = RGBA(16,      232,    0, 255);
8910
8911         outputColors[0]         = RGBA(64,      64,             0, 255);
8912         outputColors[1]         = RGBA(255, 255,        0, 255);
8913         outputColors[2]         = RGBA(255, 64,         0, 255);
8914         outputColors[3]         = RGBA(64,      255,    0, 255);
8915
8916         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8917         return testGroup.release();
8918 }
8919
8920 // Test for the OpSRem instruction.
8921 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8922 {
8923         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8924         map<string, string>                                     fragments;
8925
8926         fragments["pre_main"]                            =
8927                 "%c_f32_255 = OpConstant %f32 255.0\n"
8928                 "%c_i32_128 = OpConstant %i32 128\n"
8929                 "%c_i32_255 = OpConstant %i32 255\n"
8930                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8931                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8932                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8933
8934         // The test does the following.
8935         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8936         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8937         // return float(result + 128) / 255.0;
8938         fragments["testfun"]                             =
8939                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8940                 "%param1 = OpFunctionParameter %v4f32\n"
8941                 "%label_testfun = OpLabel\n"
8942                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8943                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8944                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8945                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8946                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8947                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8948                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8949                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8950                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8951                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8952                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8953                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8954                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8955                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8956                 "OpReturnValue %float_out\n"
8957                 "OpFunctionEnd\n";
8958
8959         const struct CaseParams
8960         {
8961                 const char*             name;
8962                 const char*             failMessageTemplate;    // customized status message
8963                 qpTestResult    failResult;                             // override status on failure
8964                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8965                 int                             results[4][3];                  // four (x, y, z) vectors of results
8966         } cases[] =
8967         {
8968                 {
8969                         "positive",
8970                         "${reason}",
8971                         QP_TEST_RESULT_FAIL,
8972                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8973                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8974                 },
8975                 {
8976                         "all",
8977                         "Inconsistent results, but within specification: ${reason}",
8978                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8979                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8980                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8981                 },
8982         };
8983         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8984
8985         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8986         {
8987                 const CaseParams&       params                  = cases[caseNdx];
8988                 RGBA                            inputColors[4];
8989                 RGBA                            outputColors[4];
8990
8991                 for (int i = 0; i < 4; ++i)
8992                 {
8993                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8994                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8995                 }
8996
8997                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8998         }
8999
9000         return testGroup.release();
9001 }
9002
9003 // Test for the OpSMod instruction.
9004 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
9005 {
9006         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
9007         map<string, string>                                     fragments;
9008
9009         fragments["pre_main"]                            =
9010                 "%c_f32_255 = OpConstant %f32 255.0\n"
9011                 "%c_i32_128 = OpConstant %i32 128\n"
9012                 "%c_i32_255 = OpConstant %i32 255\n"
9013                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
9014                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
9015                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
9016
9017         // The test does the following.
9018         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
9019         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
9020         // return float(result + 128) / 255.0;
9021         fragments["testfun"]                             =
9022                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9023                 "%param1 = OpFunctionParameter %v4f32\n"
9024                 "%label_testfun = OpLabel\n"
9025                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
9026                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
9027                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
9028                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
9029                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
9030                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
9031                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
9032                 "%x_out = OpSMod %i32 %x_in %y_in\n"
9033                 "%y_out = OpSMod %i32 %y_in %z_in\n"
9034                 "%z_out = OpSMod %i32 %z_in %x_in\n"
9035                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
9036                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
9037                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
9038                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
9039                 "OpReturnValue %float_out\n"
9040                 "OpFunctionEnd\n";
9041
9042         const struct CaseParams
9043         {
9044                 const char*             name;
9045                 const char*             failMessageTemplate;    // customized status message
9046                 qpTestResult    failResult;                             // override status on failure
9047                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
9048                 int                             results[4][3];                  // four (x, y, z) vectors of results
9049         } cases[] =
9050         {
9051                 {
9052                         "positive",
9053                         "${reason}",
9054                         QP_TEST_RESULT_FAIL,
9055                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
9056                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
9057                 },
9058                 {
9059                         "all",
9060                         "Inconsistent results, but within specification: ${reason}",
9061                         negFailResult,                                                                                                                          // negative operands, not required by the spec
9062                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
9063                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
9064                 },
9065         };
9066         // If either operand is negative the result is undefined. Some implementations may still return correct values.
9067
9068         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
9069         {
9070                 const CaseParams&       params                  = cases[caseNdx];
9071                 RGBA                            inputColors[4];
9072                 RGBA                            outputColors[4];
9073
9074                 for (int i = 0; i < 4; ++i)
9075                 {
9076                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
9077                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
9078                 }
9079
9080                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
9081         }
9082         return testGroup.release();
9083 }
9084
9085 enum ConversionDataType
9086 {
9087         DATA_TYPE_SIGNED_8,
9088         DATA_TYPE_SIGNED_16,
9089         DATA_TYPE_SIGNED_32,
9090         DATA_TYPE_SIGNED_64,
9091         DATA_TYPE_UNSIGNED_8,
9092         DATA_TYPE_UNSIGNED_16,
9093         DATA_TYPE_UNSIGNED_32,
9094         DATA_TYPE_UNSIGNED_64,
9095         DATA_TYPE_FLOAT_16,
9096         DATA_TYPE_FLOAT_32,
9097         DATA_TYPE_FLOAT_64,
9098         DATA_TYPE_VEC2_SIGNED_16,
9099         DATA_TYPE_VEC2_SIGNED_32
9100 };
9101
9102 const string getBitWidthStr (ConversionDataType type)
9103 {
9104         switch (type)
9105         {
9106                 case DATA_TYPE_SIGNED_8:
9107                 case DATA_TYPE_UNSIGNED_8:
9108                         return "8";
9109
9110                 case DATA_TYPE_SIGNED_16:
9111                 case DATA_TYPE_UNSIGNED_16:
9112                 case DATA_TYPE_FLOAT_16:
9113                         return "16";
9114
9115                 case DATA_TYPE_SIGNED_32:
9116                 case DATA_TYPE_UNSIGNED_32:
9117                 case DATA_TYPE_FLOAT_32:
9118                 case DATA_TYPE_VEC2_SIGNED_16:
9119                         return "32";
9120
9121                 case DATA_TYPE_SIGNED_64:
9122                 case DATA_TYPE_UNSIGNED_64:
9123                 case DATA_TYPE_FLOAT_64:
9124                 case DATA_TYPE_VEC2_SIGNED_32:
9125                         return "64";
9126
9127                 default:
9128                         DE_ASSERT(false);
9129         }
9130         return "";
9131 }
9132
9133 const string getByteWidthStr (ConversionDataType type)
9134 {
9135         switch (type)
9136         {
9137                 case DATA_TYPE_SIGNED_8:
9138                 case DATA_TYPE_UNSIGNED_8:
9139                         return "1";
9140
9141                 case DATA_TYPE_SIGNED_16:
9142                 case DATA_TYPE_UNSIGNED_16:
9143                 case DATA_TYPE_FLOAT_16:
9144                         return "2";
9145
9146                 case DATA_TYPE_SIGNED_32:
9147                 case DATA_TYPE_UNSIGNED_32:
9148                 case DATA_TYPE_FLOAT_32:
9149                 case DATA_TYPE_VEC2_SIGNED_16:
9150                         return "4";
9151
9152                 case DATA_TYPE_SIGNED_64:
9153                 case DATA_TYPE_UNSIGNED_64:
9154                 case DATA_TYPE_FLOAT_64:
9155                 case DATA_TYPE_VEC2_SIGNED_32:
9156                         return "8";
9157
9158                 default:
9159                         DE_ASSERT(false);
9160         }
9161         return "";
9162 }
9163
9164 bool isSigned (ConversionDataType type)
9165 {
9166         switch (type)
9167         {
9168                 case DATA_TYPE_SIGNED_8:
9169                 case DATA_TYPE_SIGNED_16:
9170                 case DATA_TYPE_SIGNED_32:
9171                 case DATA_TYPE_SIGNED_64:
9172                 case DATA_TYPE_FLOAT_16:
9173                 case DATA_TYPE_FLOAT_32:
9174                 case DATA_TYPE_FLOAT_64:
9175                 case DATA_TYPE_VEC2_SIGNED_16:
9176                 case DATA_TYPE_VEC2_SIGNED_32:
9177                         return true;
9178
9179                 case DATA_TYPE_UNSIGNED_8:
9180                 case DATA_TYPE_UNSIGNED_16:
9181                 case DATA_TYPE_UNSIGNED_32:
9182                 case DATA_TYPE_UNSIGNED_64:
9183                         return false;
9184
9185                 default:
9186                         DE_ASSERT(false);
9187         }
9188         return false;
9189 }
9190
9191 bool isInt (ConversionDataType type)
9192 {
9193         switch (type)
9194         {
9195                 case DATA_TYPE_SIGNED_8:
9196                 case DATA_TYPE_SIGNED_16:
9197                 case DATA_TYPE_SIGNED_32:
9198                 case DATA_TYPE_SIGNED_64:
9199                 case DATA_TYPE_UNSIGNED_8:
9200                 case DATA_TYPE_UNSIGNED_16:
9201                 case DATA_TYPE_UNSIGNED_32:
9202                 case DATA_TYPE_UNSIGNED_64:
9203                         return true;
9204
9205                 case DATA_TYPE_FLOAT_16:
9206                 case DATA_TYPE_FLOAT_32:
9207                 case DATA_TYPE_FLOAT_64:
9208                 case DATA_TYPE_VEC2_SIGNED_16:
9209                 case DATA_TYPE_VEC2_SIGNED_32:
9210                         return false;
9211
9212                 default:
9213                         DE_ASSERT(false);
9214         }
9215         return false;
9216 }
9217
9218 bool isFloat (ConversionDataType type)
9219 {
9220         switch (type)
9221         {
9222                 case DATA_TYPE_SIGNED_8:
9223                 case DATA_TYPE_SIGNED_16:
9224                 case DATA_TYPE_SIGNED_32:
9225                 case DATA_TYPE_SIGNED_64:
9226                 case DATA_TYPE_UNSIGNED_8:
9227                 case DATA_TYPE_UNSIGNED_16:
9228                 case DATA_TYPE_UNSIGNED_32:
9229                 case DATA_TYPE_UNSIGNED_64:
9230                 case DATA_TYPE_VEC2_SIGNED_16:
9231                 case DATA_TYPE_VEC2_SIGNED_32:
9232                         return false;
9233
9234                 case DATA_TYPE_FLOAT_16:
9235                 case DATA_TYPE_FLOAT_32:
9236                 case DATA_TYPE_FLOAT_64:
9237                         return true;
9238
9239                 default:
9240                         DE_ASSERT(false);
9241         }
9242         return false;
9243 }
9244
9245 const string getTypeName (ConversionDataType type)
9246 {
9247         string prefix = isSigned(type) ? "" : "u";
9248
9249         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9250         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9251         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9252         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9253         else                                                                            DE_ASSERT(false);
9254
9255         return "";
9256 }
9257
9258 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9259 {
9260         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9261
9262         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9263 }
9264
9265 const string getAsmTypeName (ConversionDataType type)
9266 {
9267         string prefix;
9268
9269         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9270         else if (isFloat(type))                                         prefix = "f";
9271         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9272         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9273         else                                                                            DE_ASSERT(false);
9274
9275         return prefix + getBitWidthStr(type);
9276 }
9277
9278 template<typename T>
9279 BufferSp getSpecializedBuffer (deInt64 number)
9280 {
9281         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9282 }
9283
9284 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9285 {
9286         switch (type)
9287         {
9288                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9289                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9290                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9291                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9292                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9293                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9294                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9295                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9296                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9297                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9298                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9299                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9300                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9301
9302                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9303         }
9304 }
9305
9306 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9307 {
9308         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9309                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9310 }
9311
9312 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9313 {
9314         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9315                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9316                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9317 }
9318
9319 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9320 {
9321         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9322                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9323                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9324 }
9325
9326 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9327 {
9328         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9329                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9330 }
9331
9332 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9333 {
9334         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9335 }
9336
9337 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9338 {
9339         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9340 }
9341
9342 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9343 {
9344         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9345 }
9346
9347 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9348 {
9349         if (usesInt16(from, to) && !usesInt32(from, to))
9350                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9351
9352         if (usesInt64(from, to))
9353                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9354
9355         if (usesFloat64(from, to))
9356                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9357
9358         if (usesInt16(from, to) || usesFloat16(from, to))
9359         {
9360                 extensions.push_back("VK_KHR_16bit_storage");
9361                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9362         }
9363
9364         if (usesFloat16(from, to) || usesInt8(from, to))
9365         {
9366                 extensions.push_back("VK_KHR_shader_float16_int8");
9367
9368                 if (usesFloat16(from, to))
9369                 {
9370                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9371                 }
9372
9373                 if (usesInt8(from, to))
9374                 {
9375                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9376
9377                         extensions.push_back("VK_KHR_8bit_storage");
9378                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9379                 }
9380         }
9381 }
9382
9383 struct ConvertCase
9384 {
9385         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9386         : m_fromType            (from)
9387         , m_toType                      (to)
9388         , m_name                        (getTestName(from, to, suffix))
9389         , m_inputBuffer         (getBuffer(from, number))
9390         {
9391                 string caps;
9392                 string decl;
9393                 string exts;
9394
9395                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9396                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9397
9398                 if (separateOutput)
9399                         m_outputBuffer = getBuffer(to, outputNumber);
9400                 else
9401                         m_outputBuffer = getBuffer(to, number);
9402
9403                 if (usesInt8(from, to))
9404                 {
9405                         bool requiresInt8Capability = true;
9406                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9407                         {
9408                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9409                                 if (usesInt32(from, to))
9410                                         requiresInt8Capability = false;
9411                         }
9412
9413                         caps += "OpCapability StorageBuffer8BitAccess\n";
9414                         if (requiresInt8Capability)
9415                                 caps += "OpCapability Int8\n";
9416
9417                         decl += "%i8         = OpTypeInt 8 1\n"
9418                                         "%u8         = OpTypeInt 8 0\n";
9419                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9420                 }
9421
9422                 if (usesInt16(from, to))
9423                 {
9424                         bool requiresInt16Capability = true;
9425
9426                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9427                         {
9428                                 // Width-only conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9429                                 if (usesInt32(from, to) || usesFloat32(from, to))
9430                                         requiresInt16Capability = false;
9431                         }
9432
9433                         decl += "%i16        = OpTypeInt 16 1\n"
9434                                         "%u16        = OpTypeInt 16 0\n"
9435                                         "%i16vec2    = OpTypeVector %i16 2\n";
9436
9437                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9438                         if (requiresInt16Capability)
9439                                 caps += "OpCapability Int16\n";
9440                 }
9441
9442                 if (usesFloat16(from, to))
9443                 {
9444                         decl += "%f16        = OpTypeFloat 16\n";
9445
9446                         // Width-only conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9447                         if (!usesFloat32(from, to))
9448                                 caps += "OpCapability Float16\n";
9449                 }
9450
9451                 if (usesInt16(from, to) || usesFloat16(from, to))
9452                 {
9453                         caps += "OpCapability StorageUniformBufferBlock16\n";
9454                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9455                 }
9456
9457                 if (usesInt64(from, to))
9458                 {
9459                         caps += "OpCapability Int64\n";
9460                         decl += "%i64        = OpTypeInt 64 1\n"
9461                                         "%u64        = OpTypeInt 64 0\n";
9462                 }
9463
9464                 if (usesFloat64(from, to))
9465                 {
9466                         caps += "OpCapability Float64\n";
9467                         decl += "%f64        = OpTypeFloat 64\n";
9468                 }
9469
9470                 m_asmTypes["datatype_capabilities"]             = caps;
9471                 m_asmTypes["datatype_additional_decl"]  = decl;
9472                 m_asmTypes["datatype_extensions"]               = exts;
9473         }
9474
9475         ConversionDataType              m_fromType;
9476         ConversionDataType              m_toType;
9477         string                                  m_name;
9478         map<string, string>             m_asmTypes;
9479         BufferSp                                m_inputBuffer;
9480         BufferSp                                m_outputBuffer;
9481 };
9482
9483 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9484 {
9485         map<string, string> params = convertCase.m_asmTypes;
9486
9487         params["instruction"]   = instruction;
9488         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9489         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9490
9491         const StringTemplate shader (
9492                 "OpCapability Shader\n"
9493                 "${datatype_capabilities}"
9494                 "${datatype_extensions:opt}"
9495                 "OpMemoryModel Logical GLSL450\n"
9496                 "OpEntryPoint GLCompute %main \"main\"\n"
9497                 "OpExecutionMode %main LocalSize 1 1 1\n"
9498                 "OpSource GLSL 430\n"
9499                 "OpName %main           \"main\"\n"
9500                 // Decorators
9501                 "OpDecorate %indata DescriptorSet 0\n"
9502                 "OpDecorate %indata Binding 0\n"
9503                 "OpDecorate %outdata DescriptorSet 0\n"
9504                 "OpDecorate %outdata Binding 1\n"
9505                 "OpDecorate %in_buf BufferBlock\n"
9506                 "OpDecorate %out_buf BufferBlock\n"
9507                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9508                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9509                 // Base types
9510                 "%void       = OpTypeVoid\n"
9511                 "%voidf      = OpTypeFunction %void\n"
9512                 "%u32        = OpTypeInt 32 0\n"
9513                 "%i32        = OpTypeInt 32 1\n"
9514                 "%f32        = OpTypeFloat 32\n"
9515                 "%v2i32      = OpTypeVector %i32 2\n"
9516                 "${datatype_additional_decl}"
9517                 "%uvec3      = OpTypeVector %u32 3\n"
9518                 // Derived types
9519                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9520                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9521                 "%in_buf     = OpTypeStruct %${inputType}\n"
9522                 "%out_buf    = OpTypeStruct %${outputType}\n"
9523                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9524                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9525                 "%indata     = OpVariable %in_bufptr Uniform\n"
9526                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9527                 // Constants
9528                 "%zero       = OpConstant %i32 0\n"
9529                 // Main function
9530                 "%main       = OpFunction %void None %voidf\n"
9531                 "%label      = OpLabel\n"
9532                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9533                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9534                 "%inval      = OpLoad %${inputType} %inloc\n"
9535                 "%conv       = ${instruction} %${outputType} %inval\n"
9536                 "              OpStore %outloc %conv\n"
9537                 "              OpReturn\n"
9538                 "              OpFunctionEnd\n"
9539         );
9540
9541         return shader.specialize(params);
9542 }
9543
9544 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9545 {
9546         if (instruction == "OpUConvert")
9547         {
9548                 // Convert unsigned int to unsigned int
9549                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9550                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9551                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9552
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9555                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9556
9557                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9558                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9559                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9560
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9564         }
9565         else if (instruction == "OpSConvert")
9566         {
9567                 // Sign extension int->int
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9572                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9573                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9574
9575                 // Truncate for int->int
9576                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9577                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9578                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9579                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9580                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9581                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9582
9583                 // Sign extension for int->uint
9584                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9585                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9586                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9587                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9588                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9589                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9590
9591                 // Truncate for int->uint
9592                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9593                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9594                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9595                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9596                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9597                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9598
9599                 // Sign extension for uint->int
9600                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9601                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9602                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9603                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9604                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9605                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9606
9607                 // Truncate for uint->int
9608                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9609                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9610                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9611                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9612                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9613                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9614
9615                 // Convert i16vec2 to i32vec2 and vice versa
9616                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9617                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9618                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9619                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9620         }
9621         else if (instruction == "OpFConvert")
9622         {
9623                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9624                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9625                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9626
9627                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9628                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9629
9630                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9631                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9632         }
9633         else if (instruction == "OpConvertFToU")
9634         {
9635                 // Normal numbers from uint8 range
9636                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9637                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9638                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9639
9640                 // Maximum uint8 value
9641                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9642                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9643                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9644
9645                 // +0
9646                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9647                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9648                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9649
9650                 // -0
9651                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9652                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9653                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9654
9655                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9656                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9657                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9658                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9659
9660                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9661                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9662                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9663                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9664
9665                 // +0
9666                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9667                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9668                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9669
9670                 // -0
9671                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9672                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9673                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9674
9675                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9676                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9677                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9678                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9679                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9680                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9681         }
9682         else if (instruction == "OpConvertUToF")
9683         {
9684                 // Normal numbers from uint8 range
9685                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9686                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9687                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9688
9689                 // Maximum uint8 value
9690                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9691                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9692                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9693
9694                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9695                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9696                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9697                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9698
9699                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9700                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9701                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9702                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9703
9704                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9705                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9706                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9707                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9708                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9709                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9710         }
9711         else if (instruction == "OpConvertFToS")
9712         {
9713                 // Normal numbers from int8 range
9714                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9715                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9716                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9717
9718                 // Minimum int8 value
9719                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9720                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9721                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9722
9723                 // Maximum int8 value
9724                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9725                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9726                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9727
9728                 // +0
9729                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9730                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9731                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9732
9733                 // -0
9734                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9735                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9736                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9737
9738                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9739                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9740                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9741                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9742
9743                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9744                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9745                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9746                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9747
9748                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9749                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9750                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9751                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9752
9753                 // +0
9754                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9755                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9756                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9757
9758                 // -0
9759                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9760                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9761                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9762
9763                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9764                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9765                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9766                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9767                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9768                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9769                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9770                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9771         }
9772         else if (instruction == "OpConvertSToF")
9773         {
9774                 // Normal numbers from int8 range
9775                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9776                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9777                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9778
9779                 // Minimum int8 value
9780                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9781                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9782                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9783
9784                 // Maximum int8 value
9785                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9786                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9787                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9788
9789                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9790                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9791                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9792                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9793
9794                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9795                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9796                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9797                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9798
9799                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9800                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9801                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9802                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9803
9804                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9805                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9806                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9807                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9808                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9809                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9810         }
9811         else
9812                 DE_FATAL("Unknown instruction");
9813 }
9814
9815 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9816 {
9817         map<string, string> params = convertCase.m_asmTypes;
9818         map<string, string> fragments;
9819
9820         params["instruction"] = instruction;
9821         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9822
9823         const StringTemplate decoration (
9824                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9825                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9826                 "      OpDecorate %SSBOi Binding 0\n"
9827                 "      OpDecorate %SSBOo Binding 1\n"
9828                 "      OpDecorate %s_SSBOi Block\n"
9829                 "      OpDecorate %s_SSBOo Block\n"
9830                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9831                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9832
9833         const StringTemplate pre_main (
9834                 "${datatype_additional_decl:opt}"
9835                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9836                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9837                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9838                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9839                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9840                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9841                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9842                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9843
9844         const StringTemplate testfun (
9845                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9846                 "%param     = OpFunctionParameter %v4f32\n"
9847                 "%label     = OpLabel\n"
9848                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9849                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9850                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9851                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9852                 "             OpStore %oLoc %valOut\n"
9853                 "             OpReturnValue %param\n"
9854                 "             OpFunctionEnd\n");
9855
9856         params["datatype_extensions"] =
9857                 params["datatype_extensions"] +
9858                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9859
9860         fragments["capability"] = params["datatype_capabilities"];
9861         fragments["extension"]  = params["datatype_extensions"];
9862         fragments["decoration"] = decoration.specialize(params);
9863         fragments["pre_main"]   = pre_main.specialize(params);
9864         fragments["testfun"]    = testfun.specialize(params);
9865
9866         return fragments;
9867 }
9868
9869 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9870 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9871 {
9872         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9873         vector<ConvertCase>                                     testCases;
9874         createConvertCases(testCases, instruction);
9875
9876         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9877         {
9878                 ComputeShaderSpec spec;
9879                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9880                 spec.numWorkGroups              = IVec3(1, 1, 1);
9881                 spec.inputs.push_back   (test->m_inputBuffer);
9882                 spec.outputs.push_back  (test->m_outputBuffer);
9883
9884                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9885
9886                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9887         }
9888         return group.release();
9889 }
9890
9891 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9892 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9893 {
9894         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9895         vector<ConvertCase>                                     testCases;
9896         createConvertCases(testCases, instruction);
9897
9898         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9899         {
9900                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9901                 VulkanFeatures          vulkanFeatures;
9902                 GraphicsResources       resources;
9903                 vector<string>          extensions;
9904                 SpecConstants           noSpecConstants;
9905                 PushConstants           noPushConstants;
9906                 GraphicsInterfaces      noInterfaces;
9907                 tcu::RGBA                       defaultColors[4];
9908
9909                 getDefaultColors                        (defaultColors);
9910                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9911                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9912                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9913
9914                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9915
9916                 vulkanFeatures.coreFeatures.vertexPipelineStoresAndAtomics      = true;
9917                 vulkanFeatures.coreFeatures.fragmentStoresAndAtomics            = true;
9918
9919                 createTestsForAllStages(
9920                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9921                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9922         }
9923         return group.release();
9924 }
9925
9926 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9927 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9928 {
9929         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9930         RGBA                                                    inputColors[4];
9931         RGBA                                                    outputColors[4];
9932         vector<string>                                  extensions;
9933         GraphicsResources                               resources;
9934         VulkanFeatures                                  features;
9935
9936         const char                                              functionStart[]  =
9937                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9938                 "%param1                = OpFunctionParameter %v4f32\n"
9939                 "%lbl                   = OpLabel\n";
9940
9941         const char                                              functionEnd[]           =
9942                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9943                 "                         OpReturnValue %transformed_param_32\n"
9944                 "                         OpFunctionEnd\n";
9945
9946         struct NameConstantsCode
9947         {
9948                 string name;
9949                 string constants;
9950                 string code;
9951         };
9952
9953 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9954                         "%f16                  = OpTypeFloat 16\n"                                                 \
9955                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9956                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9957                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9958                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9959                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9960                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9961                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9962                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9963
9964         NameConstantsCode                               tests[] =
9965         {
9966                 {
9967                         "vec4",
9968
9969                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9970                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9971                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9972                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9973                 },
9974                 {
9975                         "struct",
9976
9977                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9978                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9979                         "%fp_stype             = OpTypePointer Function %stype\n"
9980                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9981                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9982                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9983                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9984
9985                         "%v                    = OpVariable %fp_stype Function %cval\n"
9986                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9987                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9988                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9989                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9990                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9991                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9992                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9993                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9994                 },
9995                 {
9996                         // [1|0|0|0.5] [x] = x + 0.5
9997                         // [0|1|0|0.5] [y] = y + 0.5
9998                         // [0|0|1|0.5] [z] = z + 0.5
9999                         // [0|0|0|1  ] [1] = 1
10000                         "matrix",
10001
10002                         FLOAT_16_COMMON_TYPES_AND_CONSTS
10003                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
10004                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
10005                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
10006                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
10007                         "%v4f16_0_5_0_5_0_5_1  = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_1\n"
10008                         "%cval                 = OpConstantComposite %mat4x4_f16 %v4f16_1_0_0_0 %v4f16_0_1_0_0 %v4f16_0_0_1_0 %v4f16_0_5_0_5_0_5_1\n",
10009
10010                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10011                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
10012                 },
10013                 {
10014                         "array",
10015
10016                         FLOAT_16_COMMON_TYPES_AND_CONSTS
10017                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
10018                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
10019                         "%f16_n_1              = OpConstant %f16 -1.0\n"
10020                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
10021                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
10022
10023                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
10024                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
10025                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
10026                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
10027                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
10028                         "%f_val                = OpLoad %f16 %f\n"
10029                         "%f1_val               = OpLoad %f16 %f1\n"
10030                         "%f2_val               = OpLoad %f16 %f2\n"
10031                         "%f3_val               = OpLoad %f16 %f3\n"
10032                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
10033                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
10034                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
10035                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
10036                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10037                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10038                 },
10039                 {
10040                         //
10041                         // [
10042                         //   {
10043                         //      0.0,
10044                         //      [ 1.0, 1.0, 1.0, 1.0]
10045                         //   },
10046                         //   {
10047                         //      1.0,
10048                         //      [ 0.0, 0.5, 0.0, 0.0]
10049                         //   }, //     ^^^
10050                         //   {
10051                         //      0.0,
10052                         //      [ 1.0, 1.0, 1.0, 1.0]
10053                         //   }
10054                         // ]
10055                         "array_of_struct_of_array",
10056
10057                         FLOAT_16_COMMON_TYPES_AND_CONSTS
10058                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
10059                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
10060                         "%stype                = OpTypeStruct %f16 %a4f16\n"
10061                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
10062                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
10063                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
10064                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
10065                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
10066                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
10067                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
10068
10069                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
10070                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
10071                         "%f_l                  = OpLoad %f16 %f\n"
10072                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
10073                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10074                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10075                 }
10076         };
10077
10078         getHalfColorsFullAlpha(inputColors);
10079         outputColors[0] = RGBA(255, 255, 255, 255);
10080         outputColors[1] = RGBA(255, 127, 127, 255);
10081         outputColors[2] = RGBA(127, 255, 127, 255);
10082         outputColors[3] = RGBA(127, 127, 255, 255);
10083
10084         extensions.push_back("VK_KHR_16bit_storage");
10085         extensions.push_back("VK_KHR_shader_float16_int8");
10086         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10087
10088         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
10089         {
10090                 map<string, string> fragments;
10091
10092                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
10093                 fragments["capability"] = "OpCapability Float16\n";
10094                 fragments["pre_main"]   = tests[testNdx].constants;
10095                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
10096
10097                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
10098         }
10099         return opConstantCompositeTests.release();
10100 }
10101
10102 template<typename T>
10103 void finalizeTestsCreation (T&                                                  specResource,
10104                                                         const map<string, string>&      fragments,
10105                                                         tcu::TestContext&                       testCtx,
10106                                                         tcu::TestCaseGroup&                     testGroup,
10107                                                         const std::string&                      testName,
10108                                                         const VulkanFeatures&           vulkanFeatures,
10109                                                         const vector<string>&           extensions,
10110                                                         const IVec3&                            numWorkGroups);
10111
10112 template<>
10113 void finalizeTestsCreation (GraphicsResources&                  specResource,
10114                                                         const map<string, string>&      fragments,
10115                                                         tcu::TestContext&                       ,
10116                                                         tcu::TestCaseGroup&                     testGroup,
10117                                                         const std::string&                      testName,
10118                                                         const VulkanFeatures&           vulkanFeatures,
10119                                                         const vector<string>&           extensions,
10120                                                         const IVec3&                            )
10121 {
10122         RGBA defaultColors[4];
10123         getDefaultColors(defaultColors);
10124
10125         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
10126 }
10127
10128 template<>
10129 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
10130                                                         const map<string, string>&      fragments,
10131                                                         tcu::TestContext&                       testCtx,
10132                                                         tcu::TestCaseGroup&                     testGroup,
10133                                                         const std::string&                      testName,
10134                                                         const VulkanFeatures&           vulkanFeatures,
10135                                                         const vector<string>&           extensions,
10136                                                         const IVec3&                            numWorkGroups)
10137 {
10138         specResource.numWorkGroups = numWorkGroups;
10139         specResource.requestedVulkanFeatures = vulkanFeatures;
10140         specResource.extensions = extensions;
10141
10142         specResource.assembly = makeComputeShaderAssembly(fragments);
10143
10144         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
10145 }
10146
10147 template<class SpecResource>
10148 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
10149 {
10150         const string                                            nan                                     = nanSupported ? "_nan" : "";
10151         const string                                            groupName                       = "logical" + nan;
10152         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
10153
10154         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10155         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
10156         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
10157         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
10158         const deUint32                                          numDataPointsScalar     = 16;
10159         const deUint32                                          numDataPointsVector     = 14;
10160         const vector<deFloat16>                         float16DataScalar       = getFloat16s(rnd, numDataPointsScalar);
10161         const vector<deFloat16>                         float16DataVector       = getFloat16s(rnd, numDataPointsVector);
10162         const vector<deFloat16>                         float16Data1            = squarize(float16DataScalar, 0);                       // Total Size: square(sizeof(float16DataScalar))
10163         const vector<deFloat16>                         float16Data2            = squarize(float16DataScalar, 1);
10164         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16DataVector, 0);         // Total Size: 2 * (square(square(sizeof(float16DataVector))))
10165         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16DataVector, 1);
10166         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
10167         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
10168
10169         struct TestOp
10170         {
10171                 const char*             opCode;
10172                 VerifyIOFunc    verifyFuncNan;
10173                 VerifyIOFunc    verifyFuncNonNan;
10174                 const deUint32  argCount;
10175         };
10176
10177         const TestOp    testOps[]       =
10178         {
10179                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
10180                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
10181                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
10182                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
10183                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
10184                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
10185                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
10186                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
10187                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
10188                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
10189                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
10190                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
10191                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
10192                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
10193         };
10194
10195         { // scalar cases
10196                 const StringTemplate preMain
10197                 (
10198                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10199                         "      %f16 = OpTypeFloat 16\n"
10200                         "  %c_f16_0 = OpConstant %f16 0.0\n"
10201                         "  %c_f16_1 = OpConstant %f16 1.0\n"
10202                         "   %up_f16 = OpTypePointer Uniform %f16\n"
10203                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10204                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
10205                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10206                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10207                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10208                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10209                 );
10210
10211                 const StringTemplate decoration
10212                 (
10213                         "OpDecorate %ra_f16 ArrayStride 2\n"
10214                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10215                         "OpDecorate %SSBO16 BufferBlock\n"
10216                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10217                         "OpDecorate %ssbo_src0 Binding 0\n"
10218                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10219                         "OpDecorate %ssbo_src1 Binding 1\n"
10220                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10221                         "OpDecorate %ssbo_dst Binding 2\n"
10222                 );
10223
10224                 const StringTemplate testFun
10225                 (
10226                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10227                         "    %param = OpFunctionParameter %v4f32\n"
10228
10229                         "    %entry = OpLabel\n"
10230                         "        %i = OpVariable %fp_i32 Function\n"
10231                         "             OpStore %i %c_i32_0\n"
10232                         "             OpBranch %loop\n"
10233
10234                         "     %loop = OpLabel\n"
10235                         "    %i_cmp = OpLoad %i32 %i\n"
10236                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10237                         "             OpLoopMerge %merge %next None\n"
10238                         "             OpBranchConditional %lt %write %merge\n"
10239
10240                         "    %write = OpLabel\n"
10241                         "      %ndx = OpLoad %i32 %i\n"
10242
10243                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10244                         " %val_src0 = OpLoad %f16 %src0\n"
10245
10246                         "${op_arg1_calc}"
10247
10248                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10249                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10250                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10251                         "             OpStore %dst %val_dst\n"
10252                         "             OpBranch %next\n"
10253
10254                         "     %next = OpLabel\n"
10255                         "    %i_cur = OpLoad %i32 %i\n"
10256                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10257                         "             OpStore %i %i_new\n"
10258                         "             OpBranch %loop\n"
10259
10260                         "    %merge = OpLabel\n"
10261                         "             OpReturnValue %param\n"
10262
10263                         "             OpFunctionEnd\n"
10264                 );
10265
10266                 const StringTemplate arg1Calc
10267                 (
10268                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10269                         " %val_src1 = OpLoad %f16 %src1\n"
10270                 );
10271
10272                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10273                 {
10274                         const size_t            iterations              = float16Data1.size();
10275                         const TestOp&           testOp                  = testOps[testOpsIdx];
10276                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10277                         SpecResource            specResource;
10278                         map<string, string>     specs;
10279                         VulkanFeatures          features;
10280                         map<string, string>     fragments;
10281                         vector<string>          extensions;
10282
10283                         specs["num_data_points"]        = de::toString(iterations);
10284                         specs["op_code"]                        = testOp.opCode;
10285                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10286                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10287
10288                         fragments["extension"]          = spvExtensions;
10289                         fragments["capability"]         = spvCapabilities;
10290                         fragments["execution_mode"]     = spvExecutionMode;
10291                         fragments["decoration"]         = decoration.specialize(specs);
10292                         fragments["pre_main"]           = preMain.specialize(specs);
10293                         fragments["testfun"]            = testFun.specialize(specs);
10294
10295                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10296                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10297                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10298                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10299
10300                         extensions.push_back("VK_KHR_16bit_storage");
10301                         extensions.push_back("VK_KHR_shader_float16_int8");
10302
10303                         if (nanSupported)
10304                         {
10305                                 extensions.push_back("VK_KHR_shader_float_controls");
10306
10307                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10308                         }
10309
10310                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10311                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10312
10313                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10314                 }
10315         }
10316         { // vector cases
10317                 const StringTemplate preMain
10318                 (
10319                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10320                         "     %v2bool = OpTypeVector %bool 2\n"
10321                         "        %f16 = OpTypeFloat 16\n"
10322                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10323                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10324                         "      %v2f16 = OpTypeVector %f16 2\n"
10325                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10326                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10327                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10328                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10329                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10330                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10331                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10332                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10333                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10334                 );
10335
10336                 const StringTemplate decoration
10337                 (
10338                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10339                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10340                         "OpDecorate %SSBO16 BufferBlock\n"
10341                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10342                         "OpDecorate %ssbo_src0 Binding 0\n"
10343                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10344                         "OpDecorate %ssbo_src1 Binding 1\n"
10345                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10346                         "OpDecorate %ssbo_dst Binding 2\n"
10347                 );
10348
10349                 const StringTemplate testFun
10350                 (
10351                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10352                         "    %param = OpFunctionParameter %v4f32\n"
10353
10354                         "    %entry = OpLabel\n"
10355                         "        %i = OpVariable %fp_i32 Function\n"
10356                         "             OpStore %i %c_i32_0\n"
10357                         "             OpBranch %loop\n"
10358
10359                         "     %loop = OpLabel\n"
10360                         "    %i_cmp = OpLoad %i32 %i\n"
10361                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10362                         "             OpLoopMerge %merge %next None\n"
10363                         "             OpBranchConditional %lt %write %merge\n"
10364
10365                         "    %write = OpLabel\n"
10366                         "      %ndx = OpLoad %i32 %i\n"
10367
10368                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10369                         " %val_src0 = OpLoad %v2f16 %src0\n"
10370
10371                         "${op_arg1_calc}"
10372
10373                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10374                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10375                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10376                         "             OpStore %dst %val_dst\n"
10377                         "             OpBranch %next\n"
10378
10379                         "     %next = OpLabel\n"
10380                         "    %i_cur = OpLoad %i32 %i\n"
10381                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10382                         "             OpStore %i %i_new\n"
10383                         "             OpBranch %loop\n"
10384
10385                         "    %merge = OpLabel\n"
10386                         "             OpReturnValue %param\n"
10387
10388                         "             OpFunctionEnd\n"
10389                 );
10390
10391                 const StringTemplate arg1Calc
10392                 (
10393                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10394                         " %val_src1 = OpLoad %v2f16 %src1\n"
10395                 );
10396
10397                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10398                 {
10399                         const deUint32          itemsPerVec     = 2;
10400                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10401                         const TestOp&           testOp          = testOps[testOpsIdx];
10402                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10403                         SpecResource            specResource;
10404                         map<string, string>     specs;
10405                         vector<string>          extensions;
10406                         VulkanFeatures          features;
10407                         map<string, string>     fragments;
10408
10409                         specs["num_data_points"]        = de::toString(iterations);
10410                         specs["op_code"]                        = testOp.opCode;
10411                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10412                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10413
10414                         fragments["extension"]          = spvExtensions;
10415                         fragments["capability"]         = spvCapabilities;
10416                         fragments["execution_mode"]     = spvExecutionMode;
10417                         fragments["decoration"]         = decoration.specialize(specs);
10418                         fragments["pre_main"]           = preMain.specialize(specs);
10419                         fragments["testfun"]            = testFun.specialize(specs);
10420
10421                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10422                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10423                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10424                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10425
10426                         extensions.push_back("VK_KHR_16bit_storage");
10427                         extensions.push_back("VK_KHR_shader_float16_int8");
10428
10429                         if (nanSupported)
10430                         {
10431                                 extensions.push_back("VK_KHR_shader_float_controls");
10432
10433                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10434                         }
10435
10436                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10437                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10438
10439                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10440                 }
10441         }
10442
10443         return testGroup.release();
10444 }
10445
10446 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10447 {
10448         if (inputs.size() != 1 || outputAllocs.size() != 1)
10449                 return false;
10450
10451         vector<deUint8> input1Bytes;
10452
10453         inputs[0].getBytes(input1Bytes);
10454
10455         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10456         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10457         std::string                             error;
10458
10459         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10460         {
10461                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10462                 {
10463                         log << TestLog::Message << error << TestLog::EndMessage;
10464
10465                         return false;
10466                 }
10467         }
10468
10469         return true;
10470 }
10471
10472 template<class SpecResource>
10473 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10474 {
10475         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10476
10477         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10478         const StringTemplate                            capabilities            ("OpCapability ${cap}\nOpCapability Float16\n");
10479         const deUint32                                          numDataPoints           = 256;
10480         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10481         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10482         map<string, string>                                     fragments;
10483
10484         struct TestType
10485         {
10486                 const deUint32  typeComponents;
10487                 const char*             typeName;
10488                 const char*             typeDecls;
10489         };
10490
10491         const TestType  testTypes[]     =
10492         {
10493                 {
10494                         1,
10495                         "f16",
10496                         ""
10497                 },
10498                 {
10499                         2,
10500                         "v2f16",
10501                         "      %v2f16 = OpTypeVector %f16 2\n"
10502                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10503                 },
10504                 {
10505                         4,
10506                         "v4f16",
10507                         "      %v4f16 = OpTypeVector %f16 4\n"
10508                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10509                 },
10510         };
10511
10512         const StringTemplate preMain
10513         (
10514                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10515                 "     %v2bool = OpTypeVector %bool 2\n"
10516                 "        %f16 = OpTypeFloat 16\n"
10517                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10518
10519                 "${type_decls}"
10520
10521                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10522                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10523                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10524                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10525                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10526                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10527                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10528         );
10529
10530         const StringTemplate decoration
10531         (
10532                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10533                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10534                 "OpDecorate %SSBO16 BufferBlock\n"
10535                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10536                 "OpDecorate %ssbo_src Binding 0\n"
10537                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10538                 "OpDecorate %ssbo_dst Binding 1\n"
10539         );
10540
10541         const StringTemplate testFun
10542         (
10543                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10544                 "    %param = OpFunctionParameter %v4f32\n"
10545                 "    %entry = OpLabel\n"
10546
10547                 "        %i = OpVariable %fp_i32 Function\n"
10548                 "             OpStore %i %c_i32_0\n"
10549                 "             OpBranch %loop\n"
10550
10551                 "     %loop = OpLabel\n"
10552                 "    %i_cmp = OpLoad %i32 %i\n"
10553                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10554                 "             OpLoopMerge %merge %next None\n"
10555                 "             OpBranchConditional %lt %write %merge\n"
10556
10557                 "    %write = OpLabel\n"
10558                 "      %ndx = OpLoad %i32 %i\n"
10559
10560                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10561                 "  %val_src = OpLoad %${tt} %src\n"
10562
10563                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10564                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10565                 "             OpStore %dst %val_dst\n"
10566                 "             OpBranch %next\n"
10567
10568                 "     %next = OpLabel\n"
10569                 "    %i_cur = OpLoad %i32 %i\n"
10570                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10571                 "             OpStore %i %i_new\n"
10572                 "             OpBranch %loop\n"
10573
10574                 "    %merge = OpLabel\n"
10575                 "             OpReturnValue %param\n"
10576
10577                 "             OpFunctionEnd\n"
10578
10579                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10580                 "   %param0 = OpFunctionParameter %${tt}\n"
10581                 " %entry_pf = OpLabel\n"
10582                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10583                 "             OpReturnValue %res0\n"
10584                 "             OpFunctionEnd\n"
10585         );
10586
10587         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10588         {
10589                 const TestType&         testType                = testTypes[testTypeIdx];
10590                 const string            testName                = testType.typeName;
10591                 const deUint32          itemsPerType    = testType.typeComponents;
10592                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10593                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10594                 SpecResource            specResource;
10595                 map<string, string>     specs;
10596                 VulkanFeatures          features;
10597                 vector<string>          extensions;
10598
10599                 specs["cap"]                            = "StorageUniformBufferBlock16";
10600                 specs["num_data_points"]        = de::toString(iterations);
10601                 specs["tt"]                                     = testType.typeName;
10602                 specs["tt_stride"]                      = de::toString(typeStride);
10603                 specs["type_decls"]                     = testType.typeDecls;
10604
10605                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10606                 fragments["capability"]         = capabilities.specialize(specs);
10607                 fragments["decoration"]         = decoration.specialize(specs);
10608                 fragments["pre_main"]           = preMain.specialize(specs);
10609                 fragments["testfun"]            = testFun.specialize(specs);
10610
10611                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10612                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10613                 specResource.verifyIO = compareFP16FunctionSetFunc;
10614
10615                 extensions.push_back("VK_KHR_16bit_storage");
10616                 extensions.push_back("VK_KHR_shader_float16_int8");
10617
10618                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10619                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10620
10621                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10622         }
10623
10624         return testGroup.release();
10625 }
10626
10627 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10628 {
10629         if (inputs.size() != 2 || outputAllocs.size() != 1)
10630                 return false;
10631
10632         vector<deUint8> input1Bytes;
10633         vector<deUint8> input2Bytes;
10634
10635         inputs[0].getBytes(input1Bytes);
10636         inputs[1].getBytes(input2Bytes);
10637
10638         DE_ASSERT(input1Bytes.size() > 0);
10639         DE_ASSERT(input2Bytes.size() > 0);
10640         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10641
10642         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10643         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10644         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10645         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10646         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10647         std::string                             error;
10648
10649         DE_ASSERT(components == 2 || components == 4);
10650         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10651
10652         for (size_t idx = 0; idx < iterations; ++idx)
10653         {
10654                 const deUint32  componentNdx    = inputIndices[idx];
10655
10656                 DE_ASSERT(componentNdx < components);
10657
10658                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10659
10660                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10661                 {
10662                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10663
10664                         return false;
10665                 }
10666         }
10667
10668         return true;
10669 }
10670
10671 template<class SpecResource>
10672 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10673 {
10674         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10675
10676         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10677         const deUint32                                          numDataPoints           = 256;
10678         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10679         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10680
10681         struct TestType
10682         {
10683                 const deUint32  typeComponents;
10684                 const size_t    typeStride;
10685                 const char*             typeName;
10686                 const char*             typeDecls;
10687         };
10688
10689         const TestType  testTypes[]     =
10690         {
10691                 {
10692                         2,
10693                         2 * sizeof(deFloat16),
10694                         "v2f16",
10695                         "      %v2f16 = OpTypeVector %f16 2\n"
10696                 },
10697                 {
10698                         3,
10699                         4 * sizeof(deFloat16),
10700                         "v3f16",
10701                         "      %v3f16 = OpTypeVector %f16 3\n"
10702                 },
10703                 {
10704                         4,
10705                         4 * sizeof(deFloat16),
10706                         "v4f16",
10707                         "      %v4f16 = OpTypeVector %f16 4\n"
10708                 },
10709         };
10710
10711         const StringTemplate preMain
10712         (
10713                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10714                 "        %f16 = OpTypeFloat 16\n"
10715
10716                 "${type_decl}"
10717
10718                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10719                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10720                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10721                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10722
10723                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10724                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10725                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10726                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10727
10728                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10729                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10730                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10731                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10732
10733                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10734                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10735                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10736         );
10737
10738         const StringTemplate decoration
10739         (
10740                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10741                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10742                 "OpDecorate %SSBO_SRC BufferBlock\n"
10743                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10744                 "OpDecorate %ssbo_src Binding 0\n"
10745
10746                 "OpDecorate %ra_u32 ArrayStride 4\n"
10747                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10748                 "OpDecorate %SSBO_IDX BufferBlock\n"
10749                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10750                 "OpDecorate %ssbo_idx Binding 1\n"
10751
10752                 "OpDecorate %ra_f16 ArrayStride 2\n"
10753                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10754                 "OpDecorate %SSBO_DST BufferBlock\n"
10755                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10756                 "OpDecorate %ssbo_dst Binding 2\n"
10757         );
10758
10759         const StringTemplate testFun
10760         (
10761                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10762                 "    %param = OpFunctionParameter %v4f32\n"
10763                 "    %entry = OpLabel\n"
10764
10765                 "        %i = OpVariable %fp_i32 Function\n"
10766                 "             OpStore %i %c_i32_0\n"
10767
10768                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10769                 "             OpSelectionMerge %end_if None\n"
10770                 "             OpBranchConditional %will_run %run_test %end_if\n"
10771
10772                 " %run_test = OpLabel\n"
10773                 "             OpBranch %loop\n"
10774
10775                 "     %loop = OpLabel\n"
10776                 "    %i_cmp = OpLoad %i32 %i\n"
10777                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10778                 "             OpLoopMerge %merge %next None\n"
10779                 "             OpBranchConditional %lt %write %merge\n"
10780
10781                 "    %write = OpLabel\n"
10782                 "      %ndx = OpLoad %i32 %i\n"
10783
10784                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10785                 "  %val_src = OpLoad %${tt} %src\n"
10786
10787                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10788                 "  %val_idx = OpLoad %u32 %src_idx\n"
10789
10790                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10791                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10792
10793                 "             OpStore %dst %val_dst\n"
10794                 "             OpBranch %next\n"
10795
10796                 "     %next = OpLabel\n"
10797                 "    %i_cur = OpLoad %i32 %i\n"
10798                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10799                 "             OpStore %i %i_new\n"
10800                 "             OpBranch %loop\n"
10801
10802                 "    %merge = OpLabel\n"
10803                 "             OpBranch %end_if\n"
10804                 "   %end_if = OpLabel\n"
10805                 "             OpReturnValue %param\n"
10806
10807                 "             OpFunctionEnd\n"
10808         );
10809
10810         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10811         {
10812                 const TestType&         testType                = testTypes[testTypeIdx];
10813                 const string            testName                = testType.typeName;
10814                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10815                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10816                 SpecResource            specResource;
10817                 map<string, string>     specs;
10818                 VulkanFeatures          features;
10819                 vector<deUint32>        inputDataNdx;
10820                 map<string, string>     fragments;
10821                 vector<string>          extensions;
10822
10823                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10824                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10825
10826                 specs["num_data_points"]        = de::toString(iterations);
10827                 specs["tt"]                                     = testType.typeName;
10828                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10829                 specs["type_decl"]                      = testType.typeDecls;
10830
10831                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10832                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
10833                 fragments["decoration"]         = decoration.specialize(specs);
10834                 fragments["pre_main"]           = preMain.specialize(specs);
10835                 fragments["testfun"]            = testFun.specialize(specs);
10836
10837                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10838                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10839                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10840                 specResource.verifyIO = compareFP16VectorExtractFunc;
10841
10842                 extensions.push_back("VK_KHR_16bit_storage");
10843                 extensions.push_back("VK_KHR_shader_float16_int8");
10844
10845                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10846                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10847
10848                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10849         }
10850
10851         return testGroup.release();
10852 }
10853
10854 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
10855 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10856 {
10857         if (inputs.size() != 2 || outputAllocs.size() != 1)
10858                 return false;
10859
10860         vector<deUint8> input1Bytes;
10861         vector<deUint8> input2Bytes;
10862
10863         inputs[0].getBytes(input1Bytes);
10864         inputs[1].getBytes(input2Bytes);
10865
10866         DE_ASSERT(input1Bytes.size() > 0);
10867         DE_ASSERT(input2Bytes.size() > 0);
10868         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10869
10870         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
10871         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10872         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
10873         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
10874         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
10875         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
10876         std::string                             error;
10877
10878         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
10879         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
10880
10881         for (size_t idx = 0; idx < iterations; ++idx)
10882         {
10883                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
10884                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
10885                 const deUint32          replacedCompNdx = inputIndices[idx];
10886
10887                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
10888
10889                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
10890                 {
10891                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
10892
10893                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
10894                         {
10895                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
10896
10897                                 return false;
10898                         }
10899                 }
10900         }
10901
10902         return true;
10903 }
10904
10905 template<class SpecResource>
10906 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
10907 {
10908         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
10909
10910         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10911         const deUint32                                          replacement                     = 42;
10912         const deUint32                                          numDataPoints           = 256;
10913         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10914         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10915
10916         struct TestType
10917         {
10918                 const deUint32  typeComponents;
10919                 const size_t    typeStride;
10920                 const char*             typeName;
10921                 const char*             typeDecls;
10922                 VerifyIOFunc    verifyIOFunc;
10923         };
10924
10925         const TestType  testTypes[]     =
10926         {
10927                 {
10928                         2,
10929                         2 * sizeof(deFloat16),
10930                         "v2f16",
10931                         "      %v2f16 = OpTypeVector %f16 2\n",
10932                         compareFP16VectorInsertFunc<2, replacement>
10933                 },
10934                 {
10935                         3,
10936                         4 * sizeof(deFloat16),
10937                         "v3f16",
10938                         "      %v3f16 = OpTypeVector %f16 3\n",
10939                         compareFP16VectorInsertFunc<3, replacement>
10940                 },
10941                 {
10942                         4,
10943                         4 * sizeof(deFloat16),
10944                         "v4f16",
10945                         "      %v4f16 = OpTypeVector %f16 4\n",
10946                         compareFP16VectorInsertFunc<4, replacement>
10947                 },
10948         };
10949
10950         const StringTemplate preMain
10951         (
10952                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10953                 "        %f16 = OpTypeFloat 16\n"
10954                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
10955
10956                 "${type_decl}"
10957
10958                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10959                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10960                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10961                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10962
10963                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10964                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10965                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10966                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10967
10968                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
10969                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10970
10971                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10972                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10973                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10974         );
10975
10976         const StringTemplate decoration
10977         (
10978                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10979                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10980                 "OpDecorate %SSBO_SRC BufferBlock\n"
10981                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10982                 "OpDecorate %ssbo_src Binding 0\n"
10983
10984                 "OpDecorate %ra_u32 ArrayStride 4\n"
10985                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10986                 "OpDecorate %SSBO_IDX BufferBlock\n"
10987                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10988                 "OpDecorate %ssbo_idx Binding 1\n"
10989
10990                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10991                 "OpDecorate %SSBO_DST BufferBlock\n"
10992                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10993                 "OpDecorate %ssbo_dst Binding 2\n"
10994         );
10995
10996         const StringTemplate testFun
10997         (
10998                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10999                 "    %param = OpFunctionParameter %v4f32\n"
11000                 "    %entry = OpLabel\n"
11001
11002                 "        %i = OpVariable %fp_i32 Function\n"
11003                 "             OpStore %i %c_i32_0\n"
11004
11005                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11006                 "             OpSelectionMerge %end_if None\n"
11007                 "             OpBranchConditional %will_run %run_test %end_if\n"
11008
11009                 " %run_test = OpLabel\n"
11010                 "             OpBranch %loop\n"
11011
11012                 "     %loop = OpLabel\n"
11013                 "    %i_cmp = OpLoad %i32 %i\n"
11014                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11015                 "             OpLoopMerge %merge %next None\n"
11016                 "             OpBranchConditional %lt %write %merge\n"
11017
11018                 "    %write = OpLabel\n"
11019                 "      %ndx = OpLoad %i32 %i\n"
11020
11021                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11022                 "  %val_src = OpLoad %${tt} %src\n"
11023
11024                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11025                 "  %val_idx = OpLoad %u32 %src_idx\n"
11026
11027                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11028                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11029
11030                 "             OpStore %dst %val_dst\n"
11031                 "             OpBranch %next\n"
11032
11033                 "     %next = OpLabel\n"
11034                 "    %i_cur = OpLoad %i32 %i\n"
11035                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11036                 "             OpStore %i %i_new\n"
11037                 "             OpBranch %loop\n"
11038
11039                 "    %merge = OpLabel\n"
11040                 "             OpBranch %end_if\n"
11041                 "   %end_if = OpLabel\n"
11042                 "             OpReturnValue %param\n"
11043
11044                 "             OpFunctionEnd\n"
11045         );
11046
11047         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11048         {
11049                 const TestType&         testType                = testTypes[testTypeIdx];
11050                 const string            testName                = testType.typeName;
11051                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11052                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11053                 SpecResource            specResource;
11054                 map<string, string>     specs;
11055                 VulkanFeatures          features;
11056                 vector<deUint32>        inputDataNdx;
11057                 map<string, string>     fragments;
11058                 vector<string>          extensions;
11059
11060                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11061                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11062
11063                 specs["num_data_points"]        = de::toString(iterations);
11064                 specs["tt"]                                     = testType.typeName;
11065                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11066                 specs["type_decl"]                      = testType.typeDecls;
11067                 specs["replacement"]            = de::toString(replacement);
11068
11069                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11070                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
11071                 fragments["decoration"]         = decoration.specialize(specs);
11072                 fragments["pre_main"]           = preMain.specialize(specs);
11073                 fragments["testfun"]            = testFun.specialize(specs);
11074
11075                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11076                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11077                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11078                 specResource.verifyIO = testType.verifyIOFunc;
11079
11080                 extensions.push_back("VK_KHR_16bit_storage");
11081                 extensions.push_back("VK_KHR_shader_float16_int8");
11082
11083                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11084                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11085
11086                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11087         }
11088
11089         return testGroup.release();
11090 }
11091
11092 inline deFloat16 getShuffledComponent (const size_t iteration, const size_t componentNdx, const deFloat16* input1Vec, const deFloat16* input2Vec, size_t vec1Len, size_t vec2Len, bool& validate)
11093 {
11094         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11095         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11096         size_t                  comp;
11097
11098         switch (componentNdx)
11099         {
11100                 case 0: comp = compNdxLimited / compNdxCount; break;
11101                 case 1: comp = compNdxLimited % compNdxCount; break;
11102                 case 2: comp = 0; break;
11103                 case 3: comp = 1; break;
11104                 default: TCU_THROW(InternalError, "Impossible");
11105         }
11106
11107         if (comp >= vec1Len + vec2Len)
11108         {
11109                 validate = false;
11110                 return 0;
11111         }
11112         else
11113         {
11114                 validate = true;
11115                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11116         }
11117 }
11118
11119 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11120 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11121 {
11122         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11123         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11124         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11125
11126         if (inputs.size() != 2 || outputAllocs.size() != 1)
11127                 return false;
11128
11129         vector<deUint8> input1Bytes;
11130         vector<deUint8> input2Bytes;
11131
11132         inputs[0].getBytes(input1Bytes);
11133         inputs[1].getBytes(input2Bytes);
11134
11135         DE_ASSERT(input1Bytes.size() > 0);
11136         DE_ASSERT(input2Bytes.size() > 0);
11137         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11138
11139         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11140         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11141         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11142         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11143         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11144         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11145         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11146         std::string                             error;
11147
11148         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11149         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11150
11151         for (size_t idx = 0; idx < iterations; ++idx)
11152         {
11153                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11154                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11155                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11156
11157                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11158                 {
11159                         bool            validate        = true;
11160                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11161
11162                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11163                         {
11164                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11165
11166                                 return false;
11167                         }
11168                 }
11169         }
11170
11171         return true;
11172 }
11173
11174 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11175 {
11176         DE_ASSERT(dstComponentsCount <= 4);
11177         DE_ASSERT(src0ComponentsCount <= 4);
11178         DE_ASSERT(src1ComponentsCount <= 4);
11179         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11180
11181         switch (funcCode)
11182         {
11183                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11184                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11185                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11186                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11187                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11188                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11189                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11190                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11191                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11192                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11193                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11194                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11195                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11196                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11197                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11198                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11199                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11200                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11201                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11202                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11203                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11204                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11205                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11206                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11207                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11208                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11209                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11210                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11211         }
11212 }
11213
11214 template<class SpecResource>
11215 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11216 {
11217         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11218         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11219         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11220         de::Random                                                      rnd                                     (seed);
11221         const deUint32                                          numDataPoints           = 128;
11222         map<string, string>                                     fragments;
11223
11224         struct TestType
11225         {
11226                 const deUint32  typeComponents;
11227                 const char*             typeName;
11228         };
11229
11230         const TestType  testTypes[]     =
11231         {
11232                 {
11233                         2,
11234                         "v2f16",
11235                 },
11236                 {
11237                         3,
11238                         "v3f16",
11239                 },
11240                 {
11241                         4,
11242                         "v4f16",
11243                 },
11244         };
11245
11246         const StringTemplate preMain
11247         (
11248                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11249                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11250                 "          %f16 = OpTypeFloat 16\n"
11251                 "        %v2f16 = OpTypeVector %f16 2\n"
11252                 "        %v3f16 = OpTypeVector %f16 3\n"
11253                 "        %v4f16 = OpTypeVector %f16 4\n"
11254
11255                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11256                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11257                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11258                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11259
11260                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11261                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11262                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11263                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11264
11265                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11266                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11267                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11268                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11269
11270                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11271
11272                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11273                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11274                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11275         );
11276
11277         const StringTemplate decoration
11278         (
11279                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11280                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11281                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11282
11283                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11284                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11285
11286                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11287                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11288
11289                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11290                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11291
11292                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11293                 "OpDecorate %ssbo_src0 Binding 0\n"
11294                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11295                 "OpDecorate %ssbo_src1 Binding 1\n"
11296                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11297                 "OpDecorate %ssbo_dst Binding 2\n"
11298         );
11299
11300         const StringTemplate testFun
11301         (
11302                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11303                 "    %param = OpFunctionParameter %v4f32\n"
11304                 "    %entry = OpLabel\n"
11305
11306                 "        %i = OpVariable %fp_i32 Function\n"
11307                 "             OpStore %i %c_i32_0\n"
11308
11309                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11310                 "             OpSelectionMerge %end_if None\n"
11311                 "             OpBranchConditional %will_run %run_test %end_if\n"
11312
11313                 " %run_test = OpLabel\n"
11314                 "             OpBranch %loop\n"
11315
11316                 "     %loop = OpLabel\n"
11317                 "    %i_cmp = OpLoad %i32 %i\n"
11318                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11319                 "             OpLoopMerge %merge %next None\n"
11320                 "             OpBranchConditional %lt %write %merge\n"
11321
11322                 "    %write = OpLabel\n"
11323                 "      %ndx = OpLoad %i32 %i\n"
11324                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11325                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11326                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11327                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11328                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11329                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11330                 "             OpStore %dst %val_dst\n"
11331                 "             OpBranch %next\n"
11332
11333                 "     %next = OpLabel\n"
11334                 "    %i_cur = OpLoad %i32 %i\n"
11335                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11336                 "             OpStore %i %i_new\n"
11337                 "             OpBranch %loop\n"
11338
11339                 "    %merge = OpLabel\n"
11340                 "             OpBranch %end_if\n"
11341                 "   %end_if = OpLabel\n"
11342                 "             OpReturnValue %param\n"
11343                 "             OpFunctionEnd\n"
11344                 "\n"
11345
11346                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11347                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11348                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11349                 "%sw_paramn = OpFunctionParameter %i32\n"
11350                 " %sw_entry = OpLabel\n"
11351                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11352                 "             OpSelectionMerge %switch_e None\n"
11353                 "             OpSwitch %modulo %default ${case_list}\n"
11354                 "${case_bodies}"
11355                 "%default   = OpLabel\n"
11356                 "             OpUnreachable\n" // Unreachable default case for switch statement
11357                 "%switch_e  = OpLabel\n"
11358                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11359                 "             OpFunctionEnd\n"
11360         );
11361
11362         const StringTemplate testCaseBody
11363         (
11364                 "%case_${case_ndx}    = OpLabel\n"
11365                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11366                 "             OpReturnValue %val_dst_${case_ndx}\n"
11367         );
11368
11369         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11370         {
11371                 const TestType& dstType                 = testTypes[dstTypeIdx];
11372
11373                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11374                 {
11375                         const TestType& src0Type        = testTypes[comp0Idx];
11376
11377                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11378                         {
11379                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11380                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11381                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11382                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11383                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11384                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11385                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11386                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11387                                 deUint32                                caseCount                       = 0;
11388                                 SpecResource                    specResource;
11389                                 map<string, string>             specs;
11390                                 vector<string>                  extensions;
11391                                 VulkanFeatures                  features;
11392                                 string                                  caseBodies;
11393                                 string                                  caseList;
11394
11395                                 // Generate case
11396                                 {
11397                                         vector<string>  componentList;
11398
11399                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11400                                         {
11401                                                 deUint32                caseNo          = 0;
11402
11403                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11404                                                         componentList.push_back(de::toString(caseNo++));
11405                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11406                                                         componentList.push_back(de::toString(caseNo++));
11407                                                 componentList.push_back("0xFFFFFFFF");
11408                                         }
11409
11410                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11411                                         {
11412                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11413                                                 {
11414                                                         map<string, string>     specCase;
11415                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11416
11417                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11418                                                                 shuffle += " " + de::toString(compIdx - 2);
11419
11420                                                         specCase["case_ndx"]    = de::toString(caseCount);
11421                                                         specCase["shuffle"]             = shuffle;
11422                                                         specCase["tt_dst"]              = dstType.typeName;
11423
11424                                                         caseBodies      += testCaseBody.specialize(specCase);
11425                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11426
11427                                                         caseCount++;
11428                                                 }
11429                                         }
11430                                 }
11431
11432                                 specs["num_data_points"]        = de::toString(numDataPoints);
11433                                 specs["tt_dst"]                         = dstType.typeName;
11434                                 specs["tt_src0"]                        = src0Type.typeName;
11435                                 specs["tt_src1"]                        = src1Type.typeName;
11436                                 specs["case_bodies"]            = caseBodies;
11437                                 specs["case_list"]                      = caseList;
11438                                 specs["case_count"]                     = de::toString(caseCount);
11439
11440                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11441                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
11442                                 fragments["decoration"]         = decoration.specialize(specs);
11443                                 fragments["pre_main"]           = preMain.specialize(specs);
11444                                 fragments["testfun"]            = testFun.specialize(specs);
11445
11446                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11447                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11448                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11449                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11450
11451                                 extensions.push_back("VK_KHR_16bit_storage");
11452                                 extensions.push_back("VK_KHR_shader_float16_int8");
11453
11454                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11455                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11456
11457                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11458                         }
11459                 }
11460         }
11461
11462         return testGroup.release();
11463 }
11464
11465 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11466 {
11467         if (inputs.size() != 1 || outputAllocs.size() != 1)
11468                 return false;
11469
11470         vector<deUint8> input1Bytes;
11471
11472         inputs[0].getBytes(input1Bytes);
11473
11474         DE_ASSERT(input1Bytes.size() > 0);
11475         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11476
11477         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11478         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11479         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11480         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11481         std::string                             error;
11482
11483         for (size_t idx = 0; idx < iterations; ++idx)
11484         {
11485                 if (input1AsFP16[idx] == exceptionValue)
11486                         continue;
11487
11488                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11489                 {
11490                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11491
11492                         return false;
11493                 }
11494         }
11495
11496         return true;
11497 }
11498
11499 template<class SpecResource>
11500 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11501 {
11502         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11503         const deUint32                                          numElements                             = 8;
11504         const string                                            testName                                = "struct";
11505         const deUint32                                          structItemsCount                = 88;
11506         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11507         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11508         const deUint32                                          fieldModifier                   = 2;
11509         const deUint32                                          fieldModifiedMulIndex   = 60;
11510         const deUint32                                          fieldModifiedAddIndex   = 66;
11511
11512         const StringTemplate preMain
11513         (
11514                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11515                 "          %f16 = OpTypeFloat 16\n"
11516                 "        %v2f16 = OpTypeVector %f16 2\n"
11517                 "        %v3f16 = OpTypeVector %f16 3\n"
11518                 "        %v4f16 = OpTypeVector %f16 4\n"
11519                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11520
11521                 "${consts}"
11522
11523                 "      %c_u32_5 = OpConstant %u32 5\n"
11524
11525                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11526                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11527                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11528                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11529                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11530                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11531                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11532                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11533
11534                 "        %up_st = OpTypePointer Uniform %st_test\n"
11535                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11536                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11537                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11538
11539                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11540         );
11541
11542         const StringTemplate decoration
11543         (
11544                 "OpDecorate %SSBO_st BufferBlock\n"
11545                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11546                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11547                 "OpDecorate %ssbo_dst Binding 1\n"
11548
11549                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11550
11551                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11552                 "OpMemberDecorate %struct16 0 Offset 0\n"
11553                 "OpMemberDecorate %struct16 1 Offset 4\n"
11554                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11555                 "OpDecorate %f16arr3 ArrayStride 2\n"
11556                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11557                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11558                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11559
11560                 "OpMemberDecorate %st_test 0 Offset 0\n"
11561                 "OpMemberDecorate %st_test 1 Offset 4\n"
11562                 "OpMemberDecorate %st_test 2 Offset 8\n"
11563                 "OpMemberDecorate %st_test 3 Offset 16\n"
11564                 "OpMemberDecorate %st_test 4 Offset 24\n"
11565                 "OpMemberDecorate %st_test 5 Offset 32\n"
11566                 "OpMemberDecorate %st_test 6 Offset 80\n"
11567                 "OpMemberDecorate %st_test 7 Offset 100\n"
11568                 "OpMemberDecorate %st_test 8 Offset 104\n"
11569                 "OpMemberDecorate %st_test 9 Offset 144\n"
11570         );
11571
11572         const StringTemplate testFun
11573         (
11574                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11575                 "     %param = OpFunctionParameter %v4f32\n"
11576                 "     %entry = OpLabel\n"
11577
11578                 "         %i = OpVariable %fp_i32 Function\n"
11579                 "              OpStore %i %c_i32_0\n"
11580
11581                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11582                 "              OpSelectionMerge %end_if None\n"
11583                 "              OpBranchConditional %will_run %run_test %end_if\n"
11584
11585                 "  %run_test = OpLabel\n"
11586                 "              OpBranch %loop\n"
11587
11588                 "      %loop = OpLabel\n"
11589                 "     %i_cmp = OpLoad %i32 %i\n"
11590                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11591                 "              OpLoopMerge %merge %next None\n"
11592                 "              OpBranchConditional %lt %write %merge\n"
11593
11594                 "     %write = OpLabel\n"
11595                 "       %ndx = OpLoad %i32 %i\n"
11596
11597                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11598                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11599                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11600
11601                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11602
11603                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11604                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11605                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11606                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11607                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11608
11609                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11610                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11611                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11612                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11613                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11614
11615                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11616                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11617                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11618                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11619                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11620
11621                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11622
11623                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11624                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11625                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11626                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11627                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11628                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11629
11630                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11631                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11632                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11633
11634                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11635                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11636                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11637                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11638                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11639                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11640                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11641                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11642
11643                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11644                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11645                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11646                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11647
11648                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11649                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11650                 "              OpStore %dst %st_val\n"
11651
11652                 "              OpBranch %next\n"
11653
11654                 "      %next = OpLabel\n"
11655                 "     %i_cur = OpLoad %i32 %i\n"
11656                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11657                 "              OpStore %i %i_new\n"
11658                 "              OpBranch %loop\n"
11659
11660                 "     %merge = OpLabel\n"
11661                 "              OpBranch %end_if\n"
11662                 "    %end_if = OpLabel\n"
11663                 "              OpReturnValue %param\n"
11664                 "              OpFunctionEnd\n"
11665         );
11666
11667         {
11668                 SpecResource            specResource;
11669                 map<string, string>     specs;
11670                 VulkanFeatures          features;
11671                 map<string, string>     fragments;
11672                 vector<string>          extensions;
11673                 vector<deFloat16>       expectedOutput;
11674                 string                          consts;
11675
11676                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11677                 {
11678                         vector<deFloat16>       expectedIterationOutput;
11679
11680                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11681                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11682
11683                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11684                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11685
11686                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11687                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11688
11689                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11690                 }
11691
11692                 for (deUint32 i = 0; i < structItemsCount; ++i)
11693                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11694
11695                 specs["num_elements"]           = de::toString(numElements);
11696                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11697                 specs["field_modifier"]         = de::toString(fieldModifier);
11698                 specs["consts"]                         = consts;
11699
11700                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11701                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
11702                 fragments["decoration"]         = decoration.specialize(specs);
11703                 fragments["pre_main"]           = preMain.specialize(specs);
11704                 fragments["testfun"]            = testFun.specialize(specs);
11705
11706                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11707                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11708                 specResource.verifyIO = compareFP16CompositeFunc;
11709
11710                 extensions.push_back("VK_KHR_16bit_storage");
11711                 extensions.push_back("VK_KHR_shader_float16_int8");
11712
11713                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11714                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11715
11716                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11717         }
11718
11719         return testGroup.release();
11720 }
11721
11722 template<class SpecResource>
11723 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11724 {
11725         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11726         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11727         const string                                            opName                  (op);
11728         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11729                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11730                                                                                                                 : -1;
11731
11732         const StringTemplate preMain
11733         (
11734                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11735                 "         %f16 = OpTypeFloat 16\n"
11736                 "       %v2f16 = OpTypeVector %f16 2\n"
11737                 "       %v3f16 = OpTypeVector %f16 3\n"
11738                 "       %v4f16 = OpTypeVector %f16 4\n"
11739                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11740                 "     %c_u32_5 = OpConstant %u32 5\n"
11741
11742                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11743                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11744                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11745                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11746                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11747                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11748                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11749                 "%st_test      = OpTypeStruct %${field_type}\n"
11750
11751                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11752                 "       %up_st = OpTypePointer Uniform %st_test\n"
11753                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11754                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11755
11756                 "${op_premain_decls}"
11757
11758                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11759                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11760
11761                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11762                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11763         );
11764
11765         const StringTemplate decoration
11766         (
11767                 "OpDecorate %SSBO_src BufferBlock\n"
11768                 "OpDecorate %SSBO_dst BufferBlock\n"
11769                 "OpDecorate %ra_f16 ArrayStride 2\n"
11770                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11771                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11772                 "OpDecorate %ssbo_src Binding 0\n"
11773                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11774                 "OpDecorate %ssbo_dst Binding 1\n"
11775
11776                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11777                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11778
11779                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11780                 "OpMemberDecorate %struct16 0 Offset 0\n"
11781                 "OpMemberDecorate %struct16 1 Offset 4\n"
11782                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11783                 "OpDecorate %f16arr3 ArrayStride 2\n"
11784                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11785                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11786                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11787
11788                 "OpMemberDecorate %st_test 0 Offset 0\n"
11789         );
11790
11791         const StringTemplate testFun
11792         (
11793                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11794                 "     %param = OpFunctionParameter %v4f32\n"
11795                 "     %entry = OpLabel\n"
11796
11797                 "         %i = OpVariable %fp_i32 Function\n"
11798                 "              OpStore %i %c_i32_0\n"
11799
11800                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11801                 "              OpSelectionMerge %end_if None\n"
11802                 "              OpBranchConditional %will_run %run_test %end_if\n"
11803
11804                 "  %run_test = OpLabel\n"
11805                 "              OpBranch %loop\n"
11806
11807                 "      %loop = OpLabel\n"
11808                 "     %i_cmp = OpLoad %i32 %i\n"
11809                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11810                 "              OpLoopMerge %merge %next None\n"
11811                 "              OpBranchConditional %lt %write %merge\n"
11812
11813                 "     %write = OpLabel\n"
11814                 "       %ndx = OpLoad %i32 %i\n"
11815
11816                 "${op_sw_fun_call}"
11817
11818                 "              OpStore %dst %val_dst\n"
11819                 "              OpBranch %next\n"
11820
11821                 "      %next = OpLabel\n"
11822                 "     %i_cur = OpLoad %i32 %i\n"
11823                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11824                 "              OpStore %i %i_new\n"
11825                 "              OpBranch %loop\n"
11826
11827                 "     %merge = OpLabel\n"
11828                 "              OpBranch %end_if\n"
11829                 "    %end_if = OpLabel\n"
11830                 "              OpReturnValue %param\n"
11831                 "              OpFunctionEnd\n"
11832
11833                 "${op_sw_fun_header}"
11834                 " %sw_param = OpFunctionParameter %st_test\n"
11835                 "%sw_paramn = OpFunctionParameter %i32\n"
11836                 " %sw_entry = OpLabel\n"
11837                 "             OpSelectionMerge %switch_e None\n"
11838                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11839
11840                 "${case_bodies}"
11841
11842                 "%default   = OpLabel\n"
11843                 "             OpReturnValue ${op_case_default_value}\n"
11844                 "%switch_e  = OpLabel\n"
11845                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11846                 "             OpFunctionEnd\n"
11847         );
11848
11849         const StringTemplate testCaseBody
11850         (
11851                 "%case_${case_ndx}    = OpLabel\n"
11852                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
11853                 "             OpReturnValue %val_ret_${case_ndx}\n"
11854         );
11855
11856         struct OpParts
11857         {
11858                 const char*     premainDecls;
11859                 const char*     swFunCall;
11860                 const char*     swFunHeader;
11861                 const char*     caseDefaultValue;
11862                 const char*     argsPartial;
11863         };
11864
11865         OpParts                                                         opPartsArray[]                  =
11866         {
11867                 // OpCompositeInsert
11868                 {
11869                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
11870                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
11871                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
11872
11873                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
11874                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
11875                         "   %val_new = OpLoad %f16 %src\n"
11876                         "   %val_old = OpLoad %st_test %dst\n"
11877                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
11878
11879                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
11880                         "%sw_paramv = OpFunctionParameter %f16\n",
11881
11882                         "%sw_param",
11883
11884                         "%st_test %sw_paramv %sw_param",
11885                 },
11886                 // OpCompositeExtract
11887                 {
11888                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
11889                         "    %SSBO_src = OpTypeStruct %ra_st\n"
11890                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
11891
11892                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
11893                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
11894                         "   %val_src = OpLoad %st_test %src\n"
11895                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
11896
11897                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
11898
11899                         "%c_f16_na",
11900
11901                         "%f16 %sw_param",
11902                 },
11903         };
11904
11905         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
11906
11907         const char*     accessPathF16[] =
11908         {
11909                 "0",                    // %f16
11910                 DE_NULL,
11911         };
11912         const char*     accessPathV2F16[] =
11913         {
11914                 "0 0",                  // %v2f16
11915                 "0 1",
11916         };
11917         const char*     accessPathV3F16[] =
11918         {
11919                 "0 0",                  // %v3f16
11920                 "0 1",
11921                 "0 2",
11922                 DE_NULL,
11923         };
11924         const char*     accessPathV4F16[] =
11925         {
11926                 "0 0",                  // %v4f16"
11927                 "0 1",
11928                 "0 2",
11929                 "0 3",
11930         };
11931         const char*     accessPathF16Arr3[] =
11932         {
11933                 "0 0",                  // %f16arr3
11934                 "0 1",
11935                 "0 2",
11936                 DE_NULL,
11937         };
11938         const char*     accessPathStruct16Arr3[] =
11939         {
11940                 "0 0 0",                // %struct16arr3
11941                 DE_NULL,
11942                 "0 0 1 0 0",
11943                 "0 0 1 0 1",
11944                 "0 0 1 1 0",
11945                 "0 0 1 1 1",
11946                 "0 0 1 2 0",
11947                 "0 0 1 2 1",
11948                 "0 1 0",
11949                 DE_NULL,
11950                 "0 1 1 0 0",
11951                 "0 1 1 0 1",
11952                 "0 1 1 1 0",
11953                 "0 1 1 1 1",
11954                 "0 1 1 2 0",
11955                 "0 1 1 2 1",
11956                 "0 2 0",
11957                 DE_NULL,
11958                 "0 2 1 0 0",
11959                 "0 2 1 0 1",
11960                 "0 2 1 1 0",
11961                 "0 2 1 1 1",
11962                 "0 2 1 2 0",
11963                 "0 2 1 2 1",
11964         };
11965         const char*     accessPathV2F16Arr5[] =
11966         {
11967                 "0 0 0",                // %v2f16arr5
11968                 "0 0 1",
11969                 "0 1 0",
11970                 "0 1 1",
11971                 "0 2 0",
11972                 "0 2 1",
11973                 "0 3 0",
11974                 "0 3 1",
11975                 "0 4 0",
11976                 "0 4 1",
11977         };
11978         const char*     accessPathV3F16Arr5[] =
11979         {
11980                 "0 0 0",                // %v3f16arr5
11981                 "0 0 1",
11982                 "0 0 2",
11983                 DE_NULL,
11984                 "0 1 0",
11985                 "0 1 1",
11986                 "0 1 2",
11987                 DE_NULL,
11988                 "0 2 0",
11989                 "0 2 1",
11990                 "0 2 2",
11991                 DE_NULL,
11992                 "0 3 0",
11993                 "0 3 1",
11994                 "0 3 2",
11995                 DE_NULL,
11996                 "0 4 0",
11997                 "0 4 1",
11998                 "0 4 2",
11999                 DE_NULL,
12000         };
12001         const char*     accessPathV4F16Arr3[] =
12002         {
12003                 "0 0 0",                // %v4f16arr3
12004                 "0 0 1",
12005                 "0 0 2",
12006                 "0 0 3",
12007                 "0 1 0",
12008                 "0 1 1",
12009                 "0 1 2",
12010                 "0 1 3",
12011                 "0 2 0",
12012                 "0 2 1",
12013                 "0 2 2",
12014                 "0 2 3",
12015                 DE_NULL,
12016                 DE_NULL,
12017                 DE_NULL,
12018                 DE_NULL,
12019         };
12020
12021         struct TypeTestParameters
12022         {
12023                 const char*             name;
12024                 size_t                  accessPathLength;
12025                 const char**    accessPath;
12026         };
12027
12028         const TypeTestParameters typeTestParameters[] =
12029         {
12030                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12031                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12032                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12033                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12034                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12035                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12036                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12037                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12038                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12039         };
12040
12041         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12042         {
12043                 const OpParts           opParts                         = opPartsArray[opIndex];
12044                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12045                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12046                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12047                 SpecResource            specResource;
12048                 map<string, string>     specs;
12049                 VulkanFeatures          features;
12050                 map<string, string>     fragments;
12051                 vector<string>          extensions;
12052                 vector<deFloat16>       inputFP16;
12053                 vector<deFloat16>       dummyFP16Output;
12054
12055                 // Generate values for input
12056                 inputFP16.reserve(structItemsCount);
12057                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12058                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12059
12060                 dummyFP16Output.resize(structItemsCount);
12061
12062                 // Generate cases for OpSwitch
12063                 {
12064                         string  caseBodies;
12065                         string  caseList;
12066
12067                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12068                                 if (accessPath[caseNdx] != DE_NULL)
12069                                 {
12070                                         map<string, string>     specCase;
12071
12072                                         specCase["case_ndx"]            = de::toString(caseNdx);
12073                                         specCase["access_path"]         = accessPath[caseNdx];
12074                                         specCase["op_args_part"]        = opParts.argsPartial;
12075                                         specCase["op_name"]                     = opName;
12076
12077                                         caseBodies      += testCaseBody.specialize(specCase);
12078                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12079                                 }
12080
12081                         specs["case_bodies"]    = caseBodies;
12082                         specs["case_list"]              = caseList;
12083                 }
12084
12085                 specs["num_elements"]                   = de::toString(structItemsCount);
12086                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12087                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12088                 specs["op_premain_decls"]               = opParts.premainDecls;
12089                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12090                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12091                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12092
12093                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12094                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
12095                 fragments["decoration"]         = decoration.specialize(specs);
12096                 fragments["pre_main"]           = preMain.specialize(specs);
12097                 fragments["testfun"]            = testFun.specialize(specs);
12098
12099                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12100                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12101                 specResource.verifyIO = compareFP16CompositeFunc;
12102
12103                 extensions.push_back("VK_KHR_16bit_storage");
12104                 extensions.push_back("VK_KHR_shader_float16_int8");
12105
12106                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12107                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12108
12109                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12110         }
12111
12112         return testGroup.release();
12113 }
12114
12115 struct fp16PerComponent
12116 {
12117         fp16PerComponent()
12118                 : flavor(0)
12119                 , floatFormat16 (-14, 15, 10, true)
12120                 , outCompCount(0)
12121                 , argCompCount(3, 0)
12122         {
12123         }
12124
12125         bool                    callOncePerComponent    ()                                                                      { return true; }
12126         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12127
12128         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12129         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12130         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12131
12132         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12133         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12134         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12135         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12136
12137         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12138         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12139
12140         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12141         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12142
12143 protected:
12144         size_t                          flavor;
12145         tcu::FloatFormat        floatFormat16;
12146         size_t                          outCompCount;
12147         vector<size_t>          argCompCount;
12148         vector<string>          flavorNames;
12149 };
12150
12151 struct fp16OpFNegate : public fp16PerComponent
12152 {
12153         template <class fp16type>
12154         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12155         {
12156                 const fp16type  x               (*in[0]);
12157                 const double    d               (x.asDouble());
12158                 const double    result  (0.0 - d);
12159
12160                 out[0] = fp16type(result).bits();
12161                 min[0] = getMin(result, getULPs(in));
12162                 max[0] = getMax(result, getULPs(in));
12163
12164                 return true;
12165         }
12166 };
12167
12168 struct fp16Round : public fp16PerComponent
12169 {
12170         fp16Round() : fp16PerComponent()
12171         {
12172                 flavorNames.push_back("Floor(x+0.5)");
12173                 flavorNames.push_back("Floor(x-0.5)");
12174                 flavorNames.push_back("RoundEven");
12175         }
12176
12177         template<class fp16type>
12178         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12179         {
12180                 const fp16type  x               (*in[0]);
12181                 const double    d               (x.asDouble());
12182                 double                  result  (0.0);
12183
12184                 switch (flavor)
12185                 {
12186                         case 0:         result = deRound(d);            break;
12187                         case 1:         result = deFloor(d - 0.5);      break;
12188                         case 2:         result = deRoundEven(d);        break;
12189                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12190                 }
12191
12192                 out[0] = fp16type(result).bits();
12193                 min[0] = getMin(result, getULPs(in));
12194                 max[0] = getMax(result, getULPs(in));
12195
12196                 return true;
12197         }
12198 };
12199
12200 struct fp16RoundEven : public fp16PerComponent
12201 {
12202         template<class fp16type>
12203         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12204         {
12205                 const fp16type  x               (*in[0]);
12206                 const double    d               (x.asDouble());
12207                 const double    result  (deRoundEven(d));
12208
12209                 out[0] = fp16type(result).bits();
12210                 min[0] = getMin(result, getULPs(in));
12211                 max[0] = getMax(result, getULPs(in));
12212
12213                 return true;
12214         }
12215 };
12216
12217 struct fp16Trunc : public fp16PerComponent
12218 {
12219         template<class fp16type>
12220         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12221         {
12222                 const fp16type  x               (*in[0]);
12223                 const double    d               (x.asDouble());
12224                 const double    result  (deTrunc(d));
12225
12226                 out[0] = fp16type(result).bits();
12227                 min[0] = getMin(result, getULPs(in));
12228                 max[0] = getMax(result, getULPs(in));
12229
12230                 return true;
12231         }
12232 };
12233
12234 struct fp16FAbs : public fp16PerComponent
12235 {
12236         template<class fp16type>
12237         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12238         {
12239                 const fp16type  x               (*in[0]);
12240                 const double    d               (x.asDouble());
12241                 const double    result  (deAbs(d));
12242
12243                 out[0] = fp16type(result).bits();
12244                 min[0] = getMin(result, getULPs(in));
12245                 max[0] = getMax(result, getULPs(in));
12246
12247                 return true;
12248         }
12249 };
12250
12251 struct fp16FSign : public fp16PerComponent
12252 {
12253         template<class fp16type>
12254         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12255         {
12256                 const fp16type  x               (*in[0]);
12257                 const double    d               (x.asDouble());
12258                 const double    result  (deSign(d));
12259
12260                 if (x.isNaN())
12261                         return false;
12262
12263                 out[0] = fp16type(result).bits();
12264                 min[0] = getMin(result, getULPs(in));
12265                 max[0] = getMax(result, getULPs(in));
12266
12267                 return true;
12268         }
12269 };
12270
12271 struct fp16Floor : public fp16PerComponent
12272 {
12273         template<class fp16type>
12274         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12275         {
12276                 const fp16type  x               (*in[0]);
12277                 const double    d               (x.asDouble());
12278                 const double    result  (deFloor(d));
12279
12280                 out[0] = fp16type(result).bits();
12281                 min[0] = getMin(result, getULPs(in));
12282                 max[0] = getMax(result, getULPs(in));
12283
12284                 return true;
12285         }
12286 };
12287
12288 struct fp16Ceil : public fp16PerComponent
12289 {
12290         template<class fp16type>
12291         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12292         {
12293                 const fp16type  x               (*in[0]);
12294                 const double    d               (x.asDouble());
12295                 const double    result  (deCeil(d));
12296
12297                 out[0] = fp16type(result).bits();
12298                 min[0] = getMin(result, getULPs(in));
12299                 max[0] = getMax(result, getULPs(in));
12300
12301                 return true;
12302         }
12303 };
12304
12305 struct fp16Fract : public fp16PerComponent
12306 {
12307         template<class fp16type>
12308         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12309         {
12310                 const fp16type  x               (*in[0]);
12311                 const double    d               (x.asDouble());
12312                 const double    result  (deFrac(d));
12313
12314                 out[0] = fp16type(result).bits();
12315                 min[0] = getMin(result, getULPs(in));
12316                 max[0] = getMax(result, getULPs(in));
12317
12318                 return true;
12319         }
12320 };
12321
12322 struct fp16Radians : public fp16PerComponent
12323 {
12324         virtual double getULPs (vector<const deFloat16*>& in)
12325         {
12326                 DE_UNREF(in);
12327
12328                 return 2.5;
12329         }
12330
12331         template<class fp16type>
12332         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12333         {
12334                 const fp16type  x               (*in[0]);
12335                 const float             d               (x.asFloat());
12336                 const float             result  (deFloatRadians(d));
12337
12338                 out[0] = fp16type(result).bits();
12339                 min[0] = getMin(result, getULPs(in));
12340                 max[0] = getMax(result, getULPs(in));
12341
12342                 return true;
12343         }
12344 };
12345
12346 struct fp16Degrees : public fp16PerComponent
12347 {
12348         virtual double getULPs (vector<const deFloat16*>& in)
12349         {
12350                 DE_UNREF(in);
12351
12352                 return 2.5;
12353         }
12354
12355         template<class fp16type>
12356         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12357         {
12358                 const fp16type  x               (*in[0]);
12359                 const float             d               (x.asFloat());
12360                 const float             result  (deFloatDegrees(d));
12361
12362                 out[0] = fp16type(result).bits();
12363                 min[0] = getMin(result, getULPs(in));
12364                 max[0] = getMax(result, getULPs(in));
12365
12366                 return true;
12367         }
12368 };
12369
12370 struct fp16Sin : public fp16PerComponent
12371 {
12372         template<class fp16type>
12373         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12374         {
12375                 const fp16type  x                       (*in[0]);
12376                 const double    d                       (x.asDouble());
12377                 const double    result          (deSin(d));
12378                 const double    unspecUlp       (16.0);
12379                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12380
12381                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12382                         return false;
12383
12384                 out[0] = fp16type(result).bits();
12385                 min[0] = result - err;
12386                 max[0] = result + err;
12387
12388                 return true;
12389         }
12390 };
12391
12392 struct fp16Cos : public fp16PerComponent
12393 {
12394         template<class fp16type>
12395         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12396         {
12397                 const fp16type  x                       (*in[0]);
12398                 const double    d                       (x.asDouble());
12399                 const double    result          (deCos(d));
12400                 const double    unspecUlp       (16.0);
12401                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12402
12403                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12404                         return false;
12405
12406                 out[0] = fp16type(result).bits();
12407                 min[0] = result - err;
12408                 max[0] = result + err;
12409
12410                 return true;
12411         }
12412 };
12413
12414 struct fp16Tan : public fp16PerComponent
12415 {
12416         template<class fp16type>
12417         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12418         {
12419                 const fp16type  x               (*in[0]);
12420                 const double    d               (x.asDouble());
12421                 const double    result  (deTan(d));
12422
12423                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12424                         return false;
12425
12426                 out[0] = fp16type(result).bits();
12427                 {
12428                         const double    err                     = deLdExp(1.0, -7);
12429                         const double    s1                      = deSin(d) + err;
12430                         const double    s2                      = deSin(d) - err;
12431                         const double    c1                      = deCos(d) + err;
12432                         const double    c2                      = deCos(d) - err;
12433                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12434                         double                  edgeLeft        = out[0];
12435                         double                  edgeRight       = out[0];
12436
12437                         if (deSign(c1 * c2) < 0.0)
12438                         {
12439                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12440                                 edgeRight       = +std::numeric_limits<double>::infinity();
12441                         }
12442                         else
12443                         {
12444                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12445                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12446                         }
12447
12448                         min[0] = edgeLeft;
12449                         max[0] = edgeRight;
12450                 }
12451
12452                 return true;
12453         }
12454 };
12455
12456 struct fp16Asin : public fp16PerComponent
12457 {
12458         template<class fp16type>
12459         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12460         {
12461                 const fp16type  x               (*in[0]);
12462                 const double    d               (x.asDouble());
12463                 const double    result  (deAsin(d));
12464                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12465
12466                 if (!x.isNaN() && deAbs(d) > 1.0)
12467                         return false;
12468
12469                 out[0] = fp16type(result).bits();
12470                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12471                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12472
12473                 return true;
12474         }
12475 };
12476
12477 struct fp16Acos : public fp16PerComponent
12478 {
12479         template<class fp16type>
12480         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12481         {
12482                 const fp16type  x               (*in[0]);
12483                 const double    d               (x.asDouble());
12484                 const double    result  (deAcos(d));
12485                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12486
12487                 if (!x.isNaN() && deAbs(d) > 1.0)
12488                         return false;
12489
12490                 out[0] = fp16type(result).bits();
12491                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12492                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12493
12494                 return true;
12495         }
12496 };
12497
12498 struct fp16Atan : public fp16PerComponent
12499 {
12500         virtual double getULPs(vector<const deFloat16*>& in)
12501         {
12502                 DE_UNREF(in);
12503
12504                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12505         }
12506
12507         template<class fp16type>
12508         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12509         {
12510                 const fp16type  x               (*in[0]);
12511                 const double    d               (x.asDouble());
12512                 const double    result  (deAtanOver(d));
12513
12514                 out[0] = fp16type(result).bits();
12515                 min[0] = getMin(result, getULPs(in));
12516                 max[0] = getMax(result, getULPs(in));
12517
12518                 return true;
12519         }
12520 };
12521
12522 struct fp16Sinh : public fp16PerComponent
12523 {
12524         fp16Sinh() : fp16PerComponent()
12525         {
12526                 flavorNames.push_back("Double");
12527                 flavorNames.push_back("ExpFP16");
12528         }
12529
12530         template<class fp16type>
12531         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12532         {
12533                 const fp16type  x               (*in[0]);
12534                 const double    d               (x.asDouble());
12535                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12536                 double                  result  (0.0);
12537                 double                  error   (0.0);
12538
12539                 if (getFlavor() == 0)
12540                 {
12541                         result  = deSinh(d);
12542                         error   = floatFormat16.ulp(deAbs(result), ulps);
12543                 }
12544                 else if (getFlavor() == 1)
12545                 {
12546                         const fp16type  epx     (deExp(d));
12547                         const fp16type  enx     (deExp(-d));
12548                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12549                         const fp16type  sx2     (esx.asDouble() / 2.0);
12550
12551                         result  = sx2.asDouble();
12552                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12553                 }
12554                 else
12555                 {
12556                         TCU_THROW(InternalError, "Unknown flavor");
12557                 }
12558
12559                 out[0] = fp16type(result).bits();
12560                 min[0] = result - error;
12561                 max[0] = result + error;
12562
12563                 return true;
12564         }
12565 };
12566
12567 struct fp16Cosh : public fp16PerComponent
12568 {
12569         fp16Cosh() : fp16PerComponent()
12570         {
12571                 flavorNames.push_back("Double");
12572                 flavorNames.push_back("ExpFP16");
12573         }
12574
12575         template<class fp16type>
12576         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12577         {
12578                 const fp16type  x               (*in[0]);
12579                 const double    d               (x.asDouble());
12580                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12581                 double                  result  (0.0);
12582
12583                 if (getFlavor() == 0)
12584                 {
12585                         result = deCosh(d);
12586                 }
12587                 else if (getFlavor() == 1)
12588                 {
12589                         const fp16type  epx     (deExp(d));
12590                         const fp16type  enx     (deExp(-d));
12591                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12592                         const fp16type  sx2     (esx.asDouble() / 2.0);
12593
12594                         result = sx2.asDouble();
12595                 }
12596                 else
12597                 {
12598                         TCU_THROW(InternalError, "Unknown flavor");
12599                 }
12600
12601                 out[0] = fp16type(result).bits();
12602                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12603                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12604
12605                 return true;
12606         }
12607 };
12608
12609 struct fp16Tanh : public fp16PerComponent
12610 {
12611         fp16Tanh() : fp16PerComponent()
12612         {
12613                 flavorNames.push_back("Tanh");
12614                 flavorNames.push_back("SinhCosh");
12615                 flavorNames.push_back("SinhCoshFP16");
12616                 flavorNames.push_back("PolyFP16");
12617         }
12618
12619         virtual double getULPs (vector<const deFloat16*>& in)
12620         {
12621                 const tcu::Float16      x       (*in[0]);
12622                 const double            d       (x.asDouble());
12623
12624                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12625         }
12626
12627         template<class fp16type>
12628         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12629         {
12630                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12631                 const fp16type  sx2     (esx.asDouble() / 2.0);
12632                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12633                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12634                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12635                 const double    rez     (tg.asDouble());
12636
12637                 return rez;
12638         }
12639
12640         template<class fp16type>
12641         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12642         {
12643                 const fp16type  x               (*in[0]);
12644                 const double    d               (x.asDouble());
12645                 double                  result  (0.0);
12646
12647                 if (getFlavor() == 0)
12648                 {
12649                         result  = deTanh(d);
12650                         min[0]  = getMin(result, getULPs(in));
12651                         max[0]  = getMax(result, getULPs(in));
12652                 }
12653                 else if (getFlavor() == 1)
12654                 {
12655                         result  = deSinh(d) / deCosh(d);
12656                         min[0]  = getMin(result, getULPs(in));
12657                         max[0]  = getMax(result, getULPs(in));
12658                 }
12659                 else if (getFlavor() == 2)
12660                 {
12661                         const fp16type  s       (deSinh(d));
12662                         const fp16type  c       (deCosh(d));
12663
12664                         result  = s.asDouble() / c.asDouble();
12665                         min[0]  = getMin(result, getULPs(in));
12666                         max[0]  = getMax(result, getULPs(in));
12667                 }
12668                 else if (getFlavor() == 3)
12669                 {
12670                         const double    ulps    (getULPs(in));
12671                         const double    epxm    (deExp( d));
12672                         const double    enxm    (deExp(-d));
12673                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12674                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12675                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12676                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12677                         const fp16type  epxm16  (epxm);
12678                         const fp16type  enxm16  (enxm);
12679                         vector<double>  tgs;
12680
12681                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12682                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12683                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12684                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12685                         {
12686                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12687
12688                                 tgs.push_back(tgh);
12689                         }
12690
12691                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12692                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12693                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12694                 }
12695                 else
12696                 {
12697                         TCU_THROW(InternalError, "Unknown flavor");
12698                 }
12699
12700                 out[0] = fp16type(result).bits();
12701
12702                 return true;
12703         }
12704 };
12705
12706 struct fp16Asinh : public fp16PerComponent
12707 {
12708         fp16Asinh() : fp16PerComponent()
12709         {
12710                 flavorNames.push_back("Double");
12711                 flavorNames.push_back("PolyFP16Wiki");
12712                 flavorNames.push_back("PolyFP16Abs");
12713         }
12714
12715         virtual double getULPs (vector<const deFloat16*>& in)
12716         {
12717                 DE_UNREF(in);
12718
12719                 return 256.0; // This is not a precision test. Value is not from spec
12720         }
12721
12722         template<class fp16type>
12723         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12724         {
12725                 const fp16type  x               (*in[0]);
12726                 const double    d               (x.asDouble());
12727                 double                  result  (0.0);
12728
12729                 if (getFlavor() == 0)
12730                 {
12731                         result = deAsinh(d);
12732                 }
12733                 else if (getFlavor() == 1)
12734                 {
12735                         const fp16type  x2              (d * d);
12736                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12737                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12738                         const fp16type  sxsq    (d + sq.asDouble());
12739                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12740
12741                         if (lsxsq.isInf())
12742                                 return false;
12743
12744                         result = lsxsq.asDouble();
12745                 }
12746                 else if (getFlavor() == 2)
12747                 {
12748                         const fp16type  x2              (d * d);
12749                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12750                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12751                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12752                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12753
12754                         result = deSign(d) * lsxsq.asDouble();
12755                 }
12756                 else
12757                 {
12758                         TCU_THROW(InternalError, "Unknown flavor");
12759                 }
12760
12761                 out[0] = fp16type(result).bits();
12762                 min[0] = getMin(result, getULPs(in));
12763                 max[0] = getMax(result, getULPs(in));
12764
12765                 return true;
12766         }
12767 };
12768
12769 struct fp16Acosh : public fp16PerComponent
12770 {
12771         fp16Acosh() : fp16PerComponent()
12772         {
12773                 flavorNames.push_back("Double");
12774                 flavorNames.push_back("PolyFP16");
12775         }
12776
12777         virtual double getULPs (vector<const deFloat16*>& in)
12778         {
12779                 DE_UNREF(in);
12780
12781                 return 16.0; // This is not a precision test. Value is not from spec
12782         }
12783
12784         template<class fp16type>
12785         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12786         {
12787                 const fp16type  x               (*in[0]);
12788                 const double    d               (x.asDouble());
12789                 double                  result  (0.0);
12790
12791                 if (!x.isNaN() && d < 1.0)
12792                         return false;
12793
12794                 if (getFlavor() == 0)
12795                 {
12796                         result = deAcosh(d);
12797                 }
12798                 else if (getFlavor() == 1)
12799                 {
12800                         const fp16type  x2              (d * d);
12801                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12802                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12803                         const fp16type  sxsq    (d + sq.asDouble());
12804                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12805
12806                         result = lsxsq.asDouble();
12807                 }
12808                 else
12809                 {
12810                         TCU_THROW(InternalError, "Unknown flavor");
12811                 }
12812
12813                 out[0] = fp16type(result).bits();
12814                 min[0] = getMin(result, getULPs(in));
12815                 max[0] = getMax(result, getULPs(in));
12816
12817                 return true;
12818         }
12819 };
12820
12821 struct fp16Atanh : public fp16PerComponent
12822 {
12823         fp16Atanh() : fp16PerComponent()
12824         {
12825                 flavorNames.push_back("Double");
12826                 flavorNames.push_back("PolyFP16");
12827         }
12828
12829         template<class fp16type>
12830         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12831         {
12832                 const fp16type  x               (*in[0]);
12833                 const double    d               (x.asDouble());
12834                 double                  result  (0.0);
12835
12836                 if (deAbs(d) >= 1.0)
12837                         return false;
12838
12839                 if (getFlavor() == 0)
12840                 {
12841                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12842
12843                         result = deAtanh(d);
12844                         min[0] = getMin(result, ulps);
12845                         max[0] = getMax(result, ulps);
12846                 }
12847                 else if (getFlavor() == 1)
12848                 {
12849                         const fp16type  x1a             (1.0 + d);
12850                         const fp16type  x1b             (1.0 - d);
12851                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
12852                         const fp16type  lx1d    (deLog(x1d.asDouble()));
12853                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
12854                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
12855
12856                         result = lx1d2.asDouble();
12857                         min[0] = result - error;
12858                         max[0] = result + error;
12859                 }
12860                 else
12861                 {
12862                         TCU_THROW(InternalError, "Unknown flavor");
12863                 }
12864
12865                 out[0] = fp16type(result).bits();
12866
12867                 return true;
12868         }
12869 };
12870
12871 struct fp16Exp : public fp16PerComponent
12872 {
12873         template<class fp16type>
12874         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12875         {
12876                 const fp16type  x               (*in[0]);
12877                 const double    d               (x.asDouble());
12878                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
12879                 const double    result  (deExp(d));
12880
12881                 out[0] = fp16type(result).bits();
12882                 min[0] = getMin(result, ulps);
12883                 max[0] = getMax(result, ulps);
12884
12885                 return true;
12886         }
12887 };
12888
12889 struct fp16Log : public fp16PerComponent
12890 {
12891         template<class fp16type>
12892         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12893         {
12894                 const fp16type  x               (*in[0]);
12895                 const double    d               (x.asDouble());
12896                 const double    result  (deLog(d));
12897                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
12898
12899                 if (d <= 0.0)
12900                         return false;
12901
12902                 out[0] = fp16type(result).bits();
12903                 min[0] = result - error;
12904                 max[0] = result + error;
12905
12906                 return true;
12907         }
12908 };
12909
12910 struct fp16Exp2 : public fp16PerComponent
12911 {
12912         template<class fp16type>
12913         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12914         {
12915                 const fp16type  x               (*in[0]);
12916                 const double    d               (x.asDouble());
12917                 const double    result  (deExp2(d));
12918                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
12919
12920                 out[0] = fp16type(result).bits();
12921                 min[0] = getMin(result, ulps);
12922                 max[0] = getMax(result, ulps);
12923
12924                 return true;
12925         }
12926 };
12927
12928 struct fp16Log2 : public fp16PerComponent
12929 {
12930         template<class fp16type>
12931         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12932         {
12933                 const fp16type  x               (*in[0]);
12934                 const double    d               (x.asDouble());
12935                 const double    result  (deLog2(d));
12936                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
12937
12938                 if (d <= 0.0)
12939                         return false;
12940
12941                 out[0] = fp16type(result).bits();
12942                 min[0] = result - error;
12943                 max[0] = result + error;
12944
12945                 return true;
12946         }
12947 };
12948
12949 struct fp16Sqrt : public fp16PerComponent
12950 {
12951         virtual double getULPs (vector<const deFloat16*>& in)
12952         {
12953                 DE_UNREF(in);
12954
12955                 return 6.0;
12956         }
12957
12958         template<class fp16type>
12959         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12960         {
12961                 const fp16type  x               (*in[0]);
12962                 const double    d               (x.asDouble());
12963                 const double    result  (deSqrt(d));
12964
12965                 if (!x.isNaN() && d < 0.0)
12966                         return false;
12967
12968                 out[0] = fp16type(result).bits();
12969                 min[0] = getMin(result, getULPs(in));
12970                 max[0] = getMax(result, getULPs(in));
12971
12972                 return true;
12973         }
12974 };
12975
12976 struct fp16InverseSqrt : public fp16PerComponent
12977 {
12978         virtual double getULPs (vector<const deFloat16*>& in)
12979         {
12980                 DE_UNREF(in);
12981
12982                 return 2.0;
12983         }
12984
12985         template<class fp16type>
12986         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12987         {
12988                 const fp16type  x               (*in[0]);
12989                 const double    d               (x.asDouble());
12990                 const double    result  (1.0/deSqrt(d));
12991
12992                 if (!x.isNaN() && d <= 0.0)
12993                         return false;
12994
12995                 out[0] = fp16type(result).bits();
12996                 min[0] = getMin(result, getULPs(in));
12997                 max[0] = getMax(result, getULPs(in));
12998
12999                 return true;
13000         }
13001 };
13002
13003 struct fp16ModfFrac : public fp16PerComponent
13004 {
13005         template<class fp16type>
13006         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13007         {
13008                 const fp16type  x               (*in[0]);
13009                 const double    d               (x.asDouble());
13010                 double                  i               (0.0);
13011                 const double    result  (deModf(d, &i));
13012
13013                 if (x.isInf() || x.isNaN())
13014                         return false;
13015
13016                 out[0] = fp16type(result).bits();
13017                 min[0] = getMin(result, getULPs(in));
13018                 max[0] = getMax(result, getULPs(in));
13019
13020                 return true;
13021         }
13022 };
13023
13024 struct fp16ModfInt : public fp16PerComponent
13025 {
13026         template<class fp16type>
13027         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13028         {
13029                 const fp16type  x               (*in[0]);
13030                 const double    d               (x.asDouble());
13031                 double                  i               (0.0);
13032                 const double    dummy   (deModf(d, &i));
13033                 const double    result  (i);
13034
13035                 DE_UNREF(dummy);
13036
13037                 if (x.isInf() || x.isNaN())
13038                         return false;
13039
13040                 out[0] = fp16type(result).bits();
13041                 min[0] = getMin(result, getULPs(in));
13042                 max[0] = getMax(result, getULPs(in));
13043
13044                 return true;
13045         }
13046 };
13047
13048 struct fp16FrexpS : public fp16PerComponent
13049 {
13050         template<class fp16type>
13051         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13052         {
13053                 const fp16type  x               (*in[0]);
13054                 const double    d               (x.asDouble());
13055                 int                             e               (0);
13056                 const double    result  (deFrExp(d, &e));
13057
13058                 if (x.isNaN() || x.isInf())
13059                         return false;
13060
13061                 out[0] = fp16type(result).bits();
13062                 min[0] = getMin(result, getULPs(in));
13063                 max[0] = getMax(result, getULPs(in));
13064
13065                 return true;
13066         }
13067 };
13068
13069 struct fp16FrexpE : public fp16PerComponent
13070 {
13071         template<class fp16type>
13072         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13073         {
13074                 const fp16type  x               (*in[0]);
13075                 const double    d               (x.asDouble());
13076                 int                             e               (0);
13077                 const double    dummy   (deFrExp(d, &e));
13078                 const double    result  (static_cast<double>(e));
13079
13080                 DE_UNREF(dummy);
13081
13082                 if (x.isNaN() || x.isInf())
13083                         return false;
13084
13085                 out[0] = fp16type(result).bits();
13086                 min[0] = getMin(result, getULPs(in));
13087                 max[0] = getMax(result, getULPs(in));
13088
13089                 return true;
13090         }
13091 };
13092
13093 struct fp16OpFAdd : public fp16PerComponent
13094 {
13095         template<class fp16type>
13096         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13097         {
13098                 const fp16type  x               (*in[0]);
13099                 const fp16type  y               (*in[1]);
13100                 const double    xd              (x.asDouble());
13101                 const double    yd              (y.asDouble());
13102                 const double    result  (xd + yd);
13103
13104                 out[0] = fp16type(result).bits();
13105                 min[0] = getMin(result, getULPs(in));
13106                 max[0] = getMax(result, getULPs(in));
13107
13108                 return true;
13109         }
13110 };
13111
13112 struct fp16OpFSub : public fp16PerComponent
13113 {
13114         template<class fp16type>
13115         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13116         {
13117                 const fp16type  x               (*in[0]);
13118                 const fp16type  y               (*in[1]);
13119                 const double    xd              (x.asDouble());
13120                 const double    yd              (y.asDouble());
13121                 const double    result  (xd - yd);
13122
13123                 out[0] = fp16type(result).bits();
13124                 min[0] = getMin(result, getULPs(in));
13125                 max[0] = getMax(result, getULPs(in));
13126
13127                 return true;
13128         }
13129 };
13130
13131 struct fp16OpFMul : public fp16PerComponent
13132 {
13133         template<class fp16type>
13134         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13135         {
13136                 const fp16type  x               (*in[0]);
13137                 const fp16type  y               (*in[1]);
13138                 const double    xd              (x.asDouble());
13139                 const double    yd              (y.asDouble());
13140                 const double    result  (xd * yd);
13141
13142                 out[0] = fp16type(result).bits();
13143                 min[0] = getMin(result, getULPs(in));
13144                 max[0] = getMax(result, getULPs(in));
13145
13146                 return true;
13147         }
13148 };
13149
13150 struct fp16OpFDiv : public fp16PerComponent
13151 {
13152         fp16OpFDiv() : fp16PerComponent()
13153         {
13154                 flavorNames.push_back("DirectDiv");
13155                 flavorNames.push_back("InverseDiv");
13156         }
13157
13158         template<class fp16type>
13159         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13160         {
13161                 const fp16type  x                       (*in[0]);
13162                 const fp16type  y                       (*in[1]);
13163                 const double    xd                      (x.asDouble());
13164                 const double    yd                      (y.asDouble());
13165                 const double    unspecUlp       (16.0);
13166                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13167                 double                  result          (0.0);
13168
13169                 if (y.isZero())
13170                         return false;
13171
13172                 if (getFlavor() == 0)
13173                 {
13174                         result = (xd / yd);
13175                 }
13176                 else if (getFlavor() == 1)
13177                 {
13178                         const double    invyd   (1.0 / yd);
13179                         const fp16type  invy    (invyd);
13180
13181                         result = (xd * invy.asDouble());
13182                 }
13183                 else
13184                 {
13185                         TCU_THROW(InternalError, "Unknown flavor");
13186                 }
13187
13188                 out[0] = fp16type(result).bits();
13189                 min[0] = getMin(result, ulpCnt);
13190                 max[0] = getMax(result, ulpCnt);
13191
13192                 return true;
13193         }
13194 };
13195
13196 struct fp16Atan2 : public fp16PerComponent
13197 {
13198         fp16Atan2() : fp16PerComponent()
13199         {
13200                 flavorNames.push_back("DoubleCalc");
13201                 flavorNames.push_back("DoubleCalc_PI");
13202         }
13203
13204         virtual double getULPs(vector<const deFloat16*>& in)
13205         {
13206                 DE_UNREF(in);
13207
13208                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13209         }
13210
13211         template<class fp16type>
13212         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13213         {
13214                 const fp16type  x               (*in[0]);
13215                 const fp16type  y               (*in[1]);
13216                 const double    xd              (x.asDouble());
13217                 const double    yd              (y.asDouble());
13218                 double                  result  (0.0);
13219
13220                 if (x.isZero() && y.isZero())
13221                         return false;
13222
13223                 if (getFlavor() == 0)
13224                 {
13225                         result  = deAtan2(xd, yd);
13226                 }
13227                 else if (getFlavor() == 1)
13228                 {
13229                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13230                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13231
13232                         result  = deAtan2(xd, yd);
13233
13234                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13235                                 result  = -result;
13236                 }
13237                 else
13238                 {
13239                         TCU_THROW(InternalError, "Unknown flavor");
13240                 }
13241
13242                 out[0] = fp16type(result).bits();
13243                 min[0] = getMin(result, getULPs(in));
13244                 max[0] = getMax(result, getULPs(in));
13245
13246                 return true;
13247         }
13248 };
13249
13250 struct fp16Pow : public fp16PerComponent
13251 {
13252         fp16Pow() : fp16PerComponent()
13253         {
13254                 flavorNames.push_back("Pow");
13255                 flavorNames.push_back("PowLog2");
13256                 flavorNames.push_back("PowLog2FP16");
13257         }
13258
13259         template<class fp16type>
13260         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13261         {
13262                 const fp16type  x               (*in[0]);
13263                 const fp16type  y               (*in[1]);
13264                 const double    xd              (x.asDouble());
13265                 const double    yd              (y.asDouble());
13266                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13267                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13268                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13269                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13270                 double                  result  (0.0);
13271
13272                 if (xd < 0.0)
13273                         return false;
13274
13275                 if (x.isZero() && yd <= 0.0)
13276                         return false;
13277
13278                 if (getFlavor() == 0)
13279                 {
13280                         result = dePow(xd, yd);
13281                 }
13282                 else if (getFlavor() == 1)
13283                 {
13284                         const double    l2d     (deLog2(xd));
13285                         const double    e2d     (deExp2(yd * l2d));
13286
13287                         result = e2d;
13288                 }
13289                 else if (getFlavor() == 2)
13290                 {
13291                         const double    l2d     (deLog2(xd));
13292                         const fp16type  l2      (l2d);
13293                         const double    e2d     (deExp2(yd * l2.asDouble()));
13294                         const fp16type  e2      (e2d);
13295
13296                         result = e2.asDouble();
13297                 }
13298                 else
13299                 {
13300                         TCU_THROW(InternalError, "Unknown flavor");
13301                 }
13302
13303                 out[0] = fp16type(result).bits();
13304                 min[0] = getMin(result, ulps);
13305                 max[0] = getMax(result, ulps);
13306
13307                 return true;
13308         }
13309 };
13310
13311 struct fp16FMin : public fp16PerComponent
13312 {
13313         template<class fp16type>
13314         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13315         {
13316                 const fp16type  x               (*in[0]);
13317                 const fp16type  y               (*in[1]);
13318                 const double    xd              (x.asDouble());
13319                 const double    yd              (y.asDouble());
13320                 const double    result  (deMin(xd, yd));
13321
13322                 if (x.isNaN() || y.isNaN())
13323                         return false;
13324
13325                 out[0] = fp16type(result).bits();
13326                 min[0] = getMin(result, getULPs(in));
13327                 max[0] = getMax(result, getULPs(in));
13328
13329                 return true;
13330         }
13331 };
13332
13333 struct fp16FMax : public fp16PerComponent
13334 {
13335         template<class fp16type>
13336         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13337         {
13338                 const fp16type  x               (*in[0]);
13339                 const fp16type  y               (*in[1]);
13340                 const double    xd              (x.asDouble());
13341                 const double    yd              (y.asDouble());
13342                 const double    result  (deMax(xd, yd));
13343
13344                 if (x.isNaN() || y.isNaN())
13345                         return false;
13346
13347                 out[0] = fp16type(result).bits();
13348                 min[0] = getMin(result, getULPs(in));
13349                 max[0] = getMax(result, getULPs(in));
13350
13351                 return true;
13352         }
13353 };
13354
13355 struct fp16Step : public fp16PerComponent
13356 {
13357         template<class fp16type>
13358         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13359         {
13360                 const fp16type  edge    (*in[0]);
13361                 const fp16type  x               (*in[1]);
13362                 const double    edged   (edge.asDouble());
13363                 const double    xd              (x.asDouble());
13364                 const double    result  (deStep(edged, xd));
13365
13366                 out[0] = fp16type(result).bits();
13367                 min[0] = getMin(result, getULPs(in));
13368                 max[0] = getMax(result, getULPs(in));
13369
13370                 return true;
13371         }
13372 };
13373
13374 struct fp16Ldexp : public fp16PerComponent
13375 {
13376         template<class fp16type>
13377         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13378         {
13379                 const fp16type  x               (*in[0]);
13380                 const fp16type  y               (*in[1]);
13381                 const double    xd              (x.asDouble());
13382                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13383                 const double    result  (deLdExp(xd, yd));
13384
13385                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13386                         return false;
13387
13388                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13389                 if (fp16type(result).isInf())
13390                         return false;
13391
13392                 out[0] = fp16type(result).bits();
13393                 min[0] = getMin(result, getULPs(in));
13394                 max[0] = getMax(result, getULPs(in));
13395
13396                 return true;
13397         }
13398 };
13399
13400 struct fp16FClamp : public fp16PerComponent
13401 {
13402         template<class fp16type>
13403         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13404         {
13405                 const fp16type  x               (*in[0]);
13406                 const fp16type  minVal  (*in[1]);
13407                 const fp16type  maxVal  (*in[2]);
13408                 const double    xd              (x.asDouble());
13409                 const double    minVald (minVal.asDouble());
13410                 const double    maxVald (maxVal.asDouble());
13411                 const double    result  (deClamp(xd, minVald, maxVald));
13412
13413                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13414                         return false;
13415
13416                 out[0] = fp16type(result).bits();
13417                 min[0] = getMin(result, getULPs(in));
13418                 max[0] = getMax(result, getULPs(in));
13419
13420                 return true;
13421         }
13422 };
13423
13424 struct fp16FMix : public fp16PerComponent
13425 {
13426         fp16FMix() : fp16PerComponent()
13427         {
13428                 flavorNames.push_back("DoubleCalc");
13429                 flavorNames.push_back("EmulatingFP16");
13430                 flavorNames.push_back("EmulatingFP16YminusX");
13431         }
13432
13433         template<class fp16type>
13434         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13435         {
13436                 const fp16type  x               (*in[0]);
13437                 const fp16type  y               (*in[1]);
13438                 const fp16type  a               (*in[2]);
13439                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13440                 double                  result  (0.0);
13441
13442                 if (getFlavor() == 0)
13443                 {
13444                         const double    xd              (x.asDouble());
13445                         const double    yd              (y.asDouble());
13446                         const double    ad              (a.asDouble());
13447                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13448                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13449                         const double    eps             (xeps + yeps);
13450
13451                         result = deMix(xd, yd, ad);
13452                         min[0] = result - eps;
13453                         max[0] = result + eps;
13454                 }
13455                 else if (getFlavor() == 1)
13456                 {
13457                         const double    xd              (x.asDouble());
13458                         const double    yd              (y.asDouble());
13459                         const double    ad              (a.asDouble());
13460                         const fp16type  am              (1.0 - ad);
13461                         const double    amd             (am.asDouble());
13462                         const fp16type  xam             (xd * amd);
13463                         const double    xamd    (xam.asDouble());
13464                         const fp16type  ya              (yd * ad);
13465                         const double    yad             (ya.asDouble());
13466                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13467                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13468                         const double    eps             (xeps + yeps);
13469
13470                         result = xamd + yad;
13471                         min[0] = result - eps;
13472                         max[0] = result + eps;
13473                 }
13474                 else if (getFlavor() == 2)
13475                 {
13476                         const double    xd              (x.asDouble());
13477                         const double    yd              (y.asDouble());
13478                         const double    ad              (a.asDouble());
13479                         const fp16type  ymx             (yd - xd);
13480                         const double    ymxd    (ymx.asDouble());
13481                         const fp16type  ymxa    (ymxd * ad);
13482                         const double    ymxad   (ymxa.asDouble());
13483                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13484                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13485                         const double    eps             (xeps + yeps);
13486
13487                         result = xd + ymxad;
13488                         min[0] = result - eps;
13489                         max[0] = result + eps;
13490                 }
13491                 else
13492                 {
13493                         TCU_THROW(InternalError, "Unknown flavor");
13494                 }
13495
13496                 out[0] = fp16type(result).bits();
13497
13498                 return true;
13499         }
13500 };
13501
13502 struct fp16SmoothStep : public fp16PerComponent
13503 {
13504         fp16SmoothStep() : fp16PerComponent()
13505         {
13506                 flavorNames.push_back("FloatCalc");
13507                 flavorNames.push_back("EmulatingFP16");
13508                 flavorNames.push_back("EmulatingFP16WClamp");
13509         }
13510
13511         virtual double getULPs(vector<const deFloat16*>& in)
13512         {
13513                 DE_UNREF(in);
13514
13515                 return 4.0; // This is not a precision test. Value is not from spec
13516         }
13517
13518         template<class fp16type>
13519         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13520         {
13521                 const fp16type  edge0   (*in[0]);
13522                 const fp16type  edge1   (*in[1]);
13523                 const fp16type  x               (*in[2]);
13524                 double                  result  (0.0);
13525
13526                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13527                         return false;
13528
13529                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13530                         return false;
13531
13532                 if (getFlavor() == 0)
13533                 {
13534                         const float     edge0d  (edge0.asFloat());
13535                         const float     edge1d  (edge1.asFloat());
13536                         const float     xd              (x.asFloat());
13537                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13538
13539                         result = sstep;
13540                 }
13541                 else if (getFlavor() == 1)
13542                 {
13543                         const double    edge0d  (edge0.asDouble());
13544                         const double    edge1d  (edge1.asDouble());
13545                         const double    xd              (x.asDouble());
13546
13547                         if (xd <= edge0d)
13548                                 result = 0.0;
13549                         else if (xd >= edge1d)
13550                                 result = 1.0;
13551                         else
13552                         {
13553                                 const fp16type  a       (xd - edge0d);
13554                                 const fp16type  b       (edge1d - edge0d);
13555                                 const fp16type  t       (a.asDouble() / b.asDouble());
13556                                 const fp16type  t2      (2.0 * t.asDouble());
13557                                 const fp16type  t3      (3.0 - t2.asDouble());
13558                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13559                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13560
13561                                 result = t5.asDouble();
13562                         }
13563                 }
13564                 else if (getFlavor() == 2)
13565                 {
13566                         const double    edge0d  (edge0.asDouble());
13567                         const double    edge1d  (edge1.asDouble());
13568                         const double    xd              (x.asDouble());
13569                         const fp16type  a       (xd - edge0d);
13570                         const fp16type  b       (edge1d - edge0d);
13571                         const fp16type  bi      (1.0 / b.asDouble());
13572                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13573                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13574                         const fp16type  t       (tc);
13575                         const fp16type  t2      (2.0 * t.asDouble());
13576                         const fp16type  t3      (3.0 - t2.asDouble());
13577                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13578                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13579
13580                         result = t5.asDouble();
13581                 }
13582                 else
13583                 {
13584                         TCU_THROW(InternalError, "Unknown flavor");
13585                 }
13586
13587                 out[0] = fp16type(result).bits();
13588                 min[0] = getMin(result, getULPs(in));
13589                 max[0] = getMax(result, getULPs(in));
13590
13591                 return true;
13592         }
13593 };
13594
13595 struct fp16Fma : public fp16PerComponent
13596 {
13597         fp16Fma()
13598         {
13599                 flavorNames.push_back("DoubleCalc");
13600                 flavorNames.push_back("EmulatingFP16");
13601         }
13602
13603         virtual double getULPs(vector<const deFloat16*>& in)
13604         {
13605                 DE_UNREF(in);
13606
13607                 return 16.0;
13608         }
13609
13610         template<class fp16type>
13611         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13612         {
13613                 DE_ASSERT(in.size() == 3);
13614                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13615                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13616                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13617                 DE_ASSERT(getOutCompCount() > 0);
13618
13619                 const fp16type  a               (*in[0]);
13620                 const fp16type  b               (*in[1]);
13621                 const fp16type  c               (*in[2]);
13622                 double                  result  (0.0);
13623
13624                 if (getFlavor() == 0)
13625                 {
13626                         const double    ad      (a.asDouble());
13627                         const double    bd      (b.asDouble());
13628                         const double    cd      (c.asDouble());
13629
13630                         result  = deMadd(ad, bd, cd);
13631                 }
13632                 else if (getFlavor() == 1)
13633                 {
13634                         const double    ad      (a.asDouble());
13635                         const double    bd      (b.asDouble());
13636                         const double    cd      (c.asDouble());
13637                         const fp16type  ab      (ad * bd);
13638                         const fp16type  r       (ab.asDouble() + cd);
13639
13640                         result  = r.asDouble();
13641                 }
13642                 else
13643                 {
13644                         TCU_THROW(InternalError, "Unknown flavor");
13645                 }
13646
13647                 out[0] = fp16type(result).bits();
13648                 min[0] = getMin(result, getULPs(in));
13649                 max[0] = getMax(result, getULPs(in));
13650
13651                 return true;
13652         }
13653 };
13654
13655
13656 struct fp16AllComponents : public fp16PerComponent
13657 {
13658         bool            callOncePerComponent    ()      { return false; }
13659 };
13660
13661 struct fp16Length : public fp16AllComponents
13662 {
13663         fp16Length() : fp16AllComponents()
13664         {
13665                 flavorNames.push_back("EmulatingFP16");
13666                 flavorNames.push_back("DoubleCalc");
13667         }
13668
13669         virtual double getULPs(vector<const deFloat16*>& in)
13670         {
13671                 DE_UNREF(in);
13672
13673                 return 4.0;
13674         }
13675
13676         template<class fp16type>
13677         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13678         {
13679                 DE_ASSERT(getOutCompCount() == 1);
13680                 DE_ASSERT(in.size() == 1);
13681
13682                 double  result  (0.0);
13683
13684                 if (getFlavor() == 0)
13685                 {
13686                         fp16type        r       (0.0);
13687
13688                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13689                         {
13690                                 const fp16type  x       (in[0][componentNdx]);
13691                                 const fp16type  q       (x.asDouble() * x.asDouble());
13692
13693                                 r = fp16type(r.asDouble() + q.asDouble());
13694                         }
13695
13696                         result = deSqrt(r.asDouble());
13697
13698                         out[0] = fp16type(result).bits();
13699                 }
13700                 else if (getFlavor() == 1)
13701                 {
13702                         double  r       (0.0);
13703
13704                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13705                         {
13706                                 const fp16type  x       (in[0][componentNdx]);
13707                                 const double    q       (x.asDouble() * x.asDouble());
13708
13709                                 r += q;
13710                         }
13711
13712                         result = deSqrt(r);
13713
13714                         out[0] = fp16type(result).bits();
13715                 }
13716                 else
13717                 {
13718                         TCU_THROW(InternalError, "Unknown flavor");
13719                 }
13720
13721                 min[0] = getMin(result, getULPs(in));
13722                 max[0] = getMax(result, getULPs(in));
13723
13724                 return true;
13725         }
13726 };
13727
13728 struct fp16Distance : public fp16AllComponents
13729 {
13730         fp16Distance() : fp16AllComponents()
13731         {
13732                 flavorNames.push_back("EmulatingFP16");
13733                 flavorNames.push_back("DoubleCalc");
13734         }
13735
13736         virtual double getULPs(vector<const deFloat16*>& in)
13737         {
13738                 DE_UNREF(in);
13739
13740                 return 4.0;
13741         }
13742
13743         template<class fp16type>
13744         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13745         {
13746                 DE_ASSERT(getOutCompCount() == 1);
13747                 DE_ASSERT(in.size() == 2);
13748                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13749
13750                 double  result  (0.0);
13751
13752                 if (getFlavor() == 0)
13753                 {
13754                         fp16type        r       (0.0);
13755
13756                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13757                         {
13758                                 const fp16type  x       (in[0][componentNdx]);
13759                                 const fp16type  y       (in[1][componentNdx]);
13760                                 const fp16type  d       (x.asDouble() - y.asDouble());
13761                                 const fp16type  q       (d.asDouble() * d.asDouble());
13762
13763                                 r = fp16type(r.asDouble() + q.asDouble());
13764                         }
13765
13766                         result = deSqrt(r.asDouble());
13767                 }
13768                 else if (getFlavor() == 1)
13769                 {
13770                         double  r       (0.0);
13771
13772                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13773                         {
13774                                 const fp16type  x       (in[0][componentNdx]);
13775                                 const fp16type  y       (in[1][componentNdx]);
13776                                 const double    d       (x.asDouble() - y.asDouble());
13777                                 const double    q       (d * d);
13778
13779                                 r += q;
13780                         }
13781
13782                         result = deSqrt(r);
13783                 }
13784                 else
13785                 {
13786                         TCU_THROW(InternalError, "Unknown flavor");
13787                 }
13788
13789                 out[0] = fp16type(result).bits();
13790                 min[0] = getMin(result, getULPs(in));
13791                 max[0] = getMax(result, getULPs(in));
13792
13793                 return true;
13794         }
13795 };
13796
13797 struct fp16Cross : public fp16AllComponents
13798 {
13799         fp16Cross() : fp16AllComponents()
13800         {
13801                 flavorNames.push_back("EmulatingFP16");
13802                 flavorNames.push_back("DoubleCalc");
13803         }
13804
13805         virtual double getULPs(vector<const deFloat16*>& in)
13806         {
13807                 DE_UNREF(in);
13808
13809                 return 4.0;
13810         }
13811
13812         template<class fp16type>
13813         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13814         {
13815                 DE_ASSERT(getOutCompCount() == 3);
13816                 DE_ASSERT(in.size() == 2);
13817                 DE_ASSERT(getArgCompCount(0) == 3);
13818                 DE_ASSERT(getArgCompCount(1) == 3);
13819
13820                 if (getFlavor() == 0)
13821                 {
13822                         const fp16type  x0              (in[0][0]);
13823                         const fp16type  x1              (in[0][1]);
13824                         const fp16type  x2              (in[0][2]);
13825                         const fp16type  y0              (in[1][0]);
13826                         const fp16type  y1              (in[1][1]);
13827                         const fp16type  y2              (in[1][2]);
13828                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13829                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13830                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13831                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13832                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13833                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13834
13835                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13836                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13837                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13838                 }
13839                 else if (getFlavor() == 1)
13840                 {
13841                         const fp16type  x0              (in[0][0]);
13842                         const fp16type  x1              (in[0][1]);
13843                         const fp16type  x2              (in[0][2]);
13844                         const fp16type  y0              (in[1][0]);
13845                         const fp16type  y1              (in[1][1]);
13846                         const fp16type  y2              (in[1][2]);
13847                         const double    x1y2    (x1.asDouble() * y2.asDouble());
13848                         const double    y1x2    (y1.asDouble() * x2.asDouble());
13849                         const double    x2y0    (x2.asDouble() * y0.asDouble());
13850                         const double    y2x0    (y2.asDouble() * x0.asDouble());
13851                         const double    x0y1    (x0.asDouble() * y1.asDouble());
13852                         const double    y0x1    (y0.asDouble() * x1.asDouble());
13853
13854                         out[0] = fp16type(x1y2 - y1x2).bits();
13855                         out[1] = fp16type(x2y0 - y2x0).bits();
13856                         out[2] = fp16type(x0y1 - y0x1).bits();
13857                 }
13858                 else
13859                 {
13860                         TCU_THROW(InternalError, "Unknown flavor");
13861                 }
13862
13863                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13864                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13865                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13866                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13867
13868                 return true;
13869         }
13870 };
13871
13872 struct fp16Normalize : public fp16AllComponents
13873 {
13874         fp16Normalize() : fp16AllComponents()
13875         {
13876                 flavorNames.push_back("EmulatingFP16");
13877                 flavorNames.push_back("DoubleCalc");
13878
13879                 // flavorNames will be extended later
13880         }
13881
13882         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
13883         {
13884                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
13885
13886                 if (argNo == 0 && argCompCount[argNo] == 0)
13887                 {
13888                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
13889                         std::vector<int>        indices;
13890
13891                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
13892                                 indices.push_back(static_cast<int>(componentNdx));
13893
13894                         m_permutations.reserve(maxPermutationsCount);
13895
13896                         permutationsFlavorStart = flavorNames.size();
13897
13898                         do
13899                         {
13900                                 tcu::UVec4      permutation;
13901                                 std::string     name            = "Permutted_";
13902
13903                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
13904                                 {
13905                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
13906                                         name += de::toString(indices[componentNdx]);
13907                                 }
13908
13909                                 m_permutations.push_back(permutation);
13910                                 flavorNames.push_back(name);
13911
13912                         } while(std::next_permutation(indices.begin(), indices.end()));
13913
13914                         permutationsFlavorEnd = flavorNames.size();
13915                 }
13916
13917                 fp16AllComponents::setArgCompCount(argNo, compCount);
13918         }
13919         virtual double getULPs(vector<const deFloat16*>& in)
13920         {
13921                 DE_UNREF(in);
13922
13923                 return 8.0;
13924         }
13925
13926         template<class fp16type>
13927         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13928         {
13929                 DE_ASSERT(in.size() == 1);
13930                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13931
13932                 if (getFlavor() == 0)
13933                 {
13934                         fp16type        r(0.0);
13935
13936                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13937                         {
13938                                 const fp16type  x       (in[0][componentNdx]);
13939                                 const fp16type  q       (x.asDouble() * x.asDouble());
13940
13941                                 r = fp16type(r.asDouble() + q.asDouble());
13942                         }
13943
13944                         r = fp16type(deSqrt(r.asDouble()));
13945
13946                         if (r.isZero())
13947                                 return false;
13948
13949                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13950                         {
13951                                 const fp16type  x       (in[0][componentNdx]);
13952
13953                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
13954                         }
13955                 }
13956                 else if (getFlavor() == 1)
13957                 {
13958                         double  r(0.0);
13959
13960                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13961                         {
13962                                 const fp16type  x       (in[0][componentNdx]);
13963                                 const double    q       (x.asDouble() * x.asDouble());
13964
13965                                 r += q;
13966                         }
13967
13968                         r = deSqrt(r);
13969
13970                         if (r == 0)
13971                                 return false;
13972
13973                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13974                         {
13975                                 const fp16type  x       (in[0][componentNdx]);
13976
13977                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
13978                         }
13979                 }
13980                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
13981                 {
13982                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
13983                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
13984                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
13985                         fp16type                        r                               (0.0);
13986
13987                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
13988                         {
13989                                 const size_t    componentNdx    (permutation[permComponentNdx]);
13990                                 const fp16type  x                               (in[0][componentNdx]);
13991                                 const fp16type  q                               (x.asDouble() * x.asDouble());
13992
13993                                 r = fp16type(r.asDouble() + q.asDouble());
13994                         }
13995
13996                         r = fp16type(deSqrt(r.asDouble()));
13997
13998                         if (r.isZero())
13999                                 return false;
14000
14001                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14002                         {
14003                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14004                                 const fp16type  x                               (in[0][componentNdx]);
14005
14006                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14007                         }
14008                 }
14009                 else
14010                 {
14011                         TCU_THROW(InternalError, "Unknown flavor");
14012                 }
14013
14014                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14015                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14016                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14017                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14018
14019                 return true;
14020         }
14021
14022 private:
14023         std::vector<tcu::UVec4> m_permutations;
14024         size_t                                  permutationsFlavorStart;
14025         size_t                                  permutationsFlavorEnd;
14026 };
14027
14028 struct fp16FaceForward : public fp16AllComponents
14029 {
14030         virtual double getULPs(vector<const deFloat16*>& in)
14031         {
14032                 DE_UNREF(in);
14033
14034                 return 4.0;
14035         }
14036
14037         template<class fp16type>
14038         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14039         {
14040                 DE_ASSERT(in.size() == 3);
14041                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14042                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14043                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14044
14045                 fp16type        dp(0.0);
14046
14047                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14048                 {
14049                         const fp16type  x       (in[1][componentNdx]);
14050                         const fp16type  y       (in[2][componentNdx]);
14051                         const double    xd      (x.asDouble());
14052                         const double    yd      (y.asDouble());
14053                         const fp16type  q       (xd * yd);
14054
14055                         dp = fp16type(dp.asDouble() + q.asDouble());
14056                 }
14057
14058                 if (dp.isNaN() || dp.isZero())
14059                         return false;
14060
14061                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14062                 {
14063                         const fp16type  n       (in[0][componentNdx]);
14064
14065                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14066                 }
14067
14068                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14069                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14070                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14071                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14072
14073                 return true;
14074         }
14075 };
14076
14077 struct fp16Reflect : public fp16AllComponents
14078 {
14079         fp16Reflect() : fp16AllComponents()
14080         {
14081                 flavorNames.push_back("EmulatingFP16");
14082                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14083                 flavorNames.push_back("FloatCalc");
14084                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14085                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14086                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14087         }
14088
14089         virtual double getULPs(vector<const deFloat16*>& in)
14090         {
14091                 DE_UNREF(in);
14092
14093                 return 256.0; // This is not a precision test. Value is not from spec
14094         }
14095
14096         template<class fp16type>
14097         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14098         {
14099                 DE_ASSERT(in.size() == 2);
14100                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14101                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14102
14103                 if (getFlavor() < 4)
14104                 {
14105                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14106                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14107
14108                         if (floatCalc)
14109                         {
14110                                 float   dp(0.0f);
14111
14112                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14113                                 {
14114                                         const fp16type  i       (in[0][componentNdx]);
14115                                         const fp16type  n       (in[1][componentNdx]);
14116                                         const float             id      (i.asFloat());
14117                                         const float             nd      (n.asFloat());
14118                                         const float             qd      (id * nd);
14119
14120                                         if (keepZeroSign)
14121                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14122                                         else
14123                                                 dp = dp + qd;
14124                                 }
14125
14126                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14127                                 {
14128                                         const fp16type  i               (in[0][componentNdx]);
14129                                         const fp16type  n               (in[1][componentNdx]);
14130                                         const float             dpnd    (dp * n.asFloat());
14131                                         const float             dpn2d   (2.0f * dpnd);
14132                                         const float             idpn2d  (i.asFloat() - dpn2d);
14133                                         const fp16type  result  (idpn2d);
14134
14135                                         out[componentNdx] = result.bits();
14136                                 }
14137                         }
14138                         else
14139                         {
14140                                 fp16type        dp(0.0);
14141
14142                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14143                                 {
14144                                         const fp16type  i       (in[0][componentNdx]);
14145                                         const fp16type  n       (in[1][componentNdx]);
14146                                         const double    id      (i.asDouble());
14147                                         const double    nd      (n.asDouble());
14148                                         const fp16type  q       (id * nd);
14149
14150                                         if (keepZeroSign)
14151                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14152                                         else
14153                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14154                                 }
14155
14156                                 if (dp.isNaN())
14157                                         return false;
14158
14159                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14160                                 {
14161                                         const fp16type  i               (in[0][componentNdx]);
14162                                         const fp16type  n               (in[1][componentNdx]);
14163                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14164                                         const fp16type  dpn2    (2 * dpn.asDouble());
14165                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14166
14167                                         out[componentNdx] = idpn2.bits();
14168                                 }
14169                         }
14170                 }
14171                 else if (getFlavor() == 4)
14172                 {
14173                         fp16type        dp(0.0);
14174
14175                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14176                         {
14177                                 const fp16type  i       (in[0][componentNdx]);
14178                                 const fp16type  n       (in[1][componentNdx]);
14179                                 const double    id      (i.asDouble());
14180                                 const double    nd      (n.asDouble());
14181                                 const fp16type  q       (id * nd);
14182
14183                                 dp = fp16type(dp.asDouble() + q.asDouble());
14184                         }
14185
14186                         if (dp.isNaN())
14187                                 return false;
14188
14189                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14190                         {
14191                                 const fp16type  i               (in[0][componentNdx]);
14192                                 const fp16type  n               (in[1][componentNdx]);
14193                                 const fp16type  n2              (2 * n.asDouble());
14194                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14195                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14196
14197                                 out[componentNdx] = idpn2.bits();
14198                         }
14199                 }
14200                 else if (getFlavor() == 5)
14201                 {
14202                         fp16type        dp2(0.0);
14203
14204                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14205                         {
14206                                 const fp16type  i       (in[0][componentNdx]);
14207                                 const fp16type  n       (in[1][componentNdx]);
14208                                 const fp16type  i2      (2.0 * i.asDouble());
14209                                 const double    i2d     (i2.asDouble());
14210                                 const double    nd      (n.asDouble());
14211                                 const fp16type  q       (i2d * nd);
14212
14213                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14214                         }
14215
14216                         if (dp2.isNaN())
14217                                 return false;
14218
14219                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14220                         {
14221                                 const fp16type  i               (in[0][componentNdx]);
14222                                 const fp16type  n               (in[1][componentNdx]);
14223                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14224                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14225
14226                                 out[componentNdx] = idpn2.bits();
14227                         }
14228                 }
14229                 else
14230                 {
14231                         TCU_THROW(InternalError, "Unknown flavor");
14232                 }
14233
14234                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14235                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14236                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14237                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14238
14239                 return true;
14240         }
14241 };
14242
14243 struct fp16Refract : public fp16AllComponents
14244 {
14245         fp16Refract() : fp16AllComponents()
14246         {
14247                 flavorNames.push_back("EmulatingFP16");
14248                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14249                 flavorNames.push_back("FloatCalc");
14250                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14251         }
14252
14253         virtual double getULPs(vector<const deFloat16*>& in)
14254         {
14255                 DE_UNREF(in);
14256
14257                 return 8192.0; // This is not a precision test. Value is not from spec
14258         }
14259
14260         template<class fp16type>
14261         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14262         {
14263                 DE_ASSERT(in.size() == 3);
14264                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14265                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14266                 DE_ASSERT(getArgCompCount(2) == 1);
14267
14268                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14269                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14270                 const fp16type  eta                             (*in[2]);
14271
14272                 if (doubleCalc)
14273                 {
14274                         double  dp      (0.0);
14275
14276                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14277                         {
14278                                 const fp16type  i       (in[0][componentNdx]);
14279                                 const fp16type  n       (in[1][componentNdx]);
14280                                 const double    id      (i.asDouble());
14281                                 const double    nd      (n.asDouble());
14282                                 const double    qd      (id * nd);
14283
14284                                 if (keepZeroSign)
14285                                         dp = (componentNdx == 0) ? qd : dp + qd;
14286                                 else
14287                                         dp = dp + qd;
14288                         }
14289
14290                         const double    eta2    (eta.asDouble() * eta.asDouble());
14291                         const double    dp2             (dp * dp);
14292                         const double    dp1             (1.0 - dp2);
14293                         const double    dpe             (eta2 * dp1);
14294                         const double    k               (1.0 - dpe);
14295
14296                         if (k < 0.0)
14297                         {
14298                                 const fp16type  zero    (0.0);
14299
14300                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14301                                         out[componentNdx] = zero.bits();
14302                         }
14303                         else
14304                         {
14305                                 const double    sk      (deSqrt(k));
14306
14307                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14308                                 {
14309                                         const fp16type  i               (in[0][componentNdx]);
14310                                         const fp16type  n               (in[1][componentNdx]);
14311                                         const double    etai    (i.asDouble() * eta.asDouble());
14312                                         const double    etadp   (eta.asDouble() * dp);
14313                                         const double    etadpk  (etadp + sk);
14314                                         const double    etadpkn (etadpk * n.asDouble());
14315                                         const double    full    (etai - etadpkn);
14316                                         const fp16type  result  (full);
14317
14318                                         if (result.isInf())
14319                                                 return false;
14320
14321                                         out[componentNdx] = result.bits();
14322                                 }
14323                         }
14324                 }
14325                 else
14326                 {
14327                         fp16type        dp      (0.0);
14328
14329                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14330                         {
14331                                 const fp16type  i       (in[0][componentNdx]);
14332                                 const fp16type  n       (in[1][componentNdx]);
14333                                 const double    id      (i.asDouble());
14334                                 const double    nd      (n.asDouble());
14335                                 const fp16type  q       (id * nd);
14336
14337                                 if (keepZeroSign)
14338                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14339                                 else
14340                                         dp = fp16type(dp.asDouble() + q.asDouble());
14341                         }
14342
14343                         if (dp.isNaN())
14344                                 return false;
14345
14346                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14347                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14348                         const fp16type  dp1     (1.0 - dp2.asDouble());
14349                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14350                         const fp16type  k       (1.0 - dpe.asDouble());
14351
14352                         if (k.asDouble() < 0.0)
14353                         {
14354                                 const fp16type  zero    (0.0);
14355
14356                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14357                                         out[componentNdx] = zero.bits();
14358                         }
14359                         else
14360                         {
14361                                 const fp16type  sk      (deSqrt(k.asDouble()));
14362
14363                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14364                                 {
14365                                         const fp16type  i               (in[0][componentNdx]);
14366                                         const fp16type  n               (in[1][componentNdx]);
14367                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14368                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14369                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14370                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14371                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14372
14373                                         if (full.isNaN() || full.isInf())
14374                                                 return false;
14375
14376                                         out[componentNdx] = full.bits();
14377                                 }
14378                         }
14379                 }
14380
14381                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14382                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14383                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14384                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14385
14386                 return true;
14387         }
14388 };
14389
14390 struct fp16Dot : public fp16AllComponents
14391 {
14392         fp16Dot() : fp16AllComponents()
14393         {
14394                 flavorNames.push_back("EmulatingFP16");
14395                 flavorNames.push_back("FloatCalc");
14396                 flavorNames.push_back("DoubleCalc");
14397
14398                 // flavorNames will be extended later
14399         }
14400
14401         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14402         {
14403                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14404
14405                 if (argNo == 0 && argCompCount[argNo] == 0)
14406                 {
14407                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14408                         std::vector<int>        indices;
14409
14410                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14411                                 indices.push_back(static_cast<int>(componentNdx));
14412
14413                         m_permutations.reserve(maxPermutationsCount);
14414
14415                         permutationsFlavorStart = flavorNames.size();
14416
14417                         do
14418                         {
14419                                 tcu::UVec4      permutation;
14420                                 std::string     name            = "Permutted_";
14421
14422                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14423                                 {
14424                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14425                                         name += de::toString(indices[componentNdx]);
14426                                 }
14427
14428                                 m_permutations.push_back(permutation);
14429                                 flavorNames.push_back(name);
14430
14431                         } while(std::next_permutation(indices.begin(), indices.end()));
14432
14433                         permutationsFlavorEnd = flavorNames.size();
14434                 }
14435
14436                 fp16AllComponents::setArgCompCount(argNo, compCount);
14437         }
14438
14439         virtual double  getULPs(vector<const deFloat16*>& in)
14440         {
14441                 DE_UNREF(in);
14442
14443                 return 16.0; // This is not a precision test. Value is not from spec
14444         }
14445
14446         template<class fp16type>
14447         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14448         {
14449                 DE_ASSERT(in.size() == 2);
14450                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14451                 DE_ASSERT(getOutCompCount() == 1);
14452
14453                 double  result  (0.0);
14454                 double  eps             (0.0);
14455
14456                 if (getFlavor() == 0)
14457                 {
14458                         fp16type        dp      (0.0);
14459
14460                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14461                         {
14462                                 const fp16type  x       (in[0][componentNdx]);
14463                                 const fp16type  y       (in[1][componentNdx]);
14464                                 const fp16type  q       (x.asDouble() * y.asDouble());
14465
14466                                 dp = fp16type(dp.asDouble() + q.asDouble());
14467                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14468                         }
14469
14470                         result = dp.asDouble();
14471                 }
14472                 else if (getFlavor() == 1)
14473                 {
14474                         float   dp      (0.0);
14475
14476                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14477                         {
14478                                 const fp16type  x       (in[0][componentNdx]);
14479                                 const fp16type  y       (in[1][componentNdx]);
14480                                 const float             q       (x.asFloat() * y.asFloat());
14481
14482                                 dp += q;
14483                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14484                         }
14485
14486                         result = dp;
14487                 }
14488                 else if (getFlavor() == 2)
14489                 {
14490                         double  dp      (0.0);
14491
14492                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14493                         {
14494                                 const fp16type  x       (in[0][componentNdx]);
14495                                 const fp16type  y       (in[1][componentNdx]);
14496                                 const double    q       (x.asDouble() * y.asDouble());
14497
14498                                 dp += q;
14499                                 eps += floatFormat16.ulp(q, 2.0);
14500                         }
14501
14502                         result = dp;
14503                 }
14504                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14505                 {
14506                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14507                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14508                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14509                         fp16type                        dp                              (0.0);
14510
14511                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14512                         {
14513                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14514                                 const fp16type          x                               (in[0][componentNdx]);
14515                                 const fp16type          y                               (in[1][componentNdx]);
14516                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14517
14518                                 dp = fp16type(dp.asDouble() + q.asDouble());
14519                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14520                         }
14521
14522                         result = dp.asDouble();
14523                 }
14524                 else
14525                 {
14526                         TCU_THROW(InternalError, "Unknown flavor");
14527                 }
14528
14529                 out[0] = fp16type(result).bits();
14530                 min[0] = result - eps;
14531                 max[0] = result + eps;
14532
14533                 return true;
14534         }
14535
14536 private:
14537         std::vector<tcu::UVec4> m_permutations;
14538         size_t                                  permutationsFlavorStart;
14539         size_t                                  permutationsFlavorEnd;
14540 };
14541
14542 struct fp16VectorTimesScalar : public fp16AllComponents
14543 {
14544         virtual double getULPs(vector<const deFloat16*>& in)
14545         {
14546                 DE_UNREF(in);
14547
14548                 return 2.0;
14549         }
14550
14551         template<class fp16type>
14552         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14553         {
14554                 DE_ASSERT(in.size() == 2);
14555                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14556                 DE_ASSERT(getArgCompCount(1) == 1);
14557
14558                 fp16type        s       (*in[1]);
14559
14560                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14561                 {
14562                         const fp16type  x          (in[0][componentNdx]);
14563                         const double    result (s.asDouble() * x.asDouble());
14564                         const fp16type  m          (result);
14565
14566                         out[componentNdx] = m.bits();
14567                         min[componentNdx] = getMin(result, getULPs(in));
14568                         max[componentNdx] = getMax(result, getULPs(in));
14569                 }
14570
14571                 return true;
14572         }
14573 };
14574
14575 struct fp16MatrixBase : public fp16AllComponents
14576 {
14577         deUint32                getComponentValidity                    ()
14578         {
14579                 return static_cast<deUint32>(-1);
14580         }
14581
14582         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14583         {
14584                 const size_t minComponentCount  = 0;
14585                 const size_t maxComponentCount  = 3;
14586                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14587
14588                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14589                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14590                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14591                 DE_UNREF(minComponentCount);
14592                 DE_UNREF(maxComponentCount);
14593
14594                 return col * alignedRowsCount + row;
14595         }
14596
14597         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14598         {
14599                 deUint32        result  = 0u;
14600
14601                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14602                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14603                         {
14604                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14605
14606                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14607
14608                                 result |= (1<<bitNdx);
14609                         }
14610
14611                 return result;
14612         }
14613 };
14614
14615 template<size_t cols, size_t rows>
14616 struct fp16Transpose : public fp16MatrixBase
14617 {
14618         virtual double getULPs(vector<const deFloat16*>& in)
14619         {
14620                 DE_UNREF(in);
14621
14622                 return 1.0;
14623         }
14624
14625         deUint32        getComponentValidity    ()
14626         {
14627                 return getComponentMatrixValidityMask(rows, cols);
14628         }
14629
14630         template<class fp16type>
14631         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14632         {
14633                 DE_ASSERT(in.size() == 1);
14634
14635                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14636                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14637                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14638
14639                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14640
14641                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14642                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14643                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14644
14645                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14646                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14647                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14648
14649                 return true;
14650         }
14651 };
14652
14653 template<size_t cols, size_t rows>
14654 struct fp16MatrixTimesScalar : public fp16MatrixBase
14655 {
14656         virtual double getULPs(vector<const deFloat16*>& in)
14657         {
14658                 DE_UNREF(in);
14659
14660                 return 4.0;
14661         }
14662
14663         deUint32        getComponentValidity    ()
14664         {
14665                 return getComponentMatrixValidityMask(cols, rows);
14666         }
14667
14668         template<class fp16type>
14669         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14670         {
14671                 DE_ASSERT(in.size() == 2);
14672                 DE_ASSERT(getArgCompCount(1) == 1);
14673
14674                 const fp16type  y                       (in[1][0]);
14675                 const float             scalar          (y.asFloat());
14676                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14677                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14678
14679                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14680                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14681                 DE_UNREF(alignedCols);
14682
14683                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14684                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14685                         {
14686                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14687                                 const fp16type  x       (in[0][ndx]);
14688                                 const double    result  (scalar * x.asFloat());
14689
14690                                 out[ndx] = fp16type(result).bits();
14691                                 min[ndx] = getMin(result, getULPs(in));
14692                                 max[ndx] = getMax(result, getULPs(in));
14693                         }
14694
14695                 return true;
14696         }
14697 };
14698
14699 template<size_t cols, size_t rows>
14700 struct fp16VectorTimesMatrix : public fp16MatrixBase
14701 {
14702         fp16VectorTimesMatrix() : fp16MatrixBase()
14703         {
14704                 flavorNames.push_back("EmulatingFP16");
14705                 flavorNames.push_back("FloatCalc");
14706         }
14707
14708         virtual double getULPs (vector<const deFloat16*>& in)
14709         {
14710                 DE_UNREF(in);
14711
14712                 return (8.0 * cols);
14713         }
14714
14715         deUint32 getComponentValidity ()
14716         {
14717                 return getComponentMatrixValidityMask(cols, 1);
14718         }
14719
14720         template<class fp16type>
14721         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14722         {
14723                 DE_ASSERT(in.size() == 2);
14724
14725                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14726                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14727
14728                 DE_ASSERT(getOutCompCount() == cols);
14729                 DE_ASSERT(getArgCompCount(0) == rows);
14730                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14731                 DE_UNREF(alignedCols);
14732
14733                 if (getFlavor() == 0)
14734                 {
14735                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14736                         {
14737                                 fp16type        s       (fp16type::zero(1));
14738
14739                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14740                                 {
14741                                         const fp16type  v       (in[0][rowNdx]);
14742                                         const float             vf      (v.asFloat());
14743                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14744                                         const fp16type  x       (in[1][ndx]);
14745                                         const float             xf      (x.asFloat());
14746                                         const fp16type  m       (vf * xf);
14747
14748                                         s = fp16type(s.asFloat() + m.asFloat());
14749                                 }
14750
14751                                 out[colNdx] = s.bits();
14752                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14753                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14754                         }
14755                 }
14756                 else if (getFlavor() == 1)
14757                 {
14758                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14759                         {
14760                                 float   s       (0.0f);
14761
14762                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14763                                 {
14764                                         const fp16type  v       (in[0][rowNdx]);
14765                                         const float             vf      (v.asFloat());
14766                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14767                                         const fp16type  x       (in[1][ndx]);
14768                                         const float             xf      (x.asFloat());
14769                                         const float             m       (vf * xf);
14770
14771                                         s += m;
14772                                 }
14773
14774                                 out[colNdx] = fp16type(s).bits();
14775                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14776                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14777                         }
14778                 }
14779                 else
14780                 {
14781                         TCU_THROW(InternalError, "Unknown flavor");
14782                 }
14783
14784                 return true;
14785         }
14786 };
14787
14788 template<size_t cols, size_t rows>
14789 struct fp16MatrixTimesVector : public fp16MatrixBase
14790 {
14791         fp16MatrixTimesVector() : fp16MatrixBase()
14792         {
14793                 flavorNames.push_back("EmulatingFP16");
14794                 flavorNames.push_back("FloatCalc");
14795         }
14796
14797         virtual double getULPs (vector<const deFloat16*>& in)
14798         {
14799                 DE_UNREF(in);
14800
14801                 return (8.0 * rows);
14802         }
14803
14804         deUint32 getComponentValidity ()
14805         {
14806                 return getComponentMatrixValidityMask(rows, 1);
14807         }
14808
14809         template<class fp16type>
14810         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14811         {
14812                 DE_ASSERT(in.size() == 2);
14813
14814                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14815                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14816
14817                 DE_ASSERT(getOutCompCount() == rows);
14818                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14819                 DE_ASSERT(getArgCompCount(1) == cols);
14820                 DE_UNREF(alignedCols);
14821
14822                 if (getFlavor() == 0)
14823                 {
14824                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14825                         {
14826                                 fp16type        s       (fp16type::zero(1));
14827
14828                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14829                                 {
14830                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14831                                         const fp16type  x       (in[0][ndx]);
14832                                         const float             xf      (x.asFloat());
14833                                         const fp16type  v       (in[1][colNdx]);
14834                                         const float             vf      (v.asFloat());
14835                                         const fp16type  m       (vf * xf);
14836
14837                                         s = fp16type(s.asFloat() + m.asFloat());
14838                                 }
14839
14840                                 out[rowNdx] = s.bits();
14841                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14842                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14843                         }
14844                 }
14845                 else if (getFlavor() == 1)
14846                 {
14847                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14848                         {
14849                                 float   s       (0.0f);
14850
14851                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14852                                 {
14853                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14854                                         const fp16type  x       (in[0][ndx]);
14855                                         const float             xf      (x.asFloat());
14856                                         const fp16type  v       (in[1][colNdx]);
14857                                         const float             vf      (v.asFloat());
14858                                         const float             m       (vf * xf);
14859
14860                                         s += m;
14861                                 }
14862
14863                                 out[rowNdx] = fp16type(s).bits();
14864                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
14865                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
14866                         }
14867                 }
14868                 else
14869                 {
14870                         TCU_THROW(InternalError, "Unknown flavor");
14871                 }
14872
14873                 return true;
14874         }
14875 };
14876
14877 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
14878 struct fp16MatrixTimesMatrix : public fp16MatrixBase
14879 {
14880         fp16MatrixTimesMatrix() : fp16MatrixBase()
14881         {
14882                 flavorNames.push_back("EmulatingFP16");
14883                 flavorNames.push_back("FloatCalc");
14884         }
14885
14886         virtual double getULPs (vector<const deFloat16*>& in)
14887         {
14888                 DE_UNREF(in);
14889
14890                 return 32.0;
14891         }
14892
14893         deUint32 getComponentValidity ()
14894         {
14895                 return getComponentMatrixValidityMask(colsR, rowsL);
14896         }
14897
14898         template<class fp16type>
14899         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14900         {
14901                 DE_STATIC_ASSERT(colsL == rowsR);
14902
14903                 DE_ASSERT(in.size() == 2);
14904
14905                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
14906                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
14907                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
14908                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
14909
14910                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
14911                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
14912                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
14913                 DE_UNREF(alignedColsL);
14914                 DE_UNREF(alignedColsR);
14915
14916                 if (getFlavor() == 0)
14917                 {
14918                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
14919                         {
14920                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
14921                                 {
14922                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
14923                                         fp16type                s       (fp16type::zero(1));
14924
14925                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
14926                                         {
14927                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
14928                                                 const fp16type  l               (in[0][ndxl]);
14929                                                 const float             lf              (l.asFloat());
14930                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
14931                                                 const fp16type  r               (in[1][ndxr]);
14932                                                 const float             rf              (r.asFloat());
14933                                                 const fp16type  m               (lf * rf);
14934
14935                                                 s = fp16type(s.asFloat() + m.asFloat());
14936                                         }
14937
14938                                         out[ndx] = s.bits();
14939                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
14940                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
14941                                 }
14942                         }
14943                 }
14944                 else if (getFlavor() == 1)
14945                 {
14946                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
14947                         {
14948                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
14949                                 {
14950                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
14951                                         float                   s       (0.0f);
14952
14953                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
14954                                         {
14955                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
14956                                                 const fp16type  l               (in[0][ndxl]);
14957                                                 const float             lf              (l.asFloat());
14958                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
14959                                                 const fp16type  r               (in[1][ndxr]);
14960                                                 const float             rf              (r.asFloat());
14961                                                 const float             m               (lf * rf);
14962
14963                                                 s += m;
14964                                         }
14965
14966                                         out[ndx] = fp16type(s).bits();
14967                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
14968                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
14969                                 }
14970                         }
14971                 }
14972                 else
14973                 {
14974                         TCU_THROW(InternalError, "Unknown flavor");
14975                 }
14976
14977                 return true;
14978         }
14979 };
14980
14981 template<size_t cols, size_t rows>
14982 struct fp16OuterProduct : public fp16MatrixBase
14983 {
14984         virtual double getULPs (vector<const deFloat16*>& in)
14985         {
14986                 DE_UNREF(in);
14987
14988                 return 2.0;
14989         }
14990
14991         deUint32 getComponentValidity ()
14992         {
14993                 return getComponentMatrixValidityMask(cols, rows);
14994         }
14995
14996         template<class fp16type>
14997         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14998         {
14999                 DE_ASSERT(in.size() == 2);
15000
15001                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15002                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15003
15004                 DE_ASSERT(getArgCompCount(0) == rows);
15005                 DE_ASSERT(getArgCompCount(1) == cols);
15006                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15007                 DE_UNREF(alignedCols);
15008
15009                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15010                 {
15011                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15012                         {
15013                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15014                                 const fp16type  x       (in[0][rowNdx]);
15015                                 const float             xf      (x.asFloat());
15016                                 const fp16type  y       (in[1][colNdx]);
15017                                 const float             yf      (y.asFloat());
15018                                 const fp16type  m       (xf * yf);
15019
15020                                 out[ndx] = m.bits();
15021                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15022                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15023                         }
15024                 }
15025
15026                 return true;
15027         }
15028 };
15029
15030 template<size_t size>
15031 struct fp16Determinant;
15032
15033 template<>
15034 struct fp16Determinant<2> : public fp16MatrixBase
15035 {
15036         virtual double getULPs (vector<const deFloat16*>& in)
15037         {
15038                 DE_UNREF(in);
15039
15040                 return 128.0; // This is not a precision test. Value is not from spec
15041         }
15042
15043         deUint32 getComponentValidity ()
15044         {
15045                 return 1;
15046         }
15047
15048         template<class fp16type>
15049         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15050         {
15051                 const size_t    cols            = 2;
15052                 const size_t    rows            = 2;
15053                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15054                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15055
15056                 DE_ASSERT(in.size() == 1);
15057                 DE_ASSERT(getOutCompCount() == 1);
15058                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15059                 DE_UNREF(alignedCols);
15060                 DE_UNREF(alignedRows);
15061
15062                 // [ a b ]
15063                 // [ c d ]
15064                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15065                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15066                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15067                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15068                 const float             ad              (a * d);
15069                 const fp16type  adf16   (ad);
15070                 const float             bc              (b * c);
15071                 const fp16type  bcf16   (bc);
15072                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15073                 const fp16type  rf16    (r);
15074
15075                 out[0] = rf16.bits();
15076                 min[0] = getMin(r, getULPs(in));
15077                 max[0] = getMax(r, getULPs(in));
15078
15079                 return true;
15080         }
15081 };
15082
15083 template<>
15084 struct fp16Determinant<3> : public fp16MatrixBase
15085 {
15086         virtual double getULPs (vector<const deFloat16*>& in)
15087         {
15088                 DE_UNREF(in);
15089
15090                 return 128.0; // This is not a precision test. Value is not from spec
15091         }
15092
15093         deUint32 getComponentValidity ()
15094         {
15095                 return 1;
15096         }
15097
15098         template<class fp16type>
15099         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15100         {
15101                 const size_t    cols            = 3;
15102                 const size_t    rows            = 3;
15103                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15104                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15105
15106                 DE_ASSERT(in.size() == 1);
15107                 DE_ASSERT(getOutCompCount() == 1);
15108                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15109                 DE_UNREF(alignedCols);
15110                 DE_UNREF(alignedRows);
15111
15112                 // [ a b c ]
15113                 // [ d e f ]
15114                 // [ g h i ]
15115                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15116                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15117                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15118                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15119                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15120                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15121                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15122                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15123                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15124                 const fp16type  aei             (a * e * i);
15125                 const fp16type  bfg             (b * f * g);
15126                 const fp16type  cdh             (c * d * h);
15127                 const fp16type  ceg             (c * e * g);
15128                 const fp16type  bdi             (b * d * i);
15129                 const fp16type  afh             (a * f * h);
15130                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15131                 const fp16type  rf16    (r);
15132
15133                 out[0] = rf16.bits();
15134                 min[0] = getMin(r, getULPs(in));
15135                 max[0] = getMax(r, getULPs(in));
15136
15137                 return true;
15138         }
15139 };
15140
15141 template<>
15142 struct fp16Determinant<4> : public fp16MatrixBase
15143 {
15144         virtual double getULPs (vector<const deFloat16*>& in)
15145         {
15146                 DE_UNREF(in);
15147
15148                 return 128.0; // This is not a precision test. Value is not from spec
15149         }
15150
15151         deUint32 getComponentValidity ()
15152         {
15153                 return 1;
15154         }
15155
15156         template<class fp16type>
15157         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15158         {
15159                 const size_t    rows            = 4;
15160                 const size_t    cols            = 4;
15161                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15162                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15163
15164                 DE_ASSERT(in.size() == 1);
15165                 DE_ASSERT(getOutCompCount() == 1);
15166                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15167                 DE_UNREF(alignedCols);
15168                 DE_UNREF(alignedRows);
15169
15170                 // [ a b c d ]
15171                 // [ e f g h ]
15172                 // [ i j k l ]
15173                 // [ m n o p ]
15174                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15175                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15176                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15177                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15178                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15179                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15180                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15181                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15182                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15183                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15184                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15185                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15186                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15187                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15188                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15189                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15190
15191                 // [ f g h ]
15192                 // [ j k l ]
15193                 // [ n o p ]
15194                 const fp16type  fkp             (f * k * p);
15195                 const fp16type  gln             (g * l * n);
15196                 const fp16type  hjo             (h * j * o);
15197                 const fp16type  hkn             (h * k * n);
15198                 const fp16type  gjp             (g * j * p);
15199                 const fp16type  flo             (f * l * o);
15200                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15201
15202                 // [ e g h ]
15203                 // [ i k l ]
15204                 // [ m o p ]
15205                 const fp16type  ekp             (e * k * p);
15206                 const fp16type  glm             (g * l * m);
15207                 const fp16type  hio             (h * i * o);
15208                 const fp16type  hkm             (h * k * m);
15209                 const fp16type  gip             (g * i * p);
15210                 const fp16type  elo             (e * l * o);
15211                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15212
15213                 // [ e f h ]
15214                 // [ i j l ]
15215                 // [ m n p ]
15216                 const fp16type  ejp             (e * j * p);
15217                 const fp16type  flm             (f * l * m);
15218                 const fp16type  hin             (h * i * n);
15219                 const fp16type  hjm             (h * j * m);
15220                 const fp16type  fip             (f * i * p);
15221                 const fp16type  eln             (e * l * n);
15222                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15223
15224                 // [ e f g ]
15225                 // [ i j k ]
15226                 // [ m n o ]
15227                 const fp16type  ejo             (e * j * o);
15228                 const fp16type  fkm             (f * k * m);
15229                 const fp16type  gin             (g * i * n);
15230                 const fp16type  gjm             (g * j * m);
15231                 const fp16type  fio             (f * i * o);
15232                 const fp16type  ekn             (e * k * n);
15233                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15234
15235                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15236                 const fp16type  rf16    (r);
15237
15238                 out[0] = rf16.bits();
15239                 min[0] = getMin(r, getULPs(in));
15240                 max[0] = getMax(r, getULPs(in));
15241
15242                 return true;
15243         }
15244 };
15245
15246 template<size_t size>
15247 struct fp16Inverse;
15248
15249 template<>
15250 struct fp16Inverse<2> : public fp16MatrixBase
15251 {
15252         virtual double getULPs (vector<const deFloat16*>& in)
15253         {
15254                 DE_UNREF(in);
15255
15256                 return 128.0; // This is not a precision test. Value is not from spec
15257         }
15258
15259         deUint32 getComponentValidity ()
15260         {
15261                 return getComponentMatrixValidityMask(2, 2);
15262         }
15263
15264         template<class fp16type>
15265         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15266         {
15267                 const size_t    cols            = 2;
15268                 const size_t    rows            = 2;
15269                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15270                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15271
15272                 DE_ASSERT(in.size() == 1);
15273                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15274                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15275                 DE_UNREF(alignedCols);
15276
15277                 // [ a b ]
15278                 // [ c d ]
15279                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15280                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15281                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15282                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15283                 const float             ad              (a * d);
15284                 const fp16type  adf16   (ad);
15285                 const float             bc              (b * c);
15286                 const fp16type  bcf16   (bc);
15287                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15288                 const fp16type  det16   (det);
15289
15290                 out[0] = fp16type( d / det16.asFloat()).bits();
15291                 out[1] = fp16type(-c / det16.asFloat()).bits();
15292                 out[2] = fp16type(-b / det16.asFloat()).bits();
15293                 out[3] = fp16type( a / det16.asFloat()).bits();
15294
15295                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15296                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15297                         {
15298                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15299                                 const fp16type  s       (out[ndx]);
15300
15301                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15302                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15303                         }
15304
15305                 return true;
15306         }
15307 };
15308
15309 inline std::string fp16ToString(deFloat16 val)
15310 {
15311         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15312 }
15313
15314 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15315 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15316 {
15317         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15318                 return false;
15319
15320         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15321         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15322         const size_t    inputsSteps[3]          =
15323         {
15324                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15325                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15326                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15327         };
15328
15329         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15330         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15331
15332         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15333         {
15334                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15335                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15336         }
15337
15338         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15339         TestedArithmeticFunction        func;
15340
15341         func.setOutCompCount(RES_COMPONENTS);
15342         func.setArgCompCount(0, ARG0_COMPONENTS);
15343         func.setArgCompCount(1, ARG1_COMPONENTS);
15344         func.setArgCompCount(2, ARG2_COMPONENTS);
15345
15346         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15347         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15348         const size_t                            denormModesCount                                = 2;
15349         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15350         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15351         bool                                            success                                                 = true;
15352         size_t                                          validatedCount                                  = 0;
15353
15354         vector<deUint8> inputBytes[3];
15355
15356         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15357                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15358
15359         const deFloat16* const                  inputsAsFP16[3]                 =
15360         {
15361                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15362                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15363                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15364         };
15365
15366         for (size_t idx = 0; idx < iterationsCount; ++idx)
15367         {
15368                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15369                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15370                 bool                                            iterationValidated      (true);
15371
15372                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15373                 {
15374                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15375                         {
15376                                 func.setFlavor(flavorNdx);
15377
15378                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15379                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15380                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15381                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15382                                 vector<const deFloat16*>        arguments;
15383
15384                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15385                                 {
15386                                         std::string     error;
15387                                         bool            reportError = false;
15388
15389                                         if (callOncePerComponent || componentNdx == 0)
15390                                         {
15391                                                 bool funcCallResult;
15392
15393                                                 arguments.clear();
15394
15395                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15396                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15397
15398                                                 if (denormNdx == 0)
15399                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15400                                                 else
15401                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15402
15403                                                 if (!funcCallResult)
15404                                                 {
15405                                                         iterationValidated = false;
15406
15407                                                         if (callOncePerComponent)
15408                                                                 continue;
15409                                                         else
15410                                                                 break;
15411                                                 }
15412                                         }
15413
15414                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15415                                                 continue;
15416
15417                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15418
15419                                         if (reportError)
15420                                         {
15421                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15422                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15423
15424                                                 if (reportError && expected.isNaN())
15425                                                         reportError = false;
15426
15427                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15428                                                 {
15429                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15430                                                         {
15431                                                                 // Ignore rounding
15432                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15433                                                                         reportError = false;
15434                                                         }
15435
15436                                                         if (reportError && expected.isInf())
15437                                                         {
15438                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15439                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15440                                                                         reportError = false;
15441                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15442                                                                         reportError = false;
15443                                                         }
15444
15445                                                         if (reportError)
15446                                                         {
15447                                                                 const double    outputtedDouble = outputted.asDouble();
15448
15449                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15450
15451                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15452                                                                         reportError = false;
15453                                                         }
15454                                                 }
15455
15456                                                 if (reportError)
15457                                                 {
15458                                                         const size_t            inputsComps[3]  =
15459                                                         {
15460                                                                 ARG0_COMPONENTS,
15461                                                                 ARG1_COMPONENTS,
15462                                                                 ARG2_COMPONENTS,
15463                                                         };
15464                                                         string                          inputsValues    ("Inputs:");
15465                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15466                                                         std::stringstream       errStream;
15467
15468                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15469                                                         {
15470                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15471
15472                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15473
15474                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15475                                                                 {
15476                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15477
15478                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15479                                                                 }
15480                                                         }
15481
15482                                                         errStream       << "At"
15483                                                                                 << " iteration " << de::toString(idx)
15484                                                                                 << " component " << de::toString(componentNdx)
15485                                                                                 << " denormMode " << de::toString(denormNdx)
15486                                                                                 << " (" << denormModes[denormNdx] << ")"
15487                                                                                 << " " << flavorName
15488                                                                                 << " " << inputsValues
15489                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15490                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15491                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15492                                                                                 << " " << error << "."
15493                                                                                 << std::endl;
15494
15495                                                         errors[componentNdx] += errStream.str();
15496
15497                                                         successfulRuns[componentNdx]--;
15498                                                 }
15499                                         }
15500                                 }
15501                         }
15502                 }
15503
15504                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15505                 {
15506                         // Check if any component has total failure
15507                         if (successfulRuns[componentNdx] == 0)
15508                         {
15509                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15510                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15511
15512                                 success = false;
15513                         }
15514                 }
15515
15516                 if (iterationValidated)
15517                         validatedCount++;
15518         }
15519
15520         if (validatedCount < 16)
15521                 TCU_THROW(InternalError, "Too few samples has been validated.");
15522
15523         return success;
15524 }
15525
15526 // IEEE-754 floating point numbers:
15527 // +--------+------+----------+-------------+
15528 // | binary | sign | exponent | significand |
15529 // +--------+------+----------+-------------+
15530 // | 16-bit |  1   |    5     |     10      |
15531 // +--------+------+----------+-------------+
15532 // | 32-bit |  1   |    8     |     23      |
15533 // +--------+------+----------+-------------+
15534 //
15535 // 16-bit floats:
15536 //
15537 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15538 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15539 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15540 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15541 //
15542 // 0   000 00   00 0000 0000 (0x0000: +0)
15543 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15544 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15545 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15546 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15547 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15548 // Generate and return 16-bit floats and their corresponding 32-bit values.
15549 //
15550 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15551 // Expected count to be at least 14 (numPicks).
15552 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15553 {
15554         vector<deFloat16>       float16;
15555
15556         float16.reserve(count);
15557
15558         // Zero
15559         float16.push_back(deUint16(0x0000));
15560         float16.push_back(deUint16(0x8000));
15561         // Infinity
15562         float16.push_back(deUint16(0x7c00));
15563         float16.push_back(deUint16(0xfc00));
15564         // Normalized
15565         float16.push_back(deUint16(0x0401));
15566         float16.push_back(deUint16(0x8401));
15567         // Some normal number
15568         float16.push_back(deUint16(0x14cb));
15569         float16.push_back(deUint16(0x94cb));
15570         // Min/max positive normal
15571         float16.push_back(deUint16(0x0400));
15572         float16.push_back(deUint16(0x7bff));
15573         // Min/max negative normal
15574         float16.push_back(deUint16(0x8400));
15575         float16.push_back(deUint16(0xfbff));
15576         // PI
15577         float16.push_back(deUint16(0x4248)); // 3.140625
15578         float16.push_back(deUint16(0xb248)); // -3.140625
15579         // PI/2
15580         float16.push_back(deUint16(0x3e48)); // 1.5703125
15581         float16.push_back(deUint16(0xbe48)); // -1.5703125
15582         float16.push_back(deUint16(0x3c00)); // 1.0
15583         float16.push_back(deUint16(0x3800)); // 0.5
15584         // Some useful constants
15585         float16.push_back(tcu::Float16(-2.5f).bits());
15586         float16.push_back(tcu::Float16(-1.0f).bits());
15587         float16.push_back(tcu::Float16( 0.4f).bits());
15588         float16.push_back(tcu::Float16( 2.5f).bits());
15589
15590         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15591
15592         DE_ASSERT(count >= numPicks);
15593         count -= numPicks;
15594
15595         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15596         {
15597                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15598                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15599                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15600
15601                 // Exclude power of -14 to avoid denorms
15602                 DE_ASSERT(de::inRange(exponent, -13, 15));
15603
15604                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15605         }
15606
15607         return float16;
15608 }
15609
15610 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15611 {
15612         DE_UNREF(argNo);
15613
15614         de::Random      rnd(seed);
15615
15616         return getFloat16a(rnd, static_cast<deUint32>(count));
15617 }
15618
15619 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15620 {
15621         de::Random      rnd             (seed);
15622         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15623
15624         DE_ASSERT(newCount * newCount == count);
15625
15626         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15627
15628         return squarize(float16, static_cast<deUint32>(argNo));
15629 }
15630
15631 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15632 {
15633         if (argNo == 0 || argNo == 1)
15634                 return getInputData2(seed, count, argNo);
15635         else
15636                 return getInputData1(seed<<argNo, count, argNo);
15637 }
15638
15639 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15640 {
15641         DE_UNREF(stride);
15642
15643         vector<deFloat16>       result;
15644
15645         switch (argCount)
15646         {
15647                 case 1:result = getInputData1(seed, count, argNo); break;
15648                 case 2:result = getInputData2(seed, count, argNo); break;
15649                 case 3:result = getInputData3(seed, count, argNo); break;
15650                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15651         }
15652
15653         if (compCount == 3)
15654         {
15655                 const size_t            newCount = (3 * count) / 4;
15656                 vector<deFloat16>       newResult;
15657
15658                 newResult.reserve(result.size());
15659
15660                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15661                 {
15662                         newResult.push_back(result[ndx]);
15663
15664                         if (ndx % 3 == 2)
15665                                 newResult.push_back(0);
15666                 }
15667
15668                 result = newResult;
15669         }
15670
15671         DE_ASSERT(result.size() == count);
15672
15673         return result;
15674 }
15675
15676 // Generator for functions requiring data in range [1, inf]
15677 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15678 {
15679         vector<deFloat16>       result;
15680
15681         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15682
15683         // Filter out values below 1.0 from upper half of numbers
15684         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15685         {
15686                 const float f = tcu::Float16(result[idx]).asFloat();
15687
15688                 if (f < 1.0f)
15689                         result[idx] = tcu::Float16(1.0f - f).bits();
15690         }
15691
15692         return result;
15693 }
15694
15695 // Generator for functions requiring data in range [-1, 1]
15696 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15697 {
15698         vector<deFloat16>       result;
15699
15700         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15701
15702         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15703         {
15704                 const float f = tcu::Float16(result[idx]).asFloat();
15705
15706                 if (!de::inRange(f, -1.0f, 1.0f))
15707                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15708         }
15709
15710         return result;
15711 }
15712
15713 // Generator for functions requiring data in range [-pi, pi]
15714 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15715 {
15716         vector<deFloat16>       result;
15717
15718         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15719
15720         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15721         {
15722                 const float f = tcu::Float16(result[idx]).asFloat();
15723
15724                 if (!de::inRange(f, -DE_PI, DE_PI))
15725                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15726         }
15727
15728         return result;
15729 }
15730
15731 // Generator for functions requiring data in range [0, inf]
15732 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15733 {
15734         vector<deFloat16>       result;
15735
15736         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15737
15738         if (argNo == 0)
15739         {
15740                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15741                         result[idx] &= static_cast<deFloat16>(~0x8000);
15742         }
15743
15744         return result;
15745 }
15746
15747 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15748 {
15749         DE_UNREF(stride);
15750         DE_UNREF(argCount);
15751
15752         vector<deFloat16>       result;
15753
15754         if (argNo == 0)
15755                 result = getInputData2(seed, count, argNo);
15756         else
15757         {
15758                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15759                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15760                 const size_t            newCountY               = count / newCountX;
15761                 de::Random                      rnd                             (seed);
15762                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15763
15764                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15765
15766                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15767                 {
15768                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15769
15770                         result.insert(result.end(), tmp.begin(), tmp.end());
15771                 }
15772         }
15773
15774         DE_ASSERT(result.size() == count);
15775
15776         return result;
15777 }
15778
15779 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15780 {
15781         DE_UNREF(compCount);
15782         DE_UNREF(stride);
15783         DE_UNREF(argCount);
15784
15785         de::Random                      rnd             (seed << argNo);
15786         vector<deFloat16>       result;
15787
15788         result = getFloat16a(rnd, static_cast<deUint32>(count));
15789
15790         DE_ASSERT(result.size() == count);
15791
15792         return result;
15793 }
15794
15795 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15796 {
15797         DE_UNREF(compCount);
15798         DE_UNREF(argCount);
15799
15800         de::Random                      rnd             (seed << argNo);
15801         vector<deFloat16>       result;
15802
15803         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15804         {
15805                 int num = (rnd.getUint16() % 16) - 8;
15806
15807                 result.push_back(tcu::Float16(float(num)).bits());
15808         }
15809
15810         result[0 * stride] = deUint16(0x7c00); // +Inf
15811         result[1 * stride] = deUint16(0xfc00); // -Inf
15812
15813         DE_ASSERT(result.size() == count);
15814
15815         return result;
15816 }
15817
15818 // Generator for smoothstep function
15819 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15820 {
15821         vector<deFloat16>       result;
15822
15823         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15824
15825         if (argNo == 0)
15826         {
15827                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15828                 {
15829                         const float f = tcu::Float16(result[idx]).asFloat();
15830
15831                         if (f > 4.0f)
15832                                 result[idx] = tcu::Float16(-f).bits();
15833                 }
15834         }
15835
15836         if (argNo == 1)
15837         {
15838                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15839                 {
15840                         const float f = tcu::Float16(result[idx]).asFloat();
15841
15842                         if (f < 4.0f)
15843                                 result[idx] = tcu::Float16(-f).bits();
15844                 }
15845         }
15846
15847         return result;
15848 }
15849
15850 // Generates normalized vectors for arguments 0 and 1
15851 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15852 {
15853         DE_UNREF(compCount);
15854         DE_UNREF(argCount);
15855
15856         de::Random                      rnd             (seed << argNo);
15857         vector<deFloat16>       result;
15858
15859         if (argNo == 0 || argNo == 1)
15860         {
15861                 // The input parameters for the incident vector I and the surface normal N must already be normalized
15862                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
15863                 {
15864                         vector <float>  unnormolized;
15865                         float                   sum                             = 0;
15866
15867                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15868                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
15869
15870                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15871                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
15872
15873                         sum = deFloatSqrt(sum);
15874                         if (sum == 0.0f)
15875                                 unnormolized[0] = sum = 1.0f;
15876
15877                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15878                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
15879
15880                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
15881                                 result.push_back(0);
15882                 }
15883         }
15884         else
15885         {
15886                 // Input parameter eta
15887                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15888                 {
15889                         int num = (rnd.getUint16() % 16) - 8;
15890
15891                         result.push_back(tcu::Float16(float(num)).bits());
15892                 }
15893         }
15894
15895         DE_ASSERT(result.size() == count);
15896
15897         return result;
15898 }
15899
15900 // Data generator for complex matrix functions like determinant and inverse
15901 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15902 {
15903         DE_UNREF(compCount);
15904         DE_UNREF(stride);
15905         DE_UNREF(argCount);
15906
15907         de::Random                      rnd             (seed << argNo);
15908         vector<deFloat16>       result;
15909
15910         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15911         {
15912                 int num = (rnd.getUint16() % 16) - 8;
15913
15914                 result.push_back(tcu::Float16(float(num)).bits());
15915         }
15916
15917         DE_ASSERT(result.size() == count);
15918
15919         return result;
15920 }
15921
15922 struct Math16TestType
15923 {
15924         const char*             typePrefix;
15925         const size_t    typeComponents;
15926         const size_t    typeArrayStride;
15927         const size_t    typeStructStride;
15928 };
15929
15930 enum Math16DataTypes
15931 {
15932         NONE    = 0,
15933         SCALAR  = 1,
15934         VEC2    = 2,
15935         VEC3    = 3,
15936         VEC4    = 4,
15937         MAT2X2,
15938         MAT2X3,
15939         MAT2X4,
15940         MAT3X2,
15941         MAT3X3,
15942         MAT3X4,
15943         MAT4X2,
15944         MAT4X3,
15945         MAT4X4,
15946         MATH16_TYPE_LAST
15947 };
15948
15949 struct Math16ArgFragments
15950 {
15951         const char*     bodies;
15952         const char*     variables;
15953         const char*     decorations;
15954         const char*     funcVariables;
15955 };
15956
15957 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
15958
15959 struct Math16TestFunc
15960 {
15961         const char*                                     funcName;
15962         const char*                                     funcSuffix;
15963         size_t                                          funcArgsCount;
15964         size_t                                          typeResult;
15965         size_t                                          typeArg0;
15966         size_t                                          typeArg1;
15967         size_t                                          typeArg2;
15968         Math16GetInputData*                     getInputDataFunc;
15969         VerifyIOFunc                            verifyFunc;
15970 };
15971
15972 template<class SpecResource>
15973 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
15974 {
15975         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
15976         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
15977         const size_t                            numDataPointsByAxis                     = 32;
15978         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
15979         const char*                                     componentType                           = "f16";
15980         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
15981         {
15982                 { "",           0,       0,                                              0,                                             },
15983                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
15984                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
15985                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
15986                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
15987                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
15988                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15989                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15990                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15991                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15992                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15993                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
15994                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15995                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
15996         };
15997
15998         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
15999
16000
16001         const StringTemplate preMain
16002         (
16003                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16004
16005                 "        %f16     = OpTypeFloat 16\n"
16006                 "        %v2f16   = OpTypeVector %f16 2\n"
16007                 "        %v3f16   = OpTypeVector %f16 3\n"
16008                 "        %v4f16   = OpTypeVector %f16 4\n"
16009                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16010                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16011                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16012                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16013                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16014                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16015                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16016                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16017                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16018
16019                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16020                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16021                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16022                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16023                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16024                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16025                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16026                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16027                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16028                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16029                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16030                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16031                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16032
16033                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16034                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16035                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16036                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16037                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16038                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16039                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16040                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16041                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16042                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16043                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16044                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16045                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16046
16047                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16048                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16049                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16050                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16051                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16052                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16053                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16054                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16055                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16056                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16057                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16058                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16059                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16060
16061                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16062                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16063                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16064                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16065                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16066                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16067                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16068                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16069                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16070                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16071                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16072                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16073                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16074
16075                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16076                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16077                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16078                 "${arg_vars}"
16079         );
16080
16081         const StringTemplate decoration
16082         (
16083                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16084                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16085                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16086                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16087                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16088                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16089                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16090                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16091                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16092                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16093                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16094                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16095                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16096
16097                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16098                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16099                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16100                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16101                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16102                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16103                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16104                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16105                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16106                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16107                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16108                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16109                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16110
16111                 "OpDecorate %SSBO_f16     BufferBlock\n"
16112                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16113                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16114                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16115                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16116                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16117                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16118                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16119                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16120                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16121                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16122                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16123                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16124
16125                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16126                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16127                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16128                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16129                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16130                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16131                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16132                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16133                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16134
16135                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16136                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16137                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16138                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16139                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16140                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16141                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16142                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16143                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16144
16145                 "${arg_decorations}"
16146         );
16147
16148         const StringTemplate testFun
16149         (
16150                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16151                 "    %param = OpFunctionParameter %v4f32\n"
16152                 "    %entry = OpLabel\n"
16153
16154                 "        %i = OpVariable %fp_i32 Function\n"
16155                 "${arg_infunc_vars}"
16156                 "             OpStore %i %c_i32_0\n"
16157                 "             OpBranch %loop\n"
16158
16159                 "     %loop = OpLabel\n"
16160                 "    %i_cmp = OpLoad %i32 %i\n"
16161                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16162                 "             OpLoopMerge %merge %next None\n"
16163                 "             OpBranchConditional %lt %write %merge\n"
16164
16165                 "    %write = OpLabel\n"
16166                 "      %ndx = OpLoad %i32 %i\n"
16167
16168                 "${arg_func_call}"
16169
16170                 "             OpBranch %next\n"
16171
16172                 "     %next = OpLabel\n"
16173                 "    %i_cur = OpLoad %i32 %i\n"
16174                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16175                 "             OpStore %i %i_new\n"
16176                 "             OpBranch %loop\n"
16177
16178                 "    %merge = OpLabel\n"
16179                 "             OpReturnValue %param\n"
16180                 "             OpFunctionEnd\n"
16181         );
16182
16183         const Math16ArgFragments        argFragment1    =
16184         {
16185                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16186                 " %val_src0 = OpLoad %${t0} %src0\n"
16187                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16188                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16189                 "             OpStore %dst %val_dst\n",
16190                 "",
16191                 "",
16192                 "",
16193         };
16194
16195         const Math16ArgFragments        argFragment2    =
16196         {
16197                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16198                 " %val_src0 = OpLoad %${t0} %src0\n"
16199                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16200                 " %val_src1 = OpLoad %${t1} %src1\n"
16201                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16202                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16203                 "             OpStore %dst %val_dst\n",
16204                 "",
16205                 "",
16206                 "",
16207         };
16208
16209         const Math16ArgFragments        argFragment3    =
16210         {
16211                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16212                 " %val_src0 = OpLoad %${t0} %src0\n"
16213                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16214                 " %val_src1 = OpLoad %${t1} %src1\n"
16215                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16216                 " %val_src2 = OpLoad %${t2} %src2\n"
16217                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16218                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16219                 "             OpStore %dst %val_dst\n",
16220                 "",
16221                 "",
16222                 "",
16223         };
16224
16225         const Math16ArgFragments        argFragmentLdExp        =
16226         {
16227                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16228                 " %val_src0 = OpLoad %${t0} %src0\n"
16229                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16230                 " %val_src1 = OpLoad %${t1} %src1\n"
16231                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16232                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16233                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16234                 "             OpStore %dst %val_dst\n",
16235
16236                 "",
16237
16238                 "",
16239
16240                 "",
16241         };
16242
16243         const Math16ArgFragments        argFragmentModfFrac     =
16244         {
16245                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16246                 " %val_src0 = OpLoad %${t0} %src0\n"
16247                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16248                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16249                 "             OpStore %dst %val_dst\n",
16250
16251                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16252
16253                 "",
16254
16255                 "      %tmp = OpVariable %fp_tmp Function\n",
16256         };
16257
16258         const Math16ArgFragments        argFragmentModfInt      =
16259         {
16260                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16261                 " %val_src0 = OpLoad %${t0} %src0\n"
16262                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16263                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16264                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16265                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16266                 "             OpStore %dst %val_dst\n",
16267
16268                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16269
16270                 "",
16271
16272                 "      %tmp = OpVariable %fp_tmp Function\n",
16273         };
16274
16275         const Math16ArgFragments        argFragmentModfStruct   =
16276         {
16277                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16278                 " %val_src0 = OpLoad %${t0} %src0\n"
16279                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16280                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16281                 "             OpStore %tmp_ptr_s %val_tmp\n"
16282                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16283                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16284                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16285                 "             OpStore %dst %val_dst\n",
16286
16287                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16288                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16289                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16290                 "   %c_frac = OpConstant %i32 0\n"
16291                 "    %c_int = OpConstant %i32 1\n",
16292
16293                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16294                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16295
16296                 "      %tmp = OpVariable %fp_tmp Function\n",
16297         };
16298
16299         const Math16ArgFragments        argFragmentFrexpStructS =
16300         {
16301                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16302                 " %val_src0 = OpLoad %${t0} %src0\n"
16303                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16304                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16305                 "             OpStore %tmp_ptr_s %val_tmp\n"
16306                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16307                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16308                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16309                 "             OpStore %dst %val_dst\n",
16310
16311                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16312                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16313                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16314
16315                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16316                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16317
16318                 "      %tmp = OpVariable %fp_tmp Function\n",
16319         };
16320
16321         const Math16ArgFragments        argFragmentFrexpStructE =
16322         {
16323                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16324                 " %val_src0 = OpLoad %${t0} %src0\n"
16325                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16326                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16327                 "             OpStore %tmp_ptr_s %val_tmp\n"
16328                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16329                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16330                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16331                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16332                 "             OpStore %dst %val_dst\n",
16333
16334                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16335                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16336
16337                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16338                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16339
16340                 "      %tmp = OpVariable %fp_tmp Function\n",
16341         };
16342
16343         const Math16ArgFragments        argFragmentFrexpS               =
16344         {
16345                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16346                 " %val_src0 = OpLoad %${t0} %src0\n"
16347                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16348                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16349                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16350                 "             OpStore %dst %val_dst\n",
16351
16352                 "",
16353
16354                 "",
16355
16356                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16357         };
16358
16359         const Math16ArgFragments        argFragmentFrexpE               =
16360         {
16361                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16362                 " %val_src0 = OpLoad %${t0} %src0\n"
16363                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16364                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16365                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16366                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16367                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16368                 "             OpStore %dst %val_dst\n",
16369
16370                 "",
16371
16372                 "",
16373
16374                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16375         };
16376
16377         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16378         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16379         const string                            testName                                = de::toLower(funcNameString);
16380         const Math16ArgFragments*       argFragments                    = DE_NULL;
16381         const size_t                            typeStructStride                = testType.typeStructStride;
16382         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16383         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16384         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16385         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16386         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16387         VulkanFeatures                          features;
16388         SpecResource                            specResource;
16389         map<string, string>                     specs;
16390         map<string, string>                     fragments;
16391         vector<string>                          extensions;
16392         string                                          funcCall;
16393         string                                          funcVariables;
16394         string                                          variables;
16395         string                                          declarations;
16396         string                                          decorations;
16397
16398         switch (testFunc.funcArgsCount)
16399         {
16400                 case 1:
16401                 {
16402                         argFragments = &argFragment1;
16403
16404                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16405                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16406                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16407                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16408                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16409                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16410                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16411                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16412
16413                         break;
16414                 }
16415                 case 2:
16416                 {
16417                         argFragments = &argFragment2;
16418
16419                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16420
16421                         break;
16422                 }
16423                 case 3:
16424                 {
16425                         argFragments = &argFragment3;
16426
16427                         break;
16428                 }
16429                 default:
16430                 {
16431                         TCU_THROW(InternalError, "Invalid number of arguments");
16432                 }
16433         }
16434
16435         if (testFunc.funcArgsCount == 1)
16436         {
16437                 variables +=
16438                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16439                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16440
16441                 decorations +=
16442                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16443                         "OpDecorate %ssbo_src0 Binding 0\n"
16444                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16445                         "OpDecorate %ssbo_dst Binding 1\n";
16446         }
16447         else if (testFunc.funcArgsCount == 2)
16448         {
16449                 variables +=
16450                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16451                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16452                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16453
16454                 decorations +=
16455                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16456                         "OpDecorate %ssbo_src0 Binding 0\n"
16457                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16458                         "OpDecorate %ssbo_src1 Binding 1\n"
16459                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16460                         "OpDecorate %ssbo_dst Binding 2\n";
16461         }
16462         else if (testFunc.funcArgsCount == 3)
16463         {
16464                 variables +=
16465                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16466                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16467                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16468                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16469
16470                 decorations +=
16471                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16472                         "OpDecorate %ssbo_src0 Binding 0\n"
16473                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16474                         "OpDecorate %ssbo_src1 Binding 1\n"
16475                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16476                         "OpDecorate %ssbo_src2 Binding 2\n"
16477                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16478                         "OpDecorate %ssbo_dst Binding 3\n";
16479         }
16480         else
16481         {
16482                 TCU_THROW(InternalError, "Invalid number of function arguments");
16483         }
16484
16485         variables       += argFragments->variables;
16486         decorations     += argFragments->decorations;
16487
16488         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16489         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16490         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16491         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16492         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16493         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16494         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16495         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16496         specs["struct_stride"]          = de::toString(typeStructStride);
16497         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16498         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16499         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16500
16501         variables                                       = StringTemplate(variables).specialize(specs);
16502         decorations                                     = StringTemplate(decorations).specialize(specs);
16503         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16504         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16505
16506         specs["num_data_points"]        = de::toString(iterations);
16507         specs["arg_vars"]                       = variables;
16508         specs["arg_decorations"]        = decorations;
16509         specs["arg_infunc_vars"]        = funcVariables;
16510         specs["arg_func_call"]          = funcCall;
16511
16512         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16513         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16\nOpCapability Float16\n";
16514         fragments["decoration"]         = decoration.specialize(specs);
16515         fragments["pre_main"]           = preMain.specialize(specs);
16516         fragments["testfun"]            = testFun.specialize(specs);
16517
16518         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16519         {
16520                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16521                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16522                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16523                                                                                                         : -1;
16524                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16525
16526                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16527         }
16528
16529         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16530         specResource.verifyIO = testFunc.verifyFunc;
16531
16532         extensions.push_back("VK_KHR_16bit_storage");
16533         extensions.push_back("VK_KHR_shader_float16_int8");
16534
16535         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16536         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16537
16538         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16539 }
16540
16541 template<size_t C, class SpecResource>
16542 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16543 {
16544         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16545
16546         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16547         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16548         const Math16TestFunc                    testFuncs[]             =
16549         {
16550                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16551                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16552                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16553                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16554                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16555                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16556                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16557                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16558                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16559                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16560                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16561                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16562                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16563                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16564                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16565                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16566                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16567                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16568                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16569                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16570                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16571                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16572                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16573                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16574                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16575                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16576                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16577                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16578                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16579                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16580                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16581                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16582                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16583                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16584                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16585                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16586                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16587                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16588                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16589                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16590                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16591                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16592                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16593                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16594                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16595                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16596                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16597                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16598                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16599                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16600                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16601                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16602                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16603                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16604                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16605                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16606                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16607                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16608                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16609                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16610         };
16611
16612         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16613         {
16614                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16615                 const string                    funcNameString  = testFunc.funcName;
16616
16617                 if ((C != 3) && funcNameString == "Cross")
16618                         continue;
16619
16620                 if ((C < 2) && funcNameString == "OpDot")
16621                         continue;
16622
16623                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16624                         continue;
16625
16626                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16627         }
16628
16629         return testGroup.release();
16630 }
16631
16632 template<class SpecResource>
16633 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16634 {
16635         const std::string                               testGroupName   ("arithmetic");
16636         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16637         const Math16TestFunc                    testFuncs[]             =
16638         {
16639                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16640                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16641                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16642                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16643                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16644                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16645                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16646                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16647                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16648                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16649                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16650                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16651                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16652                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16653                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16654                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16655                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16656                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16657                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16658                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16659                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16660                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16661                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16662                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16663                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16664                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16665                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16666                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16667                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16668                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16669                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16670                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16671                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16672                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16673                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16674                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16675                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16676                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16677                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16678                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16679                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16680                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16681                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16682                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16683                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16684                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16685                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16686                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16687                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16688                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16689                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16690                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16691                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16692                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16693                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16694                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16695                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16696                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16697                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16698                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16699                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16700                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16701                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16702                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16703                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16704                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16705                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16706                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16707                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16708                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16709                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16710                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16711                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16712                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16713                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16714                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16715         };
16716
16717         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16718         {
16719                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16720
16721                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16722         }
16723
16724         return testGroup.release();
16725 }
16726
16727 const string getNumberTypeName (const NumberType type)
16728 {
16729         if (type == NUMBERTYPE_INT32)
16730         {
16731                 return "int";
16732         }
16733         else if (type == NUMBERTYPE_UINT32)
16734         {
16735                 return "uint";
16736         }
16737         else if (type == NUMBERTYPE_FLOAT32)
16738         {
16739                 return "float";
16740         }
16741         else
16742         {
16743                 DE_ASSERT(false);
16744                 return "";
16745         }
16746 }
16747
16748 deInt32 getInt(de::Random& rnd)
16749 {
16750         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16751 }
16752
16753 const string repeatString (const string& str, int times)
16754 {
16755         string filler;
16756         for (int i = 0; i < times; ++i)
16757         {
16758                 filler += str;
16759         }
16760         return filler;
16761 }
16762
16763 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16764 {
16765         if (type == NUMBERTYPE_INT32)
16766         {
16767                 return numberToString<deInt32>(getInt(rnd));
16768         }
16769         else if (type == NUMBERTYPE_UINT32)
16770         {
16771                 return numberToString<deUint32>(rnd.getUint32());
16772         }
16773         else if (type == NUMBERTYPE_FLOAT32)
16774         {
16775                 return numberToString<float>(rnd.getFloat());
16776         }
16777         else
16778         {
16779                 DE_ASSERT(false);
16780                 return "";
16781         }
16782 }
16783
16784 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16785 {
16786         map<string, string> params;
16787
16788         // Vec2 to Vec4
16789         for (int width = 2; width <= 4; ++width)
16790         {
16791                 const string randomConst = numberToString(getInt(rnd));
16792                 const string widthStr = numberToString(width);
16793                 const string composite_type = "${customType}vec" + widthStr;
16794                 const int index = rnd.getInt(0, width-1);
16795
16796                 params["type"]                  = "vec";
16797                 params["name"]                  = params["type"] + "_" + widthStr;
16798                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16799                 params["compositeType"]         = composite_type;
16800                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16801                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16802                 params["indexes"]               = numberToString(index);
16803                 testCases.push_back(params);
16804         }
16805 }
16806
16807 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16808 {
16809         const int limit = 10;
16810         map<string, string> params;
16811
16812         for (int width = 2; width <= limit; ++width)
16813         {
16814                 string randomConst = numberToString(getInt(rnd));
16815                 string widthStr = numberToString(width);
16816                 int index = rnd.getInt(0, width-1);
16817
16818                 params["type"]                  = "array";
16819                 params["name"]                  = params["type"] + "_" + widthStr;
16820                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16821                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16822                 params["compositeType"]         = "%composite";
16823                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16824                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16825                 params["indexes"]               = numberToString(index);
16826                 testCases.push_back(params);
16827         }
16828 }
16829
16830 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16831 {
16832         const int limit = 10;
16833         map<string, string> params;
16834
16835         for (int width = 2; width <= limit; ++width)
16836         {
16837                 string randomConst = numberToString(getInt(rnd));
16838                 int index = rnd.getInt(0, width-1);
16839
16840                 params["type"]                  = "struct";
16841                 params["name"]                  = params["type"] + "_" + numberToString(width);
16842                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16843                 params["compositeType"]         = "%composite";
16844                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16845                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16846                 params["indexes"]               = numberToString(index);
16847                 testCases.push_back(params);
16848         }
16849 }
16850
16851 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16852 {
16853         map<string, string> params;
16854
16855         // Vec2 to Vec4
16856         for (int width = 2; width <= 4; ++width)
16857         {
16858                 string widthStr = numberToString(width);
16859
16860                 for (int column = 2 ; column <= 4; ++column)
16861                 {
16862                         int index_0 = rnd.getInt(0, column-1);
16863                         int index_1 = rnd.getInt(0, width-1);
16864                         string columnStr = numberToString(column);
16865
16866                         params["type"]          = "matrix";
16867                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
16868                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
16869                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
16870                         params["compositeType"] = "%composite";
16871
16872                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
16873                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
16874
16875                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
16876                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
16877                         testCases.push_back(params);
16878                 }
16879         }
16880 }
16881
16882 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16883 {
16884         createVectorCompositeCases(testCases, rnd, type);
16885         createArrayCompositeCases(testCases, rnd, type);
16886         createStructCompositeCases(testCases, rnd, type);
16887         // Matrix only supports float types
16888         if (type == NUMBERTYPE_FLOAT32)
16889         {
16890                 createMatrixCompositeCases(testCases, rnd, type);
16891         }
16892 }
16893
16894 const string getAssemblyTypeDeclaration (const NumberType type)
16895 {
16896         switch (type)
16897         {
16898                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
16899                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
16900                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
16901                 default:                        DE_ASSERT(false); return "";
16902         }
16903 }
16904
16905 const string getAssemblyTypeName (const NumberType type)
16906 {
16907         switch (type)
16908         {
16909                 case NUMBERTYPE_INT32:          return "%i32";
16910                 case NUMBERTYPE_UINT32:         return "%u32";
16911                 case NUMBERTYPE_FLOAT32:        return "%f32";
16912                 default:                        DE_ASSERT(false); return "";
16913         }
16914 }
16915
16916 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
16917 {
16918         map<string, string>     parameters(params);
16919
16920         const string customType = getAssemblyTypeName(type);
16921         map<string, string> substCustomType;
16922         substCustomType["customType"] = customType;
16923         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
16924         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
16925         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
16926         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
16927         parameters["customType"] = customType;
16928         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
16929
16930         if (parameters.at("compositeType") != "%u32vec3")
16931         {
16932                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
16933         }
16934
16935         return StringTemplate(
16936                 "OpCapability Shader\n"
16937                 "OpCapability Matrix\n"
16938                 "OpMemoryModel Logical GLSL450\n"
16939                 "OpEntryPoint GLCompute %main \"main\" %id\n"
16940                 "OpExecutionMode %main LocalSize 1 1 1\n"
16941
16942                 "OpSource GLSL 430\n"
16943                 "OpName %main           \"main\"\n"
16944                 "OpName %id             \"gl_GlobalInvocationID\"\n"
16945
16946                 // Decorators
16947                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
16948                 "OpDecorate %buf BufferBlock\n"
16949                 "OpDecorate %indata DescriptorSet 0\n"
16950                 "OpDecorate %indata Binding 0\n"
16951                 "OpDecorate %outdata DescriptorSet 0\n"
16952                 "OpDecorate %outdata Binding 1\n"
16953                 "OpDecorate %customarr ArrayStride 4\n"
16954                 "${compositeDecorator}"
16955                 "OpMemberDecorate %buf 0 Offset 0\n"
16956
16957                 // General types
16958                 "%void      = OpTypeVoid\n"
16959                 "%voidf     = OpTypeFunction %void\n"
16960                 "%u32       = OpTypeInt 32 0\n"
16961                 "%i32       = OpTypeInt 32 1\n"
16962                 "%f32       = OpTypeFloat 32\n"
16963
16964                 // Composite declaration
16965                 "${compositeDecl}"
16966
16967                 // Constants
16968                 "${filler}"
16969
16970                 "${u32vec3Decl:opt}"
16971                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
16972
16973                 // Inherited from custom
16974                 "%customptr = OpTypePointer Uniform ${customType}\n"
16975                 "%customarr = OpTypeRuntimeArray ${customType}\n"
16976                 "%buf       = OpTypeStruct %customarr\n"
16977                 "%bufptr    = OpTypePointer Uniform %buf\n"
16978
16979                 "%indata    = OpVariable %bufptr Uniform\n"
16980                 "%outdata   = OpVariable %bufptr Uniform\n"
16981
16982                 "%id        = OpVariable %uvec3ptr Input\n"
16983                 "%zero      = OpConstant %i32 0\n"
16984
16985                 "%main      = OpFunction %void None %voidf\n"
16986                 "%label     = OpLabel\n"
16987                 "%idval     = OpLoad %u32vec3 %id\n"
16988                 "%x         = OpCompositeExtract %u32 %idval 0\n"
16989
16990                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
16991                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
16992                 // Read the input value
16993                 "%inval     = OpLoad ${customType} %inloc\n"
16994                 // Create the composite and fill it
16995                 "${compositeConstruct}"
16996                 // Insert the input value to a place
16997                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
16998                 // Read back the value from the position
16999                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17000                 // Store it in the output position
17001                 "             OpStore %outloc %out_val\n"
17002                 "             OpReturn\n"
17003                 "             OpFunctionEnd\n"
17004         ).specialize(parameters);
17005 }
17006
17007 template<typename T>
17008 BufferSp createCompositeBuffer(T number)
17009 {
17010         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17011 }
17012
17013 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17014 {
17015         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17016         de::Random                                              rnd             (deStringHash(group->getName()));
17017
17018         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17019         {
17020                 NumberType                                              numberType              = NumberType(type);
17021                 const string                                    typeName                = getNumberTypeName(numberType);
17022                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17023                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17024                 vector<map<string, string> >    testCases;
17025
17026                 createCompositeCases(testCases, rnd, numberType);
17027
17028                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17029                 {
17030                         ComputeShaderSpec       spec;
17031
17032                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17033
17034                         switch (numberType)
17035                         {
17036                                 case NUMBERTYPE_INT32:
17037                                 {
17038                                         deInt32 number = getInt(rnd);
17039                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17040                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17041                                         break;
17042                                 }
17043                                 case NUMBERTYPE_UINT32:
17044                                 {
17045                                         deUint32 number = rnd.getUint32();
17046                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17047                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17048                                         break;
17049                                 }
17050                                 case NUMBERTYPE_FLOAT32:
17051                                 {
17052                                         float number = rnd.getFloat();
17053                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17054                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17055                                         break;
17056                                 }
17057                                 default:
17058                                         DE_ASSERT(false);
17059                         }
17060
17061                         spec.numWorkGroups = IVec3(1, 1, 1);
17062                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17063                 }
17064                 group->addChild(subGroup.release());
17065         }
17066         return group.release();
17067 }
17068
17069 struct AssemblyStructInfo
17070 {
17071         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17072         : components    (comp)
17073         , index                 (idx)
17074         {}
17075
17076         deUint32 components;
17077         deUint32 index;
17078 };
17079
17080 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17081 {
17082         // Create the full index string
17083         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17084         // Convert it to list of indexes
17085         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17086
17087         map<string, string>     parameters      (params);
17088         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17089         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17090         parameters["insertIndexes"]     = fullIndex;
17091
17092         // In matrix cases the last two index is the CompositeExtract indexes
17093         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17094
17095         // Construct the extractIndex
17096         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17097         {
17098                 parameters["extractIndexes"] += " " + *index;
17099         }
17100
17101         // Remove the last 1 or 2 element depends on matrix case or not
17102         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17103
17104         deUint32 id = 0;
17105         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17106         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17107         {
17108                 string indexId = "%index_" + numberToString(id++);
17109                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17110                 parameters["accessChainIndexes"] += " " + indexId;
17111         }
17112
17113         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17114
17115         const string customType = getAssemblyTypeName(type);
17116         map<string, string> substCustomType;
17117         substCustomType["customType"] = customType;
17118         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17119         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17120         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17121         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17122         parameters["customType"] = customType;
17123
17124         const string compositeType = parameters.at("compositeType");
17125         map<string, string> substCompositeType;
17126         substCompositeType["compositeType"] = compositeType;
17127         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17128         if (compositeType != "%u32vec3")
17129         {
17130                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17131         }
17132
17133         return StringTemplate(
17134                 "OpCapability Shader\n"
17135                 "OpCapability Matrix\n"
17136                 "OpMemoryModel Logical GLSL450\n"
17137                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17138                 "OpExecutionMode %main LocalSize 1 1 1\n"
17139
17140                 "OpSource GLSL 430\n"
17141                 "OpName %main           \"main\"\n"
17142                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17143                 // Decorators
17144                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17145                 "OpDecorate %buf BufferBlock\n"
17146                 "OpDecorate %indata DescriptorSet 0\n"
17147                 "OpDecorate %indata Binding 0\n"
17148                 "OpDecorate %outdata DescriptorSet 0\n"
17149                 "OpDecorate %outdata Binding 1\n"
17150                 "OpDecorate %customarr ArrayStride 4\n"
17151                 "${compositeDecorator}"
17152                 "OpMemberDecorate %buf 0 Offset 0\n"
17153                 // General types
17154                 "%void      = OpTypeVoid\n"
17155                 "%voidf     = OpTypeFunction %void\n"
17156                 "%i32       = OpTypeInt 32 1\n"
17157                 "%u32       = OpTypeInt 32 0\n"
17158                 "%f32       = OpTypeFloat 32\n"
17159                 // Custom types
17160                 "${compositeDecl}"
17161                 // %u32vec3 if not already declared in ${compositeDecl}
17162                 "${u32vec3Decl:opt}"
17163                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17164                 // Inherited from composite
17165                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17166                 "%struct_t  = OpTypeStruct${structType}\n"
17167                 "%struct_p  = OpTypePointer Function %struct_t\n"
17168                 // Constants
17169                 "${filler}"
17170                 "${accessChainConstDeclaration}"
17171                 // Inherited from custom
17172                 "%customptr = OpTypePointer Uniform ${customType}\n"
17173                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17174                 "%buf       = OpTypeStruct %customarr\n"
17175                 "%bufptr    = OpTypePointer Uniform %buf\n"
17176                 "%indata    = OpVariable %bufptr Uniform\n"
17177                 "%outdata   = OpVariable %bufptr Uniform\n"
17178
17179                 "%id        = OpVariable %uvec3ptr Input\n"
17180                 "%zero      = OpConstant %u32 0\n"
17181                 "%main      = OpFunction %void None %voidf\n"
17182                 "%label     = OpLabel\n"
17183                 "%struct_v  = OpVariable %struct_p Function\n"
17184                 "%idval     = OpLoad %u32vec3 %id\n"
17185                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17186                 // Create the input/output type
17187                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17188                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17189                 // Read the input value
17190                 "%inval     = OpLoad ${customType} %inloc\n"
17191                 // Create the composite and fill it
17192                 "${compositeConstruct}"
17193                 // Create the struct and fill it with the composite
17194                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17195                 // Insert the value
17196                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17197                 // Store the object
17198                 "             OpStore %struct_v %comp_obj\n"
17199                 // Get deepest possible composite pointer
17200                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17201                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17202                 // Read back the stored value
17203                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17204                 "             OpStore %outloc %read_val\n"
17205                 "             OpReturn\n"
17206                 "             OpFunctionEnd\n"
17207         ).specialize(parameters);
17208 }
17209
17210 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17211 {
17212         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17213         de::Random                                              rnd                             (deStringHash(group->getName()));
17214
17215         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17216         {
17217                 NumberType                                              numberType      = NumberType(type);
17218                 const string                                    typeName        = getNumberTypeName(numberType);
17219                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17220                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17221
17222                 vector<map<string, string> >    testCases;
17223                 createCompositeCases(testCases, rnd, numberType);
17224
17225                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17226                 {
17227                         ComputeShaderSpec       spec;
17228
17229                         // Number of components inside of a struct
17230                         deUint32 structComponents = rnd.getInt(2, 8);
17231                         // Component index value
17232                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17233                         AssemblyStructInfo structInfo(structComponents, structIndex);
17234
17235                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17236
17237                         switch (numberType)
17238                         {
17239                                 case NUMBERTYPE_INT32:
17240                                 {
17241                                         deInt32 number = getInt(rnd);
17242                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17243                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17244                                         break;
17245                                 }
17246                                 case NUMBERTYPE_UINT32:
17247                                 {
17248                                         deUint32 number = rnd.getUint32();
17249                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17250                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17251                                         break;
17252                                 }
17253                                 case NUMBERTYPE_FLOAT32:
17254                                 {
17255                                         float number = rnd.getFloat();
17256                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17257                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17258                                         break;
17259                                 }
17260                                 default:
17261                                         DE_ASSERT(false);
17262                         }
17263                         spec.numWorkGroups = IVec3(1, 1, 1);
17264                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17265                 }
17266                 group->addChild(subGroup.release());
17267         }
17268         return group.release();
17269 }
17270
17271 // If the params missing, uninitialized case
17272 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17273 {
17274         map<string, string> parameters(params);
17275
17276         parameters["customType"]        = getAssemblyTypeName(type);
17277
17278         // Declare the const value, and use it in the initializer
17279         if (params.find("constValue") != params.end())
17280         {
17281                 parameters["variableInitializer"]       = " %const";
17282         }
17283         // Uninitialized case
17284         else
17285         {
17286                 parameters["commentDecl"]       = ";";
17287         }
17288
17289         return StringTemplate(
17290                 "OpCapability Shader\n"
17291                 "OpMemoryModel Logical GLSL450\n"
17292                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17293                 "OpExecutionMode %main LocalSize 1 1 1\n"
17294                 "OpSource GLSL 430\n"
17295                 "OpName %main           \"main\"\n"
17296                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17297                 // Decorators
17298                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17299                 "OpDecorate %indata DescriptorSet 0\n"
17300                 "OpDecorate %indata Binding 0\n"
17301                 "OpDecorate %outdata DescriptorSet 0\n"
17302                 "OpDecorate %outdata Binding 1\n"
17303                 "OpDecorate %in_arr ArrayStride 4\n"
17304                 "OpDecorate %in_buf BufferBlock\n"
17305                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17306                 // Base types
17307                 "%void       = OpTypeVoid\n"
17308                 "%voidf      = OpTypeFunction %void\n"
17309                 "%u32        = OpTypeInt 32 0\n"
17310                 "%i32        = OpTypeInt 32 1\n"
17311                 "%f32        = OpTypeFloat 32\n"
17312                 "%uvec3      = OpTypeVector %u32 3\n"
17313                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17314                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17315                 // Derived types
17316                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17317                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17318                 "%in_buf     = OpTypeStruct %in_arr\n"
17319                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17320                 "%indata     = OpVariable %in_bufptr Uniform\n"
17321                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17322                 "%id         = OpVariable %uvec3ptr Input\n"
17323                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17324                 // Constants
17325                 "%zero       = OpConstant %i32 0\n"
17326                 // Main function
17327                 "%main       = OpFunction %void None %voidf\n"
17328                 "%label      = OpLabel\n"
17329                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17330                 "%idval      = OpLoad %uvec3 %id\n"
17331                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17332                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17333                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17334
17335                 "%outval     = OpLoad ${customType} %out_var\n"
17336                 "              OpStore %outloc %outval\n"
17337                 "              OpReturn\n"
17338                 "              OpFunctionEnd\n"
17339         ).specialize(parameters);
17340 }
17341
17342 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17343 {
17344         DE_ASSERT(outputAllocs.size() != 0);
17345         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17346
17347         // Use custom epsilon because of the float->string conversion
17348         const float     epsilon = 0.00001f;
17349
17350         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17351         {
17352                 vector<deUint8> expectedBytes;
17353                 float                   expected;
17354                 float                   actual;
17355
17356                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17357                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17358                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17359
17360                 // Test with epsilon
17361                 if (fabs(expected - actual) > epsilon)
17362                 {
17363                         log << TestLog::Message << "Error: The actual and expected values not matching."
17364                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17365                         return false;
17366                 }
17367         }
17368         return true;
17369 }
17370
17371 // Checks if the driver crash with uninitialized cases
17372 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17373 {
17374         DE_ASSERT(outputAllocs.size() != 0);
17375         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17376
17377         // Copy and discard the result.
17378         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17379         {
17380                 vector<deUint8> expectedBytes;
17381                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17382
17383                 const size_t    width                   = expectedBytes.size();
17384                 vector<char>    data                    (width);
17385
17386                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17387         }
17388         return true;
17389 }
17390
17391 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17392 {
17393         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17394         de::Random                                              rnd             (deStringHash(group->getName()));
17395
17396         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17397         {
17398                 NumberType                                              numberType      = NumberType(type);
17399                 const string                                    typeName        = getNumberTypeName(numberType);
17400                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17401                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17402
17403                 // 2 similar subcases (initialized and uninitialized)
17404                 for (int subCase = 0; subCase < 2; ++subCase)
17405                 {
17406                         ComputeShaderSpec spec;
17407                         spec.numWorkGroups = IVec3(1, 1, 1);
17408
17409                         map<string, string>                             params;
17410
17411                         switch (numberType)
17412                         {
17413                                 case NUMBERTYPE_INT32:
17414                                 {
17415                                         deInt32 number = getInt(rnd);
17416                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17417                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17418                                         params["constValue"] = numberToString(number);
17419                                         break;
17420                                 }
17421                                 case NUMBERTYPE_UINT32:
17422                                 {
17423                                         deUint32 number = rnd.getUint32();
17424                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17425                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17426                                         params["constValue"] = numberToString(number);
17427                                         break;
17428                                 }
17429                                 case NUMBERTYPE_FLOAT32:
17430                                 {
17431                                         float number = rnd.getFloat();
17432                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17433                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17434                                         spec.verifyIO = &compareFloats;
17435                                         params["constValue"] = numberToString(number);
17436                                         break;
17437                                 }
17438                                 default:
17439                                         DE_ASSERT(false);
17440                         }
17441
17442                         // Initialized subcase
17443                         if (!subCase)
17444                         {
17445                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17446                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17447                         }
17448                         // Uninitialized subcase
17449                         else
17450                         {
17451                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17452                                 spec.verifyIO = &passthruVerify;
17453                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17454                         }
17455                 }
17456                 group->addChild(subGroup.release());
17457         }
17458         return group.release();
17459 }
17460
17461 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17462 {
17463         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17464         RGBA                                                    defaultColors[4];
17465         map<string, string>                             opNopFragments;
17466
17467         getDefaultColors(defaultColors);
17468
17469         opNopFragments["testfun"]               =
17470                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17471                 "%param1 = OpFunctionParameter %v4f32\n"
17472                 "%label_testfun = OpLabel\n"
17473                 "OpNop\n"
17474                 "OpNop\n"
17475                 "OpNop\n"
17476                 "OpNop\n"
17477                 "OpNop\n"
17478                 "OpNop\n"
17479                 "OpNop\n"
17480                 "OpNop\n"
17481                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17482                 "%b = OpFAdd %f32 %a %a\n"
17483                 "OpNop\n"
17484                 "%c = OpFSub %f32 %b %a\n"
17485                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17486                 "OpNop\n"
17487                 "OpNop\n"
17488                 "OpReturnValue %ret\n"
17489                 "OpFunctionEnd\n";
17490
17491         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17492
17493         return testGroup.release();
17494 }
17495
17496 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17497 {
17498         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17499         RGBA                                                    defaultColors[4];
17500         map<string, string>                             opNameFragments;
17501
17502         getDefaultColors(defaultColors);
17503
17504         opNameFragments["testfun"] =
17505                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17506                 "%param1     = OpFunctionParameter %v4f32\n"
17507                 "%label_func = OpLabel\n"
17508                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17509                 "%b          = OpFAdd %f32 %a %a\n"
17510                 "%c          = OpFSub %f32 %b %a\n"
17511                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17512                 "OpReturnValue %ret\n"
17513                 "OpFunctionEnd\n";
17514
17515         opNameFragments["debug"] =
17516                 "OpName %BP_main \"not_main\"";
17517
17518         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17519
17520         return testGroup.release();
17521 }
17522
17523 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17524 {
17525         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17526
17527         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17528         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17529         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17530         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17531         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17532         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17533         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17534         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17535         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17536         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17537         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17538         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17539         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17540         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17541         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17542
17543         return testGroup.release();
17544 }
17545
17546 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17547 {
17548         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17549
17550         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17551         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17552         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17553         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17554         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17555         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17556         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17557         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17558         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17559         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17560         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17561         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17562         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17563         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17564         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17565
17566         return testGroup.release();
17567 }
17568
17569 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17570 {
17571         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17572
17573         de::Random                                              rnd                             (deStringHash(group->getName()));
17574         const int               numElements             = 100;
17575         vector<float>   inputData               (numElements, 0);
17576         vector<float>   outputData              (numElements, 0);
17577         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17578
17579         const StringTemplate                    shaderTemplate  (
17580                 "${CAPS}\n"
17581                 "OpMemoryModel Logical GLSL450\n"
17582                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17583                 "OpExecutionMode %main LocalSize 1 1 1\n"
17584                 "OpSource GLSL 430\n"
17585                 "OpName %main           \"main\"\n"
17586                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17587
17588                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17589
17590                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17591
17592                 "%id        = OpVariable %uvec3ptr Input\n"
17593                 "${CONST}\n"
17594                 "%main      = OpFunction %void None %voidf\n"
17595                 "%label     = OpLabel\n"
17596                 "%idval     = OpLoad %uvec3 %id\n"
17597                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17598                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17599
17600                 "${TEST}\n"
17601
17602                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17603                 "             OpStore %outloc %res\n"
17604                 "             OpReturn\n"
17605                 "             OpFunctionEnd\n"
17606         );
17607
17608         // Each test case produces 4 boolean values, and we want each of these values
17609         // to come froma different combination of the available bit-sizes, so compute
17610         // all possible combinations here.
17611         vector<deUint32>        widths;
17612         widths.push_back(32);
17613         widths.push_back(16);
17614         widths.push_back(8);
17615
17616         vector<IVec4>   cases;
17617         for (size_t width0 = 0; width0 < widths.size(); width0++)
17618         {
17619                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17620                 {
17621                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17622                         {
17623                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17624                                 {
17625                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17626                                 }
17627                         }
17628                 }
17629         }
17630
17631         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17632         {
17633                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17634                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17635                         continue;
17636
17637                 map<string, string>     specializations;
17638                 ComputeShaderSpec       spec;
17639
17640                 // Inject appropriate capabilities and reference constants depending
17641                 // on the bit-sizes required by this test case
17642                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17643                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17644                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17645
17646                 string capsStr  = "OpCapability Shader\n";
17647                 string constStr =
17648                         "%c0i32     = OpConstant %i32 0\n"
17649                         "%c1f32     = OpConstant %f32 1.0\n"
17650                         "%c0f32     = OpConstant %f32 0.0\n";
17651
17652                 if (hasFloat32)
17653                 {
17654                         constStr        +=
17655                                 "%c10f32    = OpConstant %f32 10.0\n"
17656                                 "%c25f32    = OpConstant %f32 25.0\n"
17657                                 "%c50f32    = OpConstant %f32 50.0\n"
17658                                 "%c90f32    = OpConstant %f32 90.0\n";
17659                 }
17660
17661                 if (hasFloat16)
17662                 {
17663                         capsStr         += "OpCapability Float16\n";
17664                         constStr        +=
17665                                 "%f16       = OpTypeFloat 16\n"
17666                                 "%c10f16    = OpConstant %f16 10.0\n"
17667                                 "%c25f16    = OpConstant %f16 25.0\n"
17668                                 "%c50f16    = OpConstant %f16 50.0\n"
17669                                 "%c90f16    = OpConstant %f16 90.0\n";
17670                 }
17671
17672                 if (hasInt8)
17673                 {
17674                         capsStr         += "OpCapability Int8\n";
17675                         constStr        +=
17676                                 "%i8        = OpTypeInt 8 1\n"
17677                                 "%c10i8     = OpConstant %i8 10\n"
17678                                 "%c25i8     = OpConstant %i8 25\n"
17679                                 "%c50i8     = OpConstant %i8 50\n"
17680                                 "%c90i8     = OpConstant %i8 90\n";
17681                 }
17682
17683                 // Each invocation reads a different float32 value as input. Depending on
17684                 // the bit-sizes required by the particular test case, we also produce
17685                 // float16 and/or and int8 values by converting from the 32-bit float.
17686                 string testStr  = "";
17687                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
17688                 if (hasFloat16)
17689                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
17690                 if (hasInt8)
17691                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
17692
17693                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17694                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17695                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17696                 // other way around, so in this case we want < instead of <=.
17697                 if (cases[caseNdx][0] == 32)
17698                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17699                 else if (cases[caseNdx][0] == 16)
17700                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17701                 else
17702                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17703
17704                 if (cases[caseNdx][1] == 32)
17705                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17706                 else if (cases[caseNdx][1] == 16)
17707                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17708                 else
17709                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17710
17711                 if (cases[caseNdx][2] == 32)
17712                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17713                 else if (cases[caseNdx][2] == 16)
17714                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17715                 else
17716                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17717
17718                 if (cases[caseNdx][3] == 32)
17719                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17720                 else if (cases[caseNdx][3] == 16)
17721                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17722                 else
17723                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17724
17725                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17726                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17727                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
17728                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
17729                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17730
17731                 specializations["CAPS"]         = capsStr;
17732                 specializations["CONST"]        = constStr;
17733                 specializations["TEST"]         = testStr;
17734
17735                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
17736                 for (size_t ndx = 0; ndx < numElements; ++ndx)
17737                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17738
17739                 spec.assembly = shaderTemplate.specialize(specializations);
17740                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17741                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17742                 spec.numWorkGroups = IVec3(numElements, 1, 1);
17743                 if (hasFloat16)
17744                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17745                 if (hasInt8)
17746                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17747                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
17748
17749                 string testName = "b" + de::toString(cases[caseNdx][0]) + "b" + de::toString(cases[caseNdx][1]) + "b" + de::toString(cases[caseNdx][2]) + "b" + de::toString(cases[caseNdx][3]);
17750                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17751         }
17752
17753         return group.release();
17754 }
17755
17756 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17757 {
17758         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17759
17760         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17761
17762         return testGroup.release();
17763 }
17764
17765 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17766 {
17767         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17768         vector<CaseParameter>                   abuseCases;
17769         RGBA                                                    defaultColors[4];
17770         map<string, string>                             opNameFragments;
17771
17772         getOpNameAbuseCases(abuseCases);
17773         getDefaultColors(defaultColors);
17774
17775         opNameFragments["testfun"] =
17776                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17777                 "%param1     = OpFunctionParameter %v4f32\n"
17778                 "%label_func = OpLabel\n"
17779                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17780                 "%b          = OpFAdd %f32 %a %a\n"
17781                 "%c          = OpFSub %f32 %b %a\n"
17782                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17783                 "OpReturnValue %ret\n"
17784                 "OpFunctionEnd\n";
17785
17786         for (unsigned int i = 0; i < abuseCases.size(); i++)
17787         {
17788                 string casename;
17789                 casename = string("main") + abuseCases[i].name;
17790
17791                 opNameFragments["debug"] =
17792                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
17793
17794                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17795         }
17796
17797         for (unsigned int i = 0; i < abuseCases.size(); i++)
17798         {
17799                 string casename;
17800                 casename = string("b") + abuseCases[i].name;
17801
17802                 opNameFragments["debug"] =
17803                         "OpName %b \"" + abuseCases[i].param + "\"";
17804
17805                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17806         }
17807
17808         {
17809                 opNameFragments["debug"] =
17810                         "OpName %test_code \"name1\"\n"
17811                         "OpName %param1    \"name2\"\n"
17812                         "OpName %a         \"name3\"\n"
17813                         "OpName %b         \"name4\"\n"
17814                         "OpName %c         \"name5\"\n"
17815                         "OpName %ret       \"name6\"\n";
17816
17817                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17818         }
17819
17820         {
17821                 opNameFragments["debug"] =
17822                         "OpName %test_code \"the_same\"\n"
17823                         "OpName %param1    \"the_same\"\n"
17824                         "OpName %a         \"the_same\"\n"
17825                         "OpName %b         \"the_same\"\n"
17826                         "OpName %c         \"the_same\"\n"
17827                         "OpName %ret       \"the_same\"\n";
17828
17829                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17830         }
17831
17832         {
17833                 opNameFragments["debug"] =
17834                         "OpName %BP_main \"to_be\"\n"
17835                         "OpName %BP_main \"or_not\"\n"
17836                         "OpName %BP_main \"to_be\"\n";
17837
17838                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17839         }
17840
17841         {
17842                 opNameFragments["debug"] =
17843                         "OpName %b \"to_be\"\n"
17844                         "OpName %b \"or_not\"\n"
17845                         "OpName %b \"to_be\"\n";
17846
17847                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17848         }
17849
17850         return abuseGroup.release();
17851 }
17852
17853
17854 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
17855 {
17856         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
17857         vector<CaseParameter>                   abuseCases;
17858         RGBA                                                    defaultColors[4];
17859         map<string, string>                             opMemberNameFragments;
17860
17861         getOpNameAbuseCases(abuseCases);
17862         getDefaultColors(defaultColors);
17863
17864         opMemberNameFragments["pre_main"] =
17865                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
17866
17867         opMemberNameFragments["testfun"] =
17868                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17869                 "%param1     = OpFunctionParameter %v4f32\n"
17870                 "%label_func = OpLabel\n"
17871                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17872                 "%b          = OpFAdd %f32 %a %a\n"
17873                 "%c          = OpFSub %f32 %b %a\n"
17874                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
17875                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
17876                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
17877                 "OpReturnValue %ret\n"
17878                 "OpFunctionEnd\n";
17879
17880         for (unsigned int i = 0; i < abuseCases.size(); i++)
17881         {
17882                 string casename;
17883                 casename = string("f3str_x") + abuseCases[i].name;
17884
17885                 opMemberNameFragments["debug"] =
17886                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
17887
17888                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
17889         }
17890
17891         {
17892                 opMemberNameFragments["debug"] =
17893                         "OpMemberName %f3str 0 \"name1\"\n"
17894                         "OpMemberName %f3str 1 \"name2\"\n"
17895                         "OpMemberName %f3str 2 \"name3\"\n";
17896
17897                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
17898         }
17899
17900         {
17901                 opMemberNameFragments["debug"] =
17902                         "OpMemberName %f3str 0 \"the_same\"\n"
17903                         "OpMemberName %f3str 1 \"the_same\"\n"
17904                         "OpMemberName %f3str 2 \"the_same\"\n";
17905
17906                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
17907         }
17908
17909         {
17910                 opMemberNameFragments["debug"] =
17911                         "OpMemberName %f3str 0 \"to_be\"\n"
17912                         "OpMemberName %f3str 1 \"or_not\"\n"
17913                         "OpMemberName %f3str 0 \"to_be\"\n"
17914                         "OpMemberName %f3str 2 \"makes_no\"\n"
17915                         "OpMemberName %f3str 0 \"difference\"\n"
17916                         "OpMemberName %f3str 0 \"to_me\"\n";
17917
17918
17919                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
17920         }
17921
17922         return abuseGroup.release();
17923 }
17924
17925 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
17926 {
17927         vector<deUint32>        result;
17928         de::Random                      rnd             (seed);
17929
17930         result.reserve(numDataPoints);
17931
17932         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
17933                 result.push_back(rnd.getUint32());
17934
17935         return result;
17936 }
17937
17938 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
17939 {
17940         vector<deUint32>        result;
17941
17942         result.reserve(inData1.size());
17943
17944         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
17945                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
17946
17947         return result;
17948 }
17949
17950 template<class SpecResource>
17951 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
17952 {
17953         const deUint32                  numDataPoints   = 16;
17954         const std::string               testName                ("sparse_ids");
17955         const deUint32                  seed                    (deStringHash(testName.c_str()));
17956         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
17957         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
17958         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
17959         const StringTemplate    preMain
17960         (
17961                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
17962                 "   %up_u32 = OpTypePointer Uniform %u32\n"
17963                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
17964                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
17965                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
17966                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
17967                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
17968                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
17969         );
17970         const StringTemplate    decoration
17971         (
17972                 "OpDecorate %ra_u32 ArrayStride 4\n"
17973                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
17974                 "OpDecorate %SSBO32 BufferBlock\n"
17975                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
17976                 "OpDecorate %ssbo_src0 Binding 0\n"
17977                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
17978                 "OpDecorate %ssbo_src1 Binding 1\n"
17979                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
17980                 "OpDecorate %ssbo_dst Binding 2\n"
17981         );
17982         const StringTemplate    testFun
17983         (
17984                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17985                 "    %param = OpFunctionParameter %v4f32\n"
17986
17987                 "    %entry = OpLabel\n"
17988                 "        %i = OpVariable %fp_i32 Function\n"
17989                 "             OpStore %i %c_i32_0\n"
17990                 "             OpBranch %loop\n"
17991
17992                 "     %loop = OpLabel\n"
17993                 "    %i_cmp = OpLoad %i32 %i\n"
17994                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
17995                 "             OpLoopMerge %merge %next None\n"
17996                 "             OpBranchConditional %lt %write %merge\n"
17997
17998                 "    %write = OpLabel\n"
17999                 "      %ndx = OpLoad %i32 %i\n"
18000
18001                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18002                 "      %128 = OpLoad %u32 %127\n"
18003
18004                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18005                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18006                 "  %4194001 = OpLoad %u32 %4194000\n"
18007
18008                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18009                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18010                 "             OpStore %2097152 %2097151\n"
18011                 "             OpBranch %next\n"
18012
18013                 "     %next = OpLabel\n"
18014                 "    %i_cur = OpLoad %i32 %i\n"
18015                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18016                 "             OpStore %i %i_new\n"
18017                 "             OpBranch %loop\n"
18018
18019                 "    %merge = OpLabel\n"
18020                 "             OpReturnValue %param\n"
18021
18022                 "             OpFunctionEnd\n"
18023         );
18024         SpecResource                    specResource;
18025         map<string, string>             specs;
18026         VulkanFeatures                  features;
18027         map<string, string>             fragments;
18028         vector<string>                  extensions;
18029
18030         specs["num_data_points"]        = de::toString(numDataPoints);
18031
18032         fragments["decoration"]         = decoration.specialize(specs);
18033         fragments["pre_main"]           = preMain.specialize(specs);
18034         fragments["testfun"]            = testFun.specialize(specs);
18035
18036         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18037         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18038         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18039
18040         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18041         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18042
18043         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18044 }
18045
18046 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18047 {
18048         vector<deUint32>        result;
18049         de::Random                      rnd             (seed);
18050
18051         result.reserve(numDataPoints);
18052
18053         // Fixed value
18054         result.push_back(1u);
18055
18056         // Random values
18057         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18058                 result.push_back(rnd.getUint8());
18059
18060         return result;
18061 }
18062
18063 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18064 {
18065         vector<deUint32>        result;
18066
18067         result.reserve(inData1.size());
18068
18069         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18070                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18071
18072         return result;
18073 }
18074
18075 template<class SpecResource>
18076 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18077 {
18078         const deUint32                  numDataPoints   = 16;
18079         const deUint32                  firstNdx                = 100u;
18080         const deUint32                  sequenceCount   = 10000u;
18081         const std::string               testName                ("lots_ids");
18082         const deUint32                  seed                    (deStringHash(testName.c_str()));
18083         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18084         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18085         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18086         const StringTemplate preMain
18087         (
18088                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18089                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18090                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18091                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18092                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18093                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18094                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18095                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18096         );
18097         const StringTemplate decoration
18098         (
18099                 "OpDecorate %ra_u32 ArrayStride 4\n"
18100                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18101                 "OpDecorate %SSBO32 BufferBlock\n"
18102                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18103                 "OpDecorate %ssbo_src0 Binding 0\n"
18104                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18105                 "OpDecorate %ssbo_src1 Binding 1\n"
18106                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18107                 "OpDecorate %ssbo_dst Binding 2\n"
18108         );
18109         const StringTemplate testFun
18110         (
18111                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18112                 "    %param = OpFunctionParameter %v4f32\n"
18113
18114                 "    %entry = OpLabel\n"
18115                 "        %i = OpVariable %fp_i32 Function\n"
18116                 "             OpStore %i %c_i32_0\n"
18117                 "             OpBranch %loop\n"
18118
18119                 "     %loop = OpLabel\n"
18120                 "    %i_cmp = OpLoad %i32 %i\n"
18121                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18122                 "             OpLoopMerge %merge %next None\n"
18123                 "             OpBranchConditional %lt %write %merge\n"
18124
18125                 "    %write = OpLabel\n"
18126                 "      %ndx = OpLoad %i32 %i\n"
18127
18128                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18129                 "       %91 = OpLoad %u32 %90\n"
18130
18131                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18132                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18133
18134                 "${seq}\n"
18135
18136                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18137                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18138                 "             OpStore %dst %${last_id}\n"
18139                 "             OpBranch %next\n"
18140
18141                 "     %next = OpLabel\n"
18142                 "    %i_cur = OpLoad %i32 %i\n"
18143                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18144                 "             OpStore %i %i_new\n"
18145                 "             OpBranch %loop\n"
18146
18147                 "    %merge = OpLabel\n"
18148                 "             OpReturnValue %param\n"
18149
18150                 "             OpFunctionEnd\n"
18151         );
18152         deUint32                                lastId                  = firstNdx;
18153         SpecResource                    specResource;
18154         map<string, string>             specs;
18155         VulkanFeatures                  features;
18156         map<string, string>             fragments;
18157         vector<string>                  extensions;
18158         std::string                             sequence;
18159
18160         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18161         {
18162                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18163                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18164
18165                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18166                 lastId = sequenceId;
18167
18168                 if (sequenceNdx == 0)
18169                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18170         }
18171
18172         specs["num_data_points"]        = de::toString(numDataPoints);
18173         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18174         specs["last_id"]                        = de::toString(lastId);
18175         specs["seq"]                            = sequence;
18176
18177         fragments["decoration"]         = decoration.specialize(specs);
18178         fragments["pre_main"]           = preMain.specialize(specs);
18179         fragments["testfun"]            = testFun.specialize(specs);
18180
18181         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18182         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18183         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18184
18185         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18186         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18187
18188         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18189 }
18190
18191 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18192 {
18193         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18194
18195         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18196         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18197
18198         return testGroup.release();
18199 }
18200
18201 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18202 {
18203         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18204
18205         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18206         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18207
18208         return testGroup.release();
18209 }
18210
18211 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18212 {
18213         const bool testComputePipeline = true;
18214
18215         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18216         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18217         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18218
18219         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18220         computeTests->addChild(createLocalSizeGroup(testCtx));
18221         computeTests->addChild(createOpNopGroup(testCtx));
18222         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18223         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18224         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18225         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18226         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18227         computeTests->addChild(createOpAtomicGroup(testCtx, true, 65536, false, true)); // volatile atomics
18228         computeTests->addChild(createOpLineGroup(testCtx));
18229         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18230         computeTests->addChild(createOpNoLineGroup(testCtx));
18231         computeTests->addChild(createOpConstantNullGroup(testCtx));
18232         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18233         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18234         computeTests->addChild(createSpecConstantGroup(testCtx));
18235         computeTests->addChild(createOpSourceGroup(testCtx));
18236         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18237         computeTests->addChild(createDecorationGroupGroup(testCtx));
18238         computeTests->addChild(createOpPhiGroup(testCtx));
18239         computeTests->addChild(createLoopControlGroup(testCtx));
18240         computeTests->addChild(createFunctionControlGroup(testCtx));
18241         computeTests->addChild(createSelectionControlGroup(testCtx));
18242         computeTests->addChild(createBlockOrderGroup(testCtx));
18243         computeTests->addChild(createMultipleShaderGroup(testCtx));
18244         computeTests->addChild(createMemoryAccessGroup(testCtx));
18245         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18246         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18247         computeTests->addChild(createNoContractionGroup(testCtx));
18248         computeTests->addChild(createOpUndefGroup(testCtx));
18249         computeTests->addChild(createOpUnreachableGroup(testCtx));
18250         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18251         computeTests->addChild(createOpFRemGroup(testCtx));
18252         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18253         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18254         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18255         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18256         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18257         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18258         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18259         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18260         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18261         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18262         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18263         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18264         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18265         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18266         computeTests->addChild(createOpNMinGroup(testCtx));
18267         computeTests->addChild(createOpNMaxGroup(testCtx));
18268         computeTests->addChild(createOpNClampGroup(testCtx));
18269         computeTests->addChild(createFloatControlsExtensionlessGroup(testCtx));
18270         {
18271                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18272
18273                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18274                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18275
18276                 computeTests->addChild(computeAndroidTests.release());
18277         }
18278
18279         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18280         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18281         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18282         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18283         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18284         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18285         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18286         computeTests->addChild(createIndexingComputeGroup(testCtx));
18287         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18288         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18289         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18290         computeTests->addChild(createOpNameGroup(testCtx));
18291         computeTests->addChild(createOpMemberNameGroup(testCtx));
18292         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18293         computeTests->addChild(createFloat16Group(testCtx));
18294         computeTests->addChild(createBoolGroup(testCtx));
18295         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18296         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18297         computeTests->addChild(createSignedIntCompareGroup(testCtx));
18298         computeTests->addChild(createUnusedVariableComputeTests(testCtx));
18299         computeTests->addChild(createPtrAccessChainGroup(testCtx));
18300
18301         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18302         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18303         graphicsTests->addChild(createOpNopTests(testCtx));
18304         graphicsTests->addChild(createOpSourceTests(testCtx));
18305         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18306         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18307         graphicsTests->addChild(createOpLineTests(testCtx));
18308         graphicsTests->addChild(createOpNoLineTests(testCtx));
18309         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18310         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18311         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18312         graphicsTests->addChild(createOpUndefTests(testCtx));
18313         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18314         graphicsTests->addChild(createModuleTests(testCtx));
18315         graphicsTests->addChild(createUnusedVariableTests(testCtx));
18316         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18317         graphicsTests->addChild(createOpPhiTests(testCtx));
18318         graphicsTests->addChild(createNoContractionTests(testCtx));
18319         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18320         graphicsTests->addChild(createLoopTests(testCtx));
18321         graphicsTests->addChild(createSpecConstantTests(testCtx));
18322         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18323         graphicsTests->addChild(createBarrierTests(testCtx));
18324         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18325         graphicsTests->addChild(createFRemTests(testCtx));
18326         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18327         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18328
18329         {
18330                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18331
18332                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18333                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18334
18335                 graphicsTests->addChild(graphicsAndroidTests.release());
18336         }
18337         graphicsTests->addChild(createOpNameTests(testCtx));
18338         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18339         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18340
18341         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18342         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18343         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18344         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18345         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18346         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18347         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18348         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18349         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18350         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18351         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18352         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18353         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18354         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18355         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18356         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18357         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18358         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18359         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18360         graphicsTests->addChild(createFloat16Tests(testCtx));
18361         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18362
18363         instructionTests->addChild(computeTests.release());
18364         instructionTests->addChild(graphicsTests.release());
18365         instructionTests->addChild(createSpirvVersion1p4Group(testCtx));
18366
18367         return instructionTests.release();
18368 }
18369
18370 } // SpirVAssembly
18371 } // vkt