Merge vk-gl-cts/vulkan-cts-1.1.4 into vk-gl-cts/vulkan-cts-1.1.5
[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 "vktSpvAsmSpirvVersionTests.hpp"
69 #include "vktTestCaseUtil.hpp"
70 #include "vktSpvAsmLoopDepLenTests.hpp"
71 #include "vktSpvAsmLoopDepInfTests.hpp"
72 #include "vktSpvAsmCompositeInsertTests.hpp"
73 #include "vktSpvAsmVaryingNameTests.hpp"
74 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
75 #include "vktSpvAsmSignedIntCompareTests.hpp"
76 #include "vktSpvAsmPtrAccessChainTests.hpp"
77
78 #include <cmath>
79 #include <limits>
80 #include <map>
81 #include <string>
82 #include <sstream>
83 #include <utility>
84 #include <stack>
85
86 namespace vkt
87 {
88 namespace SpirVAssembly
89 {
90
91 namespace
92 {
93
94 using namespace vk;
95 using std::map;
96 using std::string;
97 using std::vector;
98 using tcu::IVec3;
99 using tcu::IVec4;
100 using tcu::RGBA;
101 using tcu::TestLog;
102 using tcu::TestStatus;
103 using tcu::Vec4;
104 using de::UniquePtr;
105 using tcu::StringTemplate;
106 using tcu::Vec4;
107
108 const bool TEST_WITH_NAN        = true;
109 const bool TEST_WITHOUT_NAN     = false;
110
111 template<typename T>
112 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
113 {
114         T* const typedPtr = (T*)dst;
115         for (int ndx = 0; ndx < numValues; ndx++)
116                 typedPtr[offset + ndx] = de::randomScalar<T>(rnd, minValue, maxValue);
117 }
118
119 // Filter is a function that returns true if a value should pass, false otherwise.
120 template<typename T, typename FilterT>
121 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
122 {
123         T* const typedPtr = (T*)dst;
124         T value;
125         for (int ndx = 0; ndx < numValues; ndx++)
126         {
127                 do
128                         value = de::randomScalar<T>(rnd, minValue, maxValue);
129                 while (!filter(value));
130
131                 typedPtr[offset + ndx] = value;
132         }
133 }
134
135 // Gets a 64-bit integer with a more logarithmic distribution
136 deInt64 randomInt64LogDistributed (de::Random& rnd)
137 {
138         deInt64 val = rnd.getUint64();
139         val &= (1ull << rnd.getInt(1, 63)) - 1;
140         if (rnd.getBool())
141                 val = -val;
142         return val;
143 }
144
145 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
146 {
147         for (int ndx = 0; ndx < numValues; ndx++)
148                 dst[ndx] = randomInt64LogDistributed(rnd);
149 }
150
151 template<typename FilterT>
152 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
153 {
154         for (int ndx = 0; ndx < numValues; ndx++)
155         {
156                 deInt64 value;
157                 do {
158                         value = randomInt64LogDistributed(rnd);
159                 } while (!filter(value));
160                 dst[ndx] = value;
161         }
162 }
163
164 inline bool filterNonNegative (const deInt64 value)
165 {
166         return value >= 0;
167 }
168
169 inline bool filterPositive (const deInt64 value)
170 {
171         return value > 0;
172 }
173
174 inline bool filterNotZero (const deInt64 value)
175 {
176         return value != 0;
177 }
178
179 static void floorAll (vector<float>& values)
180 {
181         for (size_t i = 0; i < values.size(); i++)
182                 values[i] = deFloatFloor(values[i]);
183 }
184
185 static void floorAll (vector<Vec4>& values)
186 {
187         for (size_t i = 0; i < values.size(); i++)
188                 values[i] = floor(values[i]);
189 }
190
191 struct CaseParameter
192 {
193         const char*             name;
194         string                  param;
195
196         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
197 };
198
199 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
200 //
201 // #version 430
202 //
203 // layout(std140, set = 0, binding = 0) readonly buffer Input {
204 //   float elements[];
205 // } input_data;
206 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
207 //   float elements[];
208 // } output_data;
209 //
210 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
211 //
212 // void main() {
213 //   uint x = gl_GlobalInvocationID.x;
214 //   output_data.elements[x] = -input_data.elements[x];
215 // }
216
217 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
218 {
219         std::ostringstream out;
220         out << getComputeAsmShaderPreambleWithoutLocalSize();
221
222         if (useLiteralLocalSize)
223         {
224                 out << "OpExecutionMode %main LocalSize "
225                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
226         }
227
228         out << "OpSource GLSL 430\n"
229                 "OpName %main           \"main\"\n"
230                 "OpName %id             \"gl_GlobalInvocationID\"\n"
231                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
232
233         if (useSpecConstantWorkgroupSize)
234         {
235                 out << "OpDecorate %spec_0 SpecId 100\n"
236                         << "OpDecorate %spec_1 SpecId 101\n"
237                         << "OpDecorate %spec_2 SpecId 102\n"
238                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
239         }
240
241         out << getComputeAsmInputOutputBufferTraits()
242                 << getComputeAsmCommonTypes()
243                 << getComputeAsmInputOutputBuffer()
244                 << "%id        = OpVariable %uvec3ptr Input\n"
245                 << "%zero      = OpConstant %i32 0 \n";
246
247         if (useSpecConstantWorkgroupSize)
248         {
249                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
250                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
251                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
252                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
253         }
254
255         out << "%main      = OpFunction %void None %voidf\n"
256                 << "%label     = OpLabel\n"
257                 << "%idval     = OpLoad %uvec3 %id\n"
258                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
259
260                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
261                         "%inval     = OpLoad %f32 %inloc\n"
262                         "%neg       = OpFNegate %f32 %inval\n"
263                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
264                         "             OpStore %outloc %neg\n"
265                         "             OpReturn\n"
266                         "             OpFunctionEnd\n";
267         return out.str();
268 }
269
270 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
271 {
272         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
273         ComputeShaderSpec                               spec;
274         de::Random                                              rnd                             (deStringHash(group->getName()));
275         const deUint32                                  numElements             = 64u;
276         vector<float>                                   positiveFloats  (numElements, 0);
277         vector<float>                                   negativeFloats  (numElements, 0);
278
279         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
280
281         for (size_t ndx = 0; ndx < numElements; ++ndx)
282                 negativeFloats[ndx] = -positiveFloats[ndx];
283
284         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
285         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
286
287         spec.numWorkGroups = IVec3(numElements, 1, 1);
288
289         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
290         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
291
292         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
293         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
294
295         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
296         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
297
298         spec.numWorkGroups = IVec3(1, 1, 1);
299
300         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
302
303         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
305
306         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
307         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
308
309         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
310         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
311
312         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
314
315         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
316         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
317
318         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
319         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
320
321         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
322         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
323
324         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
325         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
326
327         return group.release();
328 }
329
330 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
331 {
332         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
333         ComputeShaderSpec                               spec;
334         de::Random                                              rnd                             (deStringHash(group->getName()));
335         const int                                               numElements             = 100;
336         vector<float>                                   positiveFloats  (numElements, 0);
337         vector<float>                                   negativeFloats  (numElements, 0);
338
339         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
340
341         for (size_t ndx = 0; ndx < numElements; ++ndx)
342                 negativeFloats[ndx] = -positiveFloats[ndx];
343
344         spec.assembly =
345                 string(getComputeAsmShaderPreamble()) +
346
347                 "OpSource GLSL 430\n"
348                 "OpName %main           \"main\"\n"
349                 "OpName %id             \"gl_GlobalInvocationID\"\n"
350
351                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
352
353                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
354
355                 + string(getComputeAsmInputOutputBuffer()) +
356
357                 "%id        = OpVariable %uvec3ptr Input\n"
358                 "%zero      = OpConstant %i32 0\n"
359
360                 "%main      = OpFunction %void None %voidf\n"
361                 "%label     = OpLabel\n"
362                 "%idval     = OpLoad %uvec3 %id\n"
363                 "%x         = OpCompositeExtract %u32 %idval 0\n"
364
365                 "             OpNop\n" // Inside a function body
366
367                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
368                 "%inval     = OpLoad %f32 %inloc\n"
369                 "%neg       = OpFNegate %f32 %inval\n"
370                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
371                 "             OpStore %outloc %neg\n"
372                 "             OpReturn\n"
373                 "             OpFunctionEnd\n";
374         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
375         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
376         spec.numWorkGroups = IVec3(numElements, 1, 1);
377
378         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
379
380         return group.release();
381 }
382
383 tcu::TestCaseGroup* createUnusedVariableComputeTests (tcu::TestContext& testCtx)
384 {
385         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "unused_variables", "Compute shaders with unused variables"));
386         de::Random                                              rnd                             (deStringHash(group->getName()));
387         const int                                               numElements             = 100;
388         vector<float>                                   positiveFloats  (numElements, 0);
389         vector<float>                                   negativeFloats  (numElements, 0);
390
391         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
392
393         for (size_t ndx = 0; ndx < numElements; ++ndx)
394                 negativeFloats[ndx] = -positiveFloats[ndx];
395
396         const VariableLocation                  testLocations[] =
397         {
398                 // Set          Binding
399                 { 0,            5                       },
400                 { 5,            5                       },
401         };
402
403         for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
404         {
405                 const VariableLocation& location = testLocations[locationNdx];
406
407                 // Unused variable.
408                 {
409                         ComputeShaderSpec                               spec;
410
411                         spec.assembly =
412                                 string(getComputeAsmShaderPreamble()) +
413
414                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
415
416                                 + getUnusedDecorations(location)
417
418                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
419
420                                 + getUnusedTypesAndConstants()
421
422                                 + string(getComputeAsmInputOutputBuffer())
423
424                                 + getUnusedBuffer() +
425
426                                 "%id        = OpVariable %uvec3ptr Input\n"
427                                 "%zero      = OpConstant %i32 0\n"
428
429                                 "%main      = OpFunction %void None %voidf\n"
430                                 "%label     = OpLabel\n"
431                                 "%idval     = OpLoad %uvec3 %id\n"
432                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
433
434                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
435                                 "%inval     = OpLoad %f32 %inloc\n"
436                                 "%neg       = OpFNegate %f32 %inval\n"
437                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
438                                 "             OpStore %outloc %neg\n"
439                                 "             OpReturn\n"
440                                 "             OpFunctionEnd\n";
441                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
442                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
443                         spec.numWorkGroups = IVec3(numElements, 1, 1);
444
445                         std::string testName            = "variable_" + location.toString();
446                         std::string testDescription     = "Unused variable test with " + location.toDescription();
447
448                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
449                 }
450
451                 // Unused function.
452                 {
453                         ComputeShaderSpec                               spec;
454
455                         spec.assembly =
456                                 string(getComputeAsmShaderPreamble("", "", "", getUnusedEntryPoint())) +
457
458                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
459
460                                 + getUnusedDecorations(location)
461
462                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
463
464                                 + getUnusedTypesAndConstants() +
465
466                                 "%c_i32_0 = OpConstant %i32 0\n"
467                                 "%c_i32_1 = OpConstant %i32 1\n"
468
469                                 + string(getComputeAsmInputOutputBuffer())
470
471                                 + getUnusedBuffer() +
472
473                                 "%id        = OpVariable %uvec3ptr Input\n"
474                                 "%zero      = OpConstant %i32 0\n"
475
476                                 "%main      = OpFunction %void None %voidf\n"
477                                 "%label     = OpLabel\n"
478                                 "%idval     = OpLoad %uvec3 %id\n"
479                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
480
481                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
482                                 "%inval     = OpLoad %f32 %inloc\n"
483                                 "%neg       = OpFNegate %f32 %inval\n"
484                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
485                                 "             OpStore %outloc %neg\n"
486                                 "             OpReturn\n"
487                                 "             OpFunctionEnd\n"
488
489                                 + getUnusedFunctionBody();
490
491                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
492                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
493                         spec.numWorkGroups = IVec3(numElements, 1, 1);
494
495                         std::string testName            = "function_" + location.toString();
496                         std::string testDescription     = "Unused function test with " + location.toDescription();
497
498                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
499                 }
500         }
501
502         return group.release();
503 }
504
505 template<bool nanSupported>
506 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
507 {
508         if (outputAllocs.size() != 1)
509                 return false;
510
511         vector<deUint8> input1Bytes;
512         vector<deUint8> input2Bytes;
513         vector<deUint8> expectedBytes;
514
515         inputs[0].getBytes(input1Bytes);
516         inputs[1].getBytes(input2Bytes);
517         expectedOutputs[0].getBytes(expectedBytes);
518
519         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
520         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
521         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
522         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
523         bool returnValue                                                                = true;
524
525         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
526         {
527                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
528                         continue;
529
530                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
531                 {
532                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
533                         returnValue = false;
534                 }
535         }
536         return returnValue;
537 }
538
539 typedef VkBool32 (*compareFuncType) (float, float);
540
541 struct OpFUnordCase
542 {
543         const char*             name;
544         const char*             opCode;
545         compareFuncType compareFunc;
546
547                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
548                                                 : name                          (_name)
549                                                 , opCode                        (_opCode)
550                                                 , compareFunc           (_compareFunc) {}
551 };
552
553 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
554 do { \
555         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
556         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
557 } while (deGetFalse())
558
559 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool testWithNan)
560 {
561         const string                                    nan                             = testWithNan ? "_nan" : "";
562         const string                                    groupName               = "opfunord" + nan;
563         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
564         de::Random                                              rnd                             (deStringHash(group->getName()));
565         const int                                               numElements             = 100;
566         vector<OpFUnordCase>                    cases;
567         string                                                  extensions              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
568         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
569         string                                                  exeModes                = testWithNan ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
570         const StringTemplate                    shaderTemplate  (
571                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
572                 "OpSource GLSL 430\n"
573                 "OpName %main           \"main\"\n"
574                 "OpName %id             \"gl_GlobalInvocationID\"\n"
575
576                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
577
578                 "OpDecorate %buf BufferBlock\n"
579                 "OpDecorate %buf2 BufferBlock\n"
580                 "OpDecorate %indata1 DescriptorSet 0\n"
581                 "OpDecorate %indata1 Binding 0\n"
582                 "OpDecorate %indata2 DescriptorSet 0\n"
583                 "OpDecorate %indata2 Binding 1\n"
584                 "OpDecorate %outdata DescriptorSet 0\n"
585                 "OpDecorate %outdata Binding 2\n"
586                 "OpDecorate %f32arr ArrayStride 4\n"
587                 "OpDecorate %i32arr ArrayStride 4\n"
588                 "OpMemberDecorate %buf 0 Offset 0\n"
589                 "OpMemberDecorate %buf2 0 Offset 0\n"
590
591                 + string(getComputeAsmCommonTypes()) +
592
593                 "%buf        = OpTypeStruct %f32arr\n"
594                 "%bufptr     = OpTypePointer Uniform %buf\n"
595                 "%indata1    = OpVariable %bufptr Uniform\n"
596                 "%indata2    = OpVariable %bufptr Uniform\n"
597
598                 "%buf2       = OpTypeStruct %i32arr\n"
599                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
600                 "%outdata    = OpVariable %buf2ptr Uniform\n"
601
602                 "%id        = OpVariable %uvec3ptr Input\n"
603                 "%zero      = OpConstant %i32 0\n"
604                 "%consti1   = OpConstant %i32 1\n"
605                 "%constf1   = OpConstant %f32 1.0\n"
606
607                 "%main      = OpFunction %void None %voidf\n"
608                 "%label     = OpLabel\n"
609                 "%idval     = OpLoad %uvec3 %id\n"
610                 "%x         = OpCompositeExtract %u32 %idval 0\n"
611
612                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
613                 "%inval1    = OpLoad %f32 %inloc1\n"
614                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
615                 "%inval2    = OpLoad %f32 %inloc2\n"
616                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
617
618                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
619                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
620                 "             OpStore %outloc %int_res\n"
621
622                 "             OpReturn\n"
623                 "             OpFunctionEnd\n");
624
625         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
626         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
627         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
628         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
629         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
630         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
631
632         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
633         {
634                 map<string, string>                     specializations;
635                 ComputeShaderSpec                       spec;
636                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
637                 vector<float>                           inputFloats1    (numElements, 0);
638                 vector<float>                           inputFloats2    (numElements, 0);
639                 vector<deInt32>                         expectedInts    (numElements, 0);
640
641                 specializations["OPCODE"]       = cases[caseNdx].opCode;
642                 spec.assembly                           = shaderTemplate.specialize(specializations);
643
644                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
645                 for (size_t ndx = 0; ndx < numElements; ++ndx)
646                 {
647                         switch (ndx % 6)
648                         {
649                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
650                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
651                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
652                                 case 3:         inputFloats2[ndx] = NaN; break;
653                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
654                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
655                         }
656                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
657                 }
658
659                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
660                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
661                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
662                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
663                 spec.verifyIO           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
664
665                 if (testWithNan)
666                 {
667                         spec.extensions.push_back("VK_KHR_shader_float_controls");
668                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
669                 }
670
671                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
672         }
673
674         return group.release();
675 }
676
677 struct OpAtomicCase
678 {
679         const char*             name;
680         const char*             assembly;
681         const char*             retValAssembly;
682         OpAtomicType    opAtomic;
683         deInt32                 numOutputElements;
684
685                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
686                                                 : name                          (_name)
687                                                 , assembly                      (_assembly)
688                                                 , retValAssembly        (_retValAssembly)
689                                                 , opAtomic                      (_opAtomic)
690                                                 , numOutputElements     (_numOutputElements) {}
691 };
692
693 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
694 {
695         std::string                                             groupName                       ("opatomic");
696         if (useStorageBuffer)
697                 groupName += "_storage_buffer";
698         if (verifyReturnValues)
699                 groupName += "_return_values";
700         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
701         vector<OpAtomicCase>                    cases;
702
703         const StringTemplate                    shaderTemplate  (
704
705                 string("OpCapability Shader\n") +
706                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
707                 "OpMemoryModel Logical GLSL450\n"
708                 "OpEntryPoint GLCompute %main \"main\" %id\n"
709                 "OpExecutionMode %main LocalSize 1 1 1\n" +
710
711                 "OpSource GLSL 430\n"
712                 "OpName %main           \"main\"\n"
713                 "OpName %id             \"gl_GlobalInvocationID\"\n"
714
715                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
716
717                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
718                 "OpDecorate %indata DescriptorSet 0\n"
719                 "OpDecorate %indata Binding 0\n"
720                 "OpDecorate %i32arr ArrayStride 4\n"
721                 "OpMemberDecorate %buf 0 Offset 0\n"
722
723                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
724                 "OpDecorate %sum DescriptorSet 0\n"
725                 "OpDecorate %sum Binding 1\n"
726                 "OpMemberDecorate %sumbuf 0 Coherent\n"
727                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
728
729                 "${RETVAL_BUF_DECORATE}"
730
731                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
732
733                 "%buf       = OpTypeStruct %i32arr\n"
734                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
735                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
736
737                 "%sumbuf    = OpTypeStruct %i32arr\n"
738                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
739                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
740
741                 "${RETVAL_BUF_DECL}"
742
743                 "%id        = OpVariable %uvec3ptr Input\n"
744                 "%minusone  = OpConstant %i32 -1\n"
745                 "%zero      = OpConstant %i32 0\n"
746                 "%one       = OpConstant %u32 1\n"
747                 "%two       = OpConstant %i32 2\n"
748
749                 "%main      = OpFunction %void None %voidf\n"
750                 "%label     = OpLabel\n"
751                 "%idval     = OpLoad %uvec3 %id\n"
752                 "%x         = OpCompositeExtract %u32 %idval 0\n"
753
754                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
755                 "%inval     = OpLoad %i32 %inloc\n"
756
757                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
758                 "${INSTRUCTION}"
759                 "${RETVAL_ASSEMBLY}"
760
761                 "             OpReturn\n"
762                 "             OpFunctionEnd\n");
763
764         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
765         do { \
766                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
767                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
768         } while (deGetFalse())
769         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
770         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
771
772         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
773                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
774         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
775                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
776         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
777                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
778         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
779                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
780         if (!verifyReturnValues)
781         {
782                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
783                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
784                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
785         }
786
787         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
788                                                                 "             OpStore %outloc %even\n"
789                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
790                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
791
792
793         #undef ADD_OPATOMIC_CASE
794         #undef ADD_OPATOMIC_CASE_1
795         #undef ADD_OPATOMIC_CASE_N
796
797         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
798         {
799                 map<string, string>                     specializations;
800                 ComputeShaderSpec                       spec;
801                 vector<deInt32>                         inputInts               (numElements, 0);
802                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
803
804                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
805                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
806                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
807                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
808
809                 if (verifyReturnValues)
810                 {
811                         const StringTemplate blockDecoration    (
812                                 "\n"
813                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
814                                 "OpDecorate %ret DescriptorSet 0\n"
815                                 "OpDecorate %ret Binding 2\n"
816                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
817
818                         const StringTemplate blockDeclaration   (
819                                 "\n"
820                                 "%retbuf    = OpTypeStruct %i32arr\n"
821                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
822                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
823
824                         specializations["RETVAL_ASSEMBLY"] =
825                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
826                                 + std::string(cases[caseNdx].retValAssembly);
827
828                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
829                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
830                 }
831                 else
832                 {
833                         specializations["RETVAL_ASSEMBLY"]              = "";
834                         specializations["RETVAL_BUF_DECORATE"]  = "";
835                         specializations["RETVAL_BUF_DECL"]              = "";
836                 }
837
838                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
839
840                 if (useStorageBuffer)
841                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
842
843                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
844                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
845                 if (verifyReturnValues)
846                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
847                 spec.numWorkGroups = IVec3(numElements, 1, 1);
848
849                 if (verifyReturnValues)
850                 {
851                         switch (cases[caseNdx].opAtomic)
852                         {
853                                 case OPATOMIC_IADD:
854                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
855                                         break;
856                                 case OPATOMIC_ISUB:
857                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
858                                         break;
859                                 case OPATOMIC_IINC:
860                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
861                                         break;
862                                 case OPATOMIC_IDEC:
863                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
864                                         break;
865                                 case OPATOMIC_COMPEX:
866                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
867                                         break;
868                                 default:
869                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
870                         }
871                 }
872                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
873         }
874
875         return group.release();
876 }
877
878 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
879 {
880         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
881         ComputeShaderSpec                               spec;
882         de::Random                                              rnd                             (deStringHash(group->getName()));
883         const int                                               numElements             = 100;
884         vector<float>                                   positiveFloats  (numElements, 0);
885         vector<float>                                   negativeFloats  (numElements, 0);
886
887         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
888
889         for (size_t ndx = 0; ndx < numElements; ++ndx)
890                 negativeFloats[ndx] = -positiveFloats[ndx];
891
892         spec.assembly =
893                 string(getComputeAsmShaderPreamble()) +
894
895                 "%fname1 = OpString \"negateInputs.comp\"\n"
896                 "%fname2 = OpString \"negateInputs\"\n"
897
898                 "OpSource GLSL 430\n"
899                 "OpName %main           \"main\"\n"
900                 "OpName %id             \"gl_GlobalInvocationID\"\n"
901
902                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
903
904                 + string(getComputeAsmInputOutputBufferTraits()) +
905
906                 "OpLine %fname1 0 0\n" // At the earliest possible position
907
908                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
909
910                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
911                 "OpLine %fname2 1 0\n" // Different filenames
912                 "OpLine %fname1 1000 100000\n"
913
914                 "%id        = OpVariable %uvec3ptr Input\n"
915                 "%zero      = OpConstant %i32 0\n"
916
917                 "OpLine %fname1 1 1\n" // Before a function
918
919                 "%main      = OpFunction %void None %voidf\n"
920                 "%label     = OpLabel\n"
921
922                 "OpLine %fname1 1 1\n" // In a function
923
924                 "%idval     = OpLoad %uvec3 %id\n"
925                 "%x         = OpCompositeExtract %u32 %idval 0\n"
926                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
927                 "%inval     = OpLoad %f32 %inloc\n"
928                 "%neg       = OpFNegate %f32 %inval\n"
929                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
930                 "             OpStore %outloc %neg\n"
931                 "             OpReturn\n"
932                 "             OpFunctionEnd\n";
933         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
934         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
935         spec.numWorkGroups = IVec3(numElements, 1, 1);
936
937         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
938
939         return group.release();
940 }
941
942 bool veryfiBinaryShader (const ProgramBinary& binary)
943 {
944         const size_t    paternCount                     = 3u;
945         bool paternsCheck[paternCount]          =
946         {
947                 false, false, false
948         };
949         const string patersns[paternCount]      =
950         {
951                 "VULKAN CTS",
952                 "Negative values",
953                 "Date: 2017/09/21"
954         };
955         size_t                  paternNdx               = 0u;
956
957         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
958         {
959                 if (false == paternsCheck[paternNdx] &&
960                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
961                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
962                 {
963                         paternsCheck[paternNdx]= true;
964                         paternNdx++;
965                         if (paternNdx == paternCount)
966                                 break;
967                 }
968         }
969
970         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
971         {
972                 if (!paternsCheck[ndx])
973                         return false;
974         }
975
976         return true;
977 }
978
979 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
980 {
981         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
982         ComputeShaderSpec                               spec;
983         de::Random                                              rnd                             (deStringHash(group->getName()));
984         const int                                               numElements             = 10;
985         vector<float>                                   positiveFloats  (numElements, 0);
986         vector<float>                                   negativeFloats  (numElements, 0);
987
988         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
989
990         for (size_t ndx = 0; ndx < numElements; ++ndx)
991                 negativeFloats[ndx] = -positiveFloats[ndx];
992
993         spec.assembly =
994                 string(getComputeAsmShaderPreamble()) +
995                 "%fname = OpString \"negateInputs.comp\"\n"
996
997                 "OpSource GLSL 430\n"
998                 "OpName %main           \"main\"\n"
999                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1000                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
1001                 "OpModuleProcessed \"Negative values\"\n"
1002                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
1003                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1004
1005                 + string(getComputeAsmInputOutputBufferTraits())
1006
1007                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1008
1009                 "OpLine %fname 0 1\n"
1010
1011                 "OpLine %fname 1000 1\n"
1012
1013                 "%id        = OpVariable %uvec3ptr Input\n"
1014                 "%zero      = OpConstant %i32 0\n"
1015                 "%main      = OpFunction %void None %voidf\n"
1016
1017                 "%label     = OpLabel\n"
1018                 "%idval     = OpLoad %uvec3 %id\n"
1019                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1020
1021                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1022                 "%inval     = OpLoad %f32 %inloc\n"
1023                 "%neg       = OpFNegate %f32 %inval\n"
1024                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1025                 "             OpStore %outloc %neg\n"
1026                 "             OpReturn\n"
1027                 "             OpFunctionEnd\n";
1028         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1029         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1030         spec.numWorkGroups = IVec3(numElements, 1, 1);
1031         spec.verifyBinary = veryfiBinaryShader;
1032         spec.spirvVersion = SPIRV_VERSION_1_3;
1033
1034         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
1035
1036         return group.release();
1037 }
1038
1039 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
1040 {
1041         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
1042         ComputeShaderSpec                               spec;
1043         de::Random                                              rnd                             (deStringHash(group->getName()));
1044         const int                                               numElements             = 100;
1045         vector<float>                                   positiveFloats  (numElements, 0);
1046         vector<float>                                   negativeFloats  (numElements, 0);
1047
1048         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
1049
1050         for (size_t ndx = 0; ndx < numElements; ++ndx)
1051                 negativeFloats[ndx] = -positiveFloats[ndx];
1052
1053         spec.assembly =
1054                 string(getComputeAsmShaderPreamble()) +
1055
1056                 "%fname = OpString \"negateInputs.comp\"\n"
1057
1058                 "OpSource GLSL 430\n"
1059                 "OpName %main           \"main\"\n"
1060                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1061
1062                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1063
1064                 + string(getComputeAsmInputOutputBufferTraits()) +
1065
1066                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
1067
1068                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1069
1070                 "OpLine %fname 0 1\n"
1071                 "OpNoLine\n" // Immediately following a preceding OpLine
1072
1073                 "OpLine %fname 1000 1\n"
1074
1075                 "%id        = OpVariable %uvec3ptr Input\n"
1076                 "%zero      = OpConstant %i32 0\n"
1077
1078                 "OpNoLine\n" // Contents after the previous OpLine
1079
1080                 "%main      = OpFunction %void None %voidf\n"
1081                 "%label     = OpLabel\n"
1082                 "%idval     = OpLoad %uvec3 %id\n"
1083                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1084
1085                 "OpNoLine\n" // Multiple OpNoLine
1086                 "OpNoLine\n"
1087                 "OpNoLine\n"
1088
1089                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1090                 "%inval     = OpLoad %f32 %inloc\n"
1091                 "%neg       = OpFNegate %f32 %inval\n"
1092                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1093                 "             OpStore %outloc %neg\n"
1094                 "             OpReturn\n"
1095                 "             OpFunctionEnd\n";
1096         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1097         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1098         spec.numWorkGroups = IVec3(numElements, 1, 1);
1099
1100         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
1101
1102         return group.release();
1103 }
1104
1105 // Compare instruction for the contraction compute case.
1106 // Returns true if the output is what is expected from the test case.
1107 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1108 {
1109         if (outputAllocs.size() != 1)
1110                 return false;
1111
1112         // Only size is needed because we are not comparing the exact values.
1113         size_t byteSize = expectedOutputs[0].getByteSize();
1114
1115         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1116
1117         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
1118                 if (outputAsFloat[i] != 0.f &&
1119                         outputAsFloat[i] != -ldexp(1, -24)) {
1120                         return false;
1121                 }
1122         }
1123
1124         return true;
1125 }
1126
1127 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1128 {
1129         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1130         vector<CaseParameter>                   cases;
1131         const int                                               numElements             = 100;
1132         vector<float>                                   inputFloats1    (numElements, 0);
1133         vector<float>                                   inputFloats2    (numElements, 0);
1134         vector<float>                                   outputFloats    (numElements, 0);
1135         const StringTemplate                    shaderTemplate  (
1136                 string(getComputeAsmShaderPreamble()) +
1137
1138                 "OpName %main           \"main\"\n"
1139                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1140
1141                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1142
1143                 "${DECORATION}\n"
1144
1145                 "OpDecorate %buf BufferBlock\n"
1146                 "OpDecorate %indata1 DescriptorSet 0\n"
1147                 "OpDecorate %indata1 Binding 0\n"
1148                 "OpDecorate %indata2 DescriptorSet 0\n"
1149                 "OpDecorate %indata2 Binding 1\n"
1150                 "OpDecorate %outdata DescriptorSet 0\n"
1151                 "OpDecorate %outdata Binding 2\n"
1152                 "OpDecorate %f32arr ArrayStride 4\n"
1153                 "OpMemberDecorate %buf 0 Offset 0\n"
1154
1155                 + string(getComputeAsmCommonTypes()) +
1156
1157                 "%buf        = OpTypeStruct %f32arr\n"
1158                 "%bufptr     = OpTypePointer Uniform %buf\n"
1159                 "%indata1    = OpVariable %bufptr Uniform\n"
1160                 "%indata2    = OpVariable %bufptr Uniform\n"
1161                 "%outdata    = OpVariable %bufptr Uniform\n"
1162
1163                 "%id         = OpVariable %uvec3ptr Input\n"
1164                 "%zero       = OpConstant %i32 0\n"
1165                 "%c_f_m1     = OpConstant %f32 -1.\n"
1166
1167                 "%main       = OpFunction %void None %voidf\n"
1168                 "%label      = OpLabel\n"
1169                 "%idval      = OpLoad %uvec3 %id\n"
1170                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1171                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1172                 "%inval1     = OpLoad %f32 %inloc1\n"
1173                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1174                 "%inval2     = OpLoad %f32 %inloc2\n"
1175                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1176                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1177                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1178                 "              OpStore %outloc %add\n"
1179                 "              OpReturn\n"
1180                 "              OpFunctionEnd\n");
1181
1182         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1183         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1184         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1185
1186         for (size_t ndx = 0; ndx < numElements; ++ndx)
1187         {
1188                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1189                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1190                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1191                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1192                 // So the final result will be 0.f or 0x1p-24.
1193                 // If the operation is combined into a precise fused multiply-add, then the result would be
1194                 // 2^-46 (0xa8800000).
1195                 outputFloats[ndx]       = 0.f;
1196         }
1197
1198         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1199         {
1200                 map<string, string>             specializations;
1201                 ComputeShaderSpec               spec;
1202
1203                 specializations["DECORATION"] = cases[caseNdx].param;
1204                 spec.assembly = shaderTemplate.specialize(specializations);
1205                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1206                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1207                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1208                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1209                 // Check against the two possible answers based on rounding mode.
1210                 spec.verifyIO = &compareNoContractCase;
1211
1212                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1213         }
1214         return group.release();
1215 }
1216
1217 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1218 {
1219         if (outputAllocs.size() != 1)
1220                 return false;
1221
1222         vector<deUint8> expectedBytes;
1223         expectedOutputs[0].getBytes(expectedBytes);
1224
1225         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1226         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1227
1228         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1229         {
1230                 const float f0 = expectedOutputAsFloat[idx];
1231                 const float f1 = outputAsFloat[idx];
1232                 // \todo relative error needs to be fairly high because FRem may be implemented as
1233                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1234                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1235                         return false;
1236         }
1237
1238         return true;
1239 }
1240
1241 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1242 {
1243         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1244         ComputeShaderSpec                               spec;
1245         de::Random                                              rnd                             (deStringHash(group->getName()));
1246         const int                                               numElements             = 200;
1247         vector<float>                                   inputFloats1    (numElements, 0);
1248         vector<float>                                   inputFloats2    (numElements, 0);
1249         vector<float>                                   outputFloats    (numElements, 0);
1250
1251         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1252         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1253
1254         for (size_t ndx = 0; ndx < numElements; ++ndx)
1255         {
1256                 // Guard against divisors near zero.
1257                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1258                         inputFloats2[ndx] = 8.f;
1259
1260                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1261                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1262         }
1263
1264         spec.assembly =
1265                 string(getComputeAsmShaderPreamble()) +
1266
1267                 "OpName %main           \"main\"\n"
1268                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1269
1270                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1271
1272                 "OpDecorate %buf BufferBlock\n"
1273                 "OpDecorate %indata1 DescriptorSet 0\n"
1274                 "OpDecorate %indata1 Binding 0\n"
1275                 "OpDecorate %indata2 DescriptorSet 0\n"
1276                 "OpDecorate %indata2 Binding 1\n"
1277                 "OpDecorate %outdata DescriptorSet 0\n"
1278                 "OpDecorate %outdata Binding 2\n"
1279                 "OpDecorate %f32arr ArrayStride 4\n"
1280                 "OpMemberDecorate %buf 0 Offset 0\n"
1281
1282                 + string(getComputeAsmCommonTypes()) +
1283
1284                 "%buf        = OpTypeStruct %f32arr\n"
1285                 "%bufptr     = OpTypePointer Uniform %buf\n"
1286                 "%indata1    = OpVariable %bufptr Uniform\n"
1287                 "%indata2    = OpVariable %bufptr Uniform\n"
1288                 "%outdata    = OpVariable %bufptr Uniform\n"
1289
1290                 "%id        = OpVariable %uvec3ptr Input\n"
1291                 "%zero      = OpConstant %i32 0\n"
1292
1293                 "%main      = OpFunction %void None %voidf\n"
1294                 "%label     = OpLabel\n"
1295                 "%idval     = OpLoad %uvec3 %id\n"
1296                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1297                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1298                 "%inval1    = OpLoad %f32 %inloc1\n"
1299                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1300                 "%inval2    = OpLoad %f32 %inloc2\n"
1301                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1302                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1303                 "             OpStore %outloc %rem\n"
1304                 "             OpReturn\n"
1305                 "             OpFunctionEnd\n";
1306
1307         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1308         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1309         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1310         spec.numWorkGroups = IVec3(numElements, 1, 1);
1311         spec.verifyIO = &compareFRem;
1312
1313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1314
1315         return group.release();
1316 }
1317
1318 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1319 {
1320         if (outputAllocs.size() != 1)
1321                 return false;
1322
1323         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1324         std::vector<deUint8>    data;
1325         expectedOutput->getBytes(data);
1326
1327         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1328         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1329
1330         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1331         {
1332                 const float f0 = expectedOutputAsFloat[idx];
1333                 const float f1 = outputAsFloat[idx];
1334
1335                 // For NMin, we accept NaN as output if both inputs were NaN.
1336                 // Otherwise the NaN is the wrong choise, as on architectures that
1337                 // do not handle NaN, those are huge values.
1338                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1339                         return false;
1340         }
1341
1342         return true;
1343 }
1344
1345 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1346 {
1347         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1348         ComputeShaderSpec                               spec;
1349         de::Random                                              rnd                             (deStringHash(group->getName()));
1350         const int                                               numElements             = 200;
1351         vector<float>                                   inputFloats1    (numElements, 0);
1352         vector<float>                                   inputFloats2    (numElements, 0);
1353         vector<float>                                   outputFloats    (numElements, 0);
1354
1355         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1356         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1357
1358         // Make the first case a full-NAN case.
1359         inputFloats1[0] = TCU_NAN;
1360         inputFloats2[0] = TCU_NAN;
1361
1362         for (size_t ndx = 0; ndx < numElements; ++ndx)
1363         {
1364                 // By default, pick the smallest
1365                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1366
1367                 // Make half of the cases NaN cases
1368                 if ((ndx & 1) == 0)
1369                 {
1370                         // Alternate between the NaN operand
1371                         if ((ndx & 2) == 0)
1372                         {
1373                                 outputFloats[ndx] = inputFloats2[ndx];
1374                                 inputFloats1[ndx] = TCU_NAN;
1375                         }
1376                         else
1377                         {
1378                                 outputFloats[ndx] = inputFloats1[ndx];
1379                                 inputFloats2[ndx] = TCU_NAN;
1380                         }
1381                 }
1382         }
1383
1384         spec.assembly =
1385                 "OpCapability Shader\n"
1386                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1387                 "OpMemoryModel Logical GLSL450\n"
1388                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1389                 "OpExecutionMode %main LocalSize 1 1 1\n"
1390
1391                 "OpName %main           \"main\"\n"
1392                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1393
1394                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1395
1396                 "OpDecorate %buf BufferBlock\n"
1397                 "OpDecorate %indata1 DescriptorSet 0\n"
1398                 "OpDecorate %indata1 Binding 0\n"
1399                 "OpDecorate %indata2 DescriptorSet 0\n"
1400                 "OpDecorate %indata2 Binding 1\n"
1401                 "OpDecorate %outdata DescriptorSet 0\n"
1402                 "OpDecorate %outdata Binding 2\n"
1403                 "OpDecorate %f32arr ArrayStride 4\n"
1404                 "OpMemberDecorate %buf 0 Offset 0\n"
1405
1406                 + string(getComputeAsmCommonTypes()) +
1407
1408                 "%buf        = OpTypeStruct %f32arr\n"
1409                 "%bufptr     = OpTypePointer Uniform %buf\n"
1410                 "%indata1    = OpVariable %bufptr Uniform\n"
1411                 "%indata2    = OpVariable %bufptr Uniform\n"
1412                 "%outdata    = OpVariable %bufptr Uniform\n"
1413
1414                 "%id        = OpVariable %uvec3ptr Input\n"
1415                 "%zero      = OpConstant %i32 0\n"
1416
1417                 "%main      = OpFunction %void None %voidf\n"
1418                 "%label     = OpLabel\n"
1419                 "%idval     = OpLoad %uvec3 %id\n"
1420                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1421                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1422                 "%inval1    = OpLoad %f32 %inloc1\n"
1423                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1424                 "%inval2    = OpLoad %f32 %inloc2\n"
1425                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1426                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1427                 "             OpStore %outloc %rem\n"
1428                 "             OpReturn\n"
1429                 "             OpFunctionEnd\n";
1430
1431         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1432         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1433         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1434         spec.numWorkGroups = IVec3(numElements, 1, 1);
1435         spec.verifyIO = &compareNMin;
1436
1437         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1438
1439         return group.release();
1440 }
1441
1442 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1443 {
1444         if (outputAllocs.size() != 1)
1445                 return false;
1446
1447         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1448         std::vector<deUint8>    data;
1449         expectedOutput->getBytes(data);
1450
1451         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1452         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1453
1454         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1455         {
1456                 const float f0 = expectedOutputAsFloat[idx];
1457                 const float f1 = outputAsFloat[idx];
1458
1459                 // For NMax, NaN is considered acceptable result, since in
1460                 // architectures that do not handle NaNs, those are huge values.
1461                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1462                         return false;
1463         }
1464
1465         return true;
1466 }
1467
1468 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1469 {
1470         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1471         ComputeShaderSpec                               spec;
1472         de::Random                                              rnd                             (deStringHash(group->getName()));
1473         const int                                               numElements             = 200;
1474         vector<float>                                   inputFloats1    (numElements, 0);
1475         vector<float>                                   inputFloats2    (numElements, 0);
1476         vector<float>                                   outputFloats    (numElements, 0);
1477
1478         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1479         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1480
1481         // Make the first case a full-NAN case.
1482         inputFloats1[0] = TCU_NAN;
1483         inputFloats2[0] = TCU_NAN;
1484
1485         for (size_t ndx = 0; ndx < numElements; ++ndx)
1486         {
1487                 // By default, pick the biggest
1488                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1489
1490                 // Make half of the cases NaN cases
1491                 if ((ndx & 1) == 0)
1492                 {
1493                         // Alternate between the NaN operand
1494                         if ((ndx & 2) == 0)
1495                         {
1496                                 outputFloats[ndx] = inputFloats2[ndx];
1497                                 inputFloats1[ndx] = TCU_NAN;
1498                         }
1499                         else
1500                         {
1501                                 outputFloats[ndx] = inputFloats1[ndx];
1502                                 inputFloats2[ndx] = TCU_NAN;
1503                         }
1504                 }
1505         }
1506
1507         spec.assembly =
1508                 "OpCapability Shader\n"
1509                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1510                 "OpMemoryModel Logical GLSL450\n"
1511                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1512                 "OpExecutionMode %main LocalSize 1 1 1\n"
1513
1514                 "OpName %main           \"main\"\n"
1515                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1516
1517                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1518
1519                 "OpDecorate %buf BufferBlock\n"
1520                 "OpDecorate %indata1 DescriptorSet 0\n"
1521                 "OpDecorate %indata1 Binding 0\n"
1522                 "OpDecorate %indata2 DescriptorSet 0\n"
1523                 "OpDecorate %indata2 Binding 1\n"
1524                 "OpDecorate %outdata DescriptorSet 0\n"
1525                 "OpDecorate %outdata Binding 2\n"
1526                 "OpDecorate %f32arr ArrayStride 4\n"
1527                 "OpMemberDecorate %buf 0 Offset 0\n"
1528
1529                 + string(getComputeAsmCommonTypes()) +
1530
1531                 "%buf        = OpTypeStruct %f32arr\n"
1532                 "%bufptr     = OpTypePointer Uniform %buf\n"
1533                 "%indata1    = OpVariable %bufptr Uniform\n"
1534                 "%indata2    = OpVariable %bufptr Uniform\n"
1535                 "%outdata    = OpVariable %bufptr Uniform\n"
1536
1537                 "%id        = OpVariable %uvec3ptr Input\n"
1538                 "%zero      = OpConstant %i32 0\n"
1539
1540                 "%main      = OpFunction %void None %voidf\n"
1541                 "%label     = OpLabel\n"
1542                 "%idval     = OpLoad %uvec3 %id\n"
1543                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1544                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1545                 "%inval1    = OpLoad %f32 %inloc1\n"
1546                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1547                 "%inval2    = OpLoad %f32 %inloc2\n"
1548                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1549                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1550                 "             OpStore %outloc %rem\n"
1551                 "             OpReturn\n"
1552                 "             OpFunctionEnd\n";
1553
1554         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1555         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1556         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1557         spec.numWorkGroups = IVec3(numElements, 1, 1);
1558         spec.verifyIO = &compareNMax;
1559
1560         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1561
1562         return group.release();
1563 }
1564
1565 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1566 {
1567         if (outputAllocs.size() != 1)
1568                 return false;
1569
1570         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1571         std::vector<deUint8>    data;
1572         expectedOutput->getBytes(data);
1573
1574         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1575         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1576
1577         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1578         {
1579                 const float e0 = expectedOutputAsFloat[idx * 2];
1580                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1581                 const float res = outputAsFloat[idx];
1582
1583                 // For NClamp, we have two possible outcomes based on
1584                 // whether NaNs are handled or not.
1585                 // If either min or max value is NaN, the result is undefined,
1586                 // so this test doesn't stress those. If the clamped value is
1587                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1588                 // handled, they are big values that result in max.
1589                 // If all three parameters are NaN, the result should be NaN.
1590                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1591                          (deFloatAbs(e0 - res) < 0.00001f) ||
1592                          (deFloatAbs(e1 - res) < 0.00001f)))
1593                         return false;
1594         }
1595
1596         return true;
1597 }
1598
1599 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1600 {
1601         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1602         ComputeShaderSpec                               spec;
1603         de::Random                                              rnd                             (deStringHash(group->getName()));
1604         const int                                               numElements             = 200;
1605         vector<float>                                   inputFloats1    (numElements, 0);
1606         vector<float>                                   inputFloats2    (numElements, 0);
1607         vector<float>                                   inputFloats3    (numElements, 0);
1608         vector<float>                                   outputFloats    (numElements * 2, 0);
1609
1610         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1611         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1612         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1613
1614         for (size_t ndx = 0; ndx < numElements; ++ndx)
1615         {
1616                 // Results are only defined if max value is bigger than min value.
1617                 if (inputFloats2[ndx] > inputFloats3[ndx])
1618                 {
1619                         float t = inputFloats2[ndx];
1620                         inputFloats2[ndx] = inputFloats3[ndx];
1621                         inputFloats3[ndx] = t;
1622                 }
1623
1624                 // By default, do the clamp, setting both possible answers
1625                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1626
1627                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1628                 float maxResB = maxResA;
1629
1630                 // Alternate between the NaN cases
1631                 if (ndx & 1)
1632                 {
1633                         inputFloats1[ndx] = TCU_NAN;
1634                         // If NaN is handled, the result should be same as the clamp minimum.
1635                         // If NaN is not handled, the result should clamp to the clamp maximum.
1636                         maxResA = inputFloats2[ndx];
1637                         maxResB = inputFloats3[ndx];
1638                 }
1639                 else
1640                 {
1641                         // Not a NaN case - only one legal result.
1642                         maxResA = defaultRes;
1643                         maxResB = defaultRes;
1644                 }
1645
1646                 outputFloats[ndx * 2] = maxResA;
1647                 outputFloats[ndx * 2 + 1] = maxResB;
1648         }
1649
1650         // Make the first case a full-NAN case.
1651         inputFloats1[0] = TCU_NAN;
1652         inputFloats2[0] = TCU_NAN;
1653         inputFloats3[0] = TCU_NAN;
1654         outputFloats[0] = TCU_NAN;
1655         outputFloats[1] = TCU_NAN;
1656
1657         spec.assembly =
1658                 "OpCapability Shader\n"
1659                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1660                 "OpMemoryModel Logical GLSL450\n"
1661                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1662                 "OpExecutionMode %main LocalSize 1 1 1\n"
1663
1664                 "OpName %main           \"main\"\n"
1665                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1666
1667                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1668
1669                 "OpDecorate %buf BufferBlock\n"
1670                 "OpDecorate %indata1 DescriptorSet 0\n"
1671                 "OpDecorate %indata1 Binding 0\n"
1672                 "OpDecorate %indata2 DescriptorSet 0\n"
1673                 "OpDecorate %indata2 Binding 1\n"
1674                 "OpDecorate %indata3 DescriptorSet 0\n"
1675                 "OpDecorate %indata3 Binding 2\n"
1676                 "OpDecorate %outdata DescriptorSet 0\n"
1677                 "OpDecorate %outdata Binding 3\n"
1678                 "OpDecorate %f32arr ArrayStride 4\n"
1679                 "OpMemberDecorate %buf 0 Offset 0\n"
1680
1681                 + string(getComputeAsmCommonTypes()) +
1682
1683                 "%buf        = OpTypeStruct %f32arr\n"
1684                 "%bufptr     = OpTypePointer Uniform %buf\n"
1685                 "%indata1    = OpVariable %bufptr Uniform\n"
1686                 "%indata2    = OpVariable %bufptr Uniform\n"
1687                 "%indata3    = OpVariable %bufptr Uniform\n"
1688                 "%outdata    = OpVariable %bufptr Uniform\n"
1689
1690                 "%id        = OpVariable %uvec3ptr Input\n"
1691                 "%zero      = OpConstant %i32 0\n"
1692
1693                 "%main      = OpFunction %void None %voidf\n"
1694                 "%label     = OpLabel\n"
1695                 "%idval     = OpLoad %uvec3 %id\n"
1696                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1697                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1698                 "%inval1    = OpLoad %f32 %inloc1\n"
1699                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1700                 "%inval2    = OpLoad %f32 %inloc2\n"
1701                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1702                 "%inval3    = OpLoad %f32 %inloc3\n"
1703                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1704                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1705                 "             OpStore %outloc %rem\n"
1706                 "             OpReturn\n"
1707                 "             OpFunctionEnd\n";
1708
1709         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1710         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1711         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1712         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1713         spec.numWorkGroups = IVec3(numElements, 1, 1);
1714         spec.verifyIO = &compareNClamp;
1715
1716         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1717
1718         return group.release();
1719 }
1720
1721 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1722 {
1723         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1724         de::Random                                              rnd                             (deStringHash(group->getName()));
1725         const int                                               numElements             = 200;
1726
1727         const struct CaseParams
1728         {
1729                 const char*             name;
1730                 const char*             failMessage;            // customized status message
1731                 qpTestResult    failResult;                     // override status on failure
1732                 int                             op1Min, op1Max;         // operand ranges
1733                 int                             op2Min, op2Max;
1734         } cases[] =
1735         {
1736                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1737                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1738         };
1739         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1740
1741         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1742         {
1743                 const CaseParams&       params          = cases[caseNdx];
1744                 ComputeShaderSpec       spec;
1745                 vector<deInt32>         inputInts1      (numElements, 0);
1746                 vector<deInt32>         inputInts2      (numElements, 0);
1747                 vector<deInt32>         outputInts      (numElements, 0);
1748
1749                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1750                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1751
1752                 for (int ndx = 0; ndx < numElements; ++ndx)
1753                 {
1754                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1755                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1756                 }
1757
1758                 spec.assembly =
1759                         string(getComputeAsmShaderPreamble()) +
1760
1761                         "OpName %main           \"main\"\n"
1762                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1763
1764                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1765
1766                         "OpDecorate %buf BufferBlock\n"
1767                         "OpDecorate %indata1 DescriptorSet 0\n"
1768                         "OpDecorate %indata1 Binding 0\n"
1769                         "OpDecorate %indata2 DescriptorSet 0\n"
1770                         "OpDecorate %indata2 Binding 1\n"
1771                         "OpDecorate %outdata DescriptorSet 0\n"
1772                         "OpDecorate %outdata Binding 2\n"
1773                         "OpDecorate %i32arr ArrayStride 4\n"
1774                         "OpMemberDecorate %buf 0 Offset 0\n"
1775
1776                         + string(getComputeAsmCommonTypes()) +
1777
1778                         "%buf        = OpTypeStruct %i32arr\n"
1779                         "%bufptr     = OpTypePointer Uniform %buf\n"
1780                         "%indata1    = OpVariable %bufptr Uniform\n"
1781                         "%indata2    = OpVariable %bufptr Uniform\n"
1782                         "%outdata    = OpVariable %bufptr Uniform\n"
1783
1784                         "%id        = OpVariable %uvec3ptr Input\n"
1785                         "%zero      = OpConstant %i32 0\n"
1786
1787                         "%main      = OpFunction %void None %voidf\n"
1788                         "%label     = OpLabel\n"
1789                         "%idval     = OpLoad %uvec3 %id\n"
1790                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1791                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1792                         "%inval1    = OpLoad %i32 %inloc1\n"
1793                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1794                         "%inval2    = OpLoad %i32 %inloc2\n"
1795                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1796                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1797                         "             OpStore %outloc %rem\n"
1798                         "             OpReturn\n"
1799                         "             OpFunctionEnd\n";
1800
1801                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1802                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1803                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1804                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1805                 spec.failResult                 = params.failResult;
1806                 spec.failMessage                = params.failMessage;
1807
1808                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1809         }
1810
1811         return group.release();
1812 }
1813
1814 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1815 {
1816         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1817         de::Random                                              rnd                             (deStringHash(group->getName()));
1818         const int                                               numElements             = 200;
1819
1820         const struct CaseParams
1821         {
1822                 const char*             name;
1823                 const char*             failMessage;            // customized status message
1824                 qpTestResult    failResult;                     // override status on failure
1825                 bool                    positive;
1826         } cases[] =
1827         {
1828                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1829                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1830         };
1831         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1832
1833         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1834         {
1835                 const CaseParams&       params          = cases[caseNdx];
1836                 ComputeShaderSpec       spec;
1837                 vector<deInt64>         inputInts1      (numElements, 0);
1838                 vector<deInt64>         inputInts2      (numElements, 0);
1839                 vector<deInt64>         outputInts      (numElements, 0);
1840
1841                 if (params.positive)
1842                 {
1843                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1844                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1845                 }
1846                 else
1847                 {
1848                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1849                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1850                 }
1851
1852                 for (int ndx = 0; ndx < numElements; ++ndx)
1853                 {
1854                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1855                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1856                 }
1857
1858                 spec.assembly =
1859                         "OpCapability Int64\n"
1860
1861                         + string(getComputeAsmShaderPreamble()) +
1862
1863                         "OpName %main           \"main\"\n"
1864                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1865
1866                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1867
1868                         "OpDecorate %buf BufferBlock\n"
1869                         "OpDecorate %indata1 DescriptorSet 0\n"
1870                         "OpDecorate %indata1 Binding 0\n"
1871                         "OpDecorate %indata2 DescriptorSet 0\n"
1872                         "OpDecorate %indata2 Binding 1\n"
1873                         "OpDecorate %outdata DescriptorSet 0\n"
1874                         "OpDecorate %outdata Binding 2\n"
1875                         "OpDecorate %i64arr ArrayStride 8\n"
1876                         "OpMemberDecorate %buf 0 Offset 0\n"
1877
1878                         + string(getComputeAsmCommonTypes())
1879                         + string(getComputeAsmCommonInt64Types()) +
1880
1881                         "%buf        = OpTypeStruct %i64arr\n"
1882                         "%bufptr     = OpTypePointer Uniform %buf\n"
1883                         "%indata1    = OpVariable %bufptr Uniform\n"
1884                         "%indata2    = OpVariable %bufptr Uniform\n"
1885                         "%outdata    = OpVariable %bufptr Uniform\n"
1886
1887                         "%id        = OpVariable %uvec3ptr Input\n"
1888                         "%zero      = OpConstant %i64 0\n"
1889
1890                         "%main      = OpFunction %void None %voidf\n"
1891                         "%label     = OpLabel\n"
1892                         "%idval     = OpLoad %uvec3 %id\n"
1893                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1894                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1895                         "%inval1    = OpLoad %i64 %inloc1\n"
1896                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1897                         "%inval2    = OpLoad %i64 %inloc2\n"
1898                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1899                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1900                         "             OpStore %outloc %rem\n"
1901                         "             OpReturn\n"
1902                         "             OpFunctionEnd\n";
1903
1904                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1905                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1906                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1907                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1908                 spec.failResult                 = params.failResult;
1909                 spec.failMessage                = params.failMessage;
1910
1911                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1912
1913                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1914         }
1915
1916         return group.release();
1917 }
1918
1919 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1920 {
1921         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1922         de::Random                                              rnd                             (deStringHash(group->getName()));
1923         const int                                               numElements             = 200;
1924
1925         const struct CaseParams
1926         {
1927                 const char*             name;
1928                 const char*             failMessage;            // customized status message
1929                 qpTestResult    failResult;                     // override status on failure
1930                 int                             op1Min, op1Max;         // operand ranges
1931                 int                             op2Min, op2Max;
1932         } cases[] =
1933         {
1934                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1935                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1936         };
1937         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1938
1939         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1940         {
1941                 const CaseParams&       params          = cases[caseNdx];
1942
1943                 ComputeShaderSpec       spec;
1944                 vector<deInt32>         inputInts1      (numElements, 0);
1945                 vector<deInt32>         inputInts2      (numElements, 0);
1946                 vector<deInt32>         outputInts      (numElements, 0);
1947
1948                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1949                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1950
1951                 for (int ndx = 0; ndx < numElements; ++ndx)
1952                 {
1953                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1954                         if (rem == 0)
1955                         {
1956                                 outputInts[ndx] = 0;
1957                         }
1958                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1959                         {
1960                                 // They have the same sign
1961                                 outputInts[ndx] = rem;
1962                         }
1963                         else
1964                         {
1965                                 // They have opposite sign.  The remainder operation takes the
1966                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1967                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1968                                 // the result has the correct sign and that it is still
1969                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1970                                 //
1971                                 // See also http://mathforum.org/library/drmath/view/52343.html
1972                                 outputInts[ndx] = rem + inputInts2[ndx];
1973                         }
1974                 }
1975
1976                 spec.assembly =
1977                         string(getComputeAsmShaderPreamble()) +
1978
1979                         "OpName %main           \"main\"\n"
1980                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1981
1982                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1983
1984                         "OpDecorate %buf BufferBlock\n"
1985                         "OpDecorate %indata1 DescriptorSet 0\n"
1986                         "OpDecorate %indata1 Binding 0\n"
1987                         "OpDecorate %indata2 DescriptorSet 0\n"
1988                         "OpDecorate %indata2 Binding 1\n"
1989                         "OpDecorate %outdata DescriptorSet 0\n"
1990                         "OpDecorate %outdata Binding 2\n"
1991                         "OpDecorate %i32arr ArrayStride 4\n"
1992                         "OpMemberDecorate %buf 0 Offset 0\n"
1993
1994                         + string(getComputeAsmCommonTypes()) +
1995
1996                         "%buf        = OpTypeStruct %i32arr\n"
1997                         "%bufptr     = OpTypePointer Uniform %buf\n"
1998                         "%indata1    = OpVariable %bufptr Uniform\n"
1999                         "%indata2    = OpVariable %bufptr Uniform\n"
2000                         "%outdata    = OpVariable %bufptr Uniform\n"
2001
2002                         "%id        = OpVariable %uvec3ptr Input\n"
2003                         "%zero      = OpConstant %i32 0\n"
2004
2005                         "%main      = OpFunction %void None %voidf\n"
2006                         "%label     = OpLabel\n"
2007                         "%idval     = OpLoad %uvec3 %id\n"
2008                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2009                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
2010                         "%inval1    = OpLoad %i32 %inloc1\n"
2011                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
2012                         "%inval2    = OpLoad %i32 %inloc2\n"
2013                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
2014                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2015                         "             OpStore %outloc %rem\n"
2016                         "             OpReturn\n"
2017                         "             OpFunctionEnd\n";
2018
2019                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
2020                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
2021                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
2022                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2023                 spec.failResult                 = params.failResult;
2024                 spec.failMessage                = params.failMessage;
2025
2026                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2027         }
2028
2029         return group.release();
2030 }
2031
2032 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
2033 {
2034         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
2035         de::Random                                              rnd                             (deStringHash(group->getName()));
2036         const int                                               numElements             = 200;
2037
2038         const struct CaseParams
2039         {
2040                 const char*             name;
2041                 const char*             failMessage;            // customized status message
2042                 qpTestResult    failResult;                     // override status on failure
2043                 bool                    positive;
2044         } cases[] =
2045         {
2046                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
2047                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
2048         };
2049         // If either operand is negative the result is undefined. Some implementations may still return correct values.
2050
2051         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
2052         {
2053                 const CaseParams&       params          = cases[caseNdx];
2054
2055                 ComputeShaderSpec       spec;
2056                 vector<deInt64>         inputInts1      (numElements, 0);
2057                 vector<deInt64>         inputInts2      (numElements, 0);
2058                 vector<deInt64>         outputInts      (numElements, 0);
2059
2060
2061                 if (params.positive)
2062                 {
2063                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
2064                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
2065                 }
2066                 else
2067                 {
2068                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
2069                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
2070                 }
2071
2072                 for (int ndx = 0; ndx < numElements; ++ndx)
2073                 {
2074                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
2075                         if (rem == 0)
2076                         {
2077                                 outputInts[ndx] = 0;
2078                         }
2079                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
2080                         {
2081                                 // They have the same sign
2082                                 outputInts[ndx] = rem;
2083                         }
2084                         else
2085                         {
2086                                 // They have opposite sign.  The remainder operation takes the
2087                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
2088                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
2089                                 // the result has the correct sign and that it is still
2090                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
2091                                 //
2092                                 // See also http://mathforum.org/library/drmath/view/52343.html
2093                                 outputInts[ndx] = rem + inputInts2[ndx];
2094                         }
2095                 }
2096
2097                 spec.assembly =
2098                         "OpCapability Int64\n"
2099
2100                         + string(getComputeAsmShaderPreamble()) +
2101
2102                         "OpName %main           \"main\"\n"
2103                         "OpName %id             \"gl_GlobalInvocationID\"\n"
2104
2105                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
2106
2107                         "OpDecorate %buf BufferBlock\n"
2108                         "OpDecorate %indata1 DescriptorSet 0\n"
2109                         "OpDecorate %indata1 Binding 0\n"
2110                         "OpDecorate %indata2 DescriptorSet 0\n"
2111                         "OpDecorate %indata2 Binding 1\n"
2112                         "OpDecorate %outdata DescriptorSet 0\n"
2113                         "OpDecorate %outdata Binding 2\n"
2114                         "OpDecorate %i64arr ArrayStride 8\n"
2115                         "OpMemberDecorate %buf 0 Offset 0\n"
2116
2117                         + string(getComputeAsmCommonTypes())
2118                         + string(getComputeAsmCommonInt64Types()) +
2119
2120                         "%buf        = OpTypeStruct %i64arr\n"
2121                         "%bufptr     = OpTypePointer Uniform %buf\n"
2122                         "%indata1    = OpVariable %bufptr Uniform\n"
2123                         "%indata2    = OpVariable %bufptr Uniform\n"
2124                         "%outdata    = OpVariable %bufptr Uniform\n"
2125
2126                         "%id        = OpVariable %uvec3ptr Input\n"
2127                         "%zero      = OpConstant %i64 0\n"
2128
2129                         "%main      = OpFunction %void None %voidf\n"
2130                         "%label     = OpLabel\n"
2131                         "%idval     = OpLoad %uvec3 %id\n"
2132                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2133                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2134                         "%inval1    = OpLoad %i64 %inloc1\n"
2135                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2136                         "%inval2    = OpLoad %i64 %inloc2\n"
2137                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2138                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2139                         "             OpStore %outloc %rem\n"
2140                         "             OpReturn\n"
2141                         "             OpFunctionEnd\n";
2142
2143                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2144                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2145                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2146                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2147                 spec.failResult                 = params.failResult;
2148                 spec.failMessage                = params.failMessage;
2149
2150                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2151
2152                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2153         }
2154
2155         return group.release();
2156 }
2157
2158 // Copy contents in the input buffer to the output buffer.
2159 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2160 {
2161         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2162         de::Random                                              rnd                             (deStringHash(group->getName()));
2163         const int                                               numElements             = 100;
2164
2165         // 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.
2166         ComputeShaderSpec                               spec1;
2167         vector<Vec4>                                    inputFloats1    (numElements);
2168         vector<Vec4>                                    outputFloats1   (numElements);
2169
2170         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2171
2172         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2173         floorAll(inputFloats1);
2174
2175         for (size_t ndx = 0; ndx < numElements; ++ndx)
2176                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2177
2178         spec1.assembly =
2179                 string(getComputeAsmShaderPreamble()) +
2180
2181                 "OpName %main           \"main\"\n"
2182                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2183
2184                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2185                 "OpDecorate %vec4arr ArrayStride 16\n"
2186
2187                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2188
2189                 "%vec4       = OpTypeVector %f32 4\n"
2190                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2191                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2192                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2193                 "%buf        = OpTypeStruct %vec4arr\n"
2194                 "%bufptr     = OpTypePointer Uniform %buf\n"
2195                 "%indata     = OpVariable %bufptr Uniform\n"
2196                 "%outdata    = OpVariable %bufptr Uniform\n"
2197
2198                 "%id         = OpVariable %uvec3ptr Input\n"
2199                 "%zero       = OpConstant %i32 0\n"
2200                 "%c_f_0      = OpConstant %f32 0.\n"
2201                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2202                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2203                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2204                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2205
2206                 "%main       = OpFunction %void None %voidf\n"
2207                 "%label      = OpLabel\n"
2208                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2209                 "%idval      = OpLoad %uvec3 %id\n"
2210                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2211                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2212                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2213                 "              OpCopyMemory %v_vec4 %inloc\n"
2214                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2215                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2216                 "              OpStore %outloc %add\n"
2217                 "              OpReturn\n"
2218                 "              OpFunctionEnd\n";
2219
2220         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2221         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2222         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2223
2224         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2225
2226         // The following case copies a float[100] variable from the input buffer to the output buffer.
2227         ComputeShaderSpec                               spec2;
2228         vector<float>                                   inputFloats2    (numElements);
2229         vector<float>                                   outputFloats2   (numElements);
2230
2231         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2232
2233         for (size_t ndx = 0; ndx < numElements; ++ndx)
2234                 outputFloats2[ndx] = inputFloats2[ndx];
2235
2236         spec2.assembly =
2237                 string(getComputeAsmShaderPreamble()) +
2238
2239                 "OpName %main           \"main\"\n"
2240                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2241
2242                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2243                 "OpDecorate %f32arr100 ArrayStride 4\n"
2244
2245                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2246
2247                 "%hundred        = OpConstant %u32 100\n"
2248                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2249                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2250                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2251                 "%buf            = OpTypeStruct %f32arr100\n"
2252                 "%bufptr         = OpTypePointer Uniform %buf\n"
2253                 "%indata         = OpVariable %bufptr Uniform\n"
2254                 "%outdata        = OpVariable %bufptr Uniform\n"
2255
2256                 "%id             = OpVariable %uvec3ptr Input\n"
2257                 "%zero           = OpConstant %i32 0\n"
2258
2259                 "%main           = OpFunction %void None %voidf\n"
2260                 "%label          = OpLabel\n"
2261                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2262                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2263                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2264                 "                  OpCopyMemory %var %inarr\n"
2265                 "                  OpCopyMemory %outarr %var\n"
2266                 "                  OpReturn\n"
2267                 "                  OpFunctionEnd\n";
2268
2269         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2270         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2271         spec2.numWorkGroups = IVec3(1, 1, 1);
2272
2273         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2274
2275         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2276         ComputeShaderSpec                               spec3;
2277         vector<float>                                   inputFloats3    (16);
2278         vector<float>                                   outputFloats3   (16);
2279
2280         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2281
2282         for (size_t ndx = 0; ndx < 16; ++ndx)
2283                 outputFloats3[ndx] = inputFloats3[ndx];
2284
2285         spec3.assembly =
2286                 string(getComputeAsmShaderPreamble()) +
2287
2288                 "OpName %main           \"main\"\n"
2289                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2290
2291                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2292                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2293                 "OpMemberDecorate %buf 1 Offset 16\n"
2294                 "OpMemberDecorate %buf 2 Offset 32\n"
2295                 "OpMemberDecorate %buf 3 Offset 48\n"
2296
2297                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2298
2299                 "%vec4      = OpTypeVector %f32 4\n"
2300                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2301                 "%bufptr    = OpTypePointer Uniform %buf\n"
2302                 "%indata    = OpVariable %bufptr Uniform\n"
2303                 "%outdata   = OpVariable %bufptr Uniform\n"
2304                 "%vec4stptr = OpTypePointer Function %buf\n"
2305
2306                 "%id        = OpVariable %uvec3ptr Input\n"
2307                 "%zero      = OpConstant %i32 0\n"
2308
2309                 "%main      = OpFunction %void None %voidf\n"
2310                 "%label     = OpLabel\n"
2311                 "%var       = OpVariable %vec4stptr Function\n"
2312                 "             OpCopyMemory %var %indata\n"
2313                 "             OpCopyMemory %outdata %var\n"
2314                 "             OpReturn\n"
2315                 "             OpFunctionEnd\n";
2316
2317         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2318         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2319         spec3.numWorkGroups = IVec3(1, 1, 1);
2320
2321         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2322
2323         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2324         ComputeShaderSpec                               spec4;
2325         vector<float>                                   inputFloats4    (numElements);
2326         vector<float>                                   outputFloats4   (numElements);
2327
2328         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2329
2330         for (size_t ndx = 0; ndx < numElements; ++ndx)
2331                 outputFloats4[ndx] = -inputFloats4[ndx];
2332
2333         spec4.assembly =
2334                 string(getComputeAsmShaderPreamble()) +
2335
2336                 "OpName %main           \"main\"\n"
2337                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2338
2339                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2340
2341                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2342
2343                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2344                 "%id        = OpVariable %uvec3ptr Input\n"
2345                 "%zero      = OpConstant %i32 0\n"
2346
2347                 "%main      = OpFunction %void None %voidf\n"
2348                 "%label     = OpLabel\n"
2349                 "%var       = OpVariable %f32ptr_f Function\n"
2350                 "%idval     = OpLoad %uvec3 %id\n"
2351                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2352                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2353                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2354                 "             OpCopyMemory %var %inloc\n"
2355                 "%val       = OpLoad %f32 %var\n"
2356                 "%neg       = OpFNegate %f32 %val\n"
2357                 "             OpStore %outloc %neg\n"
2358                 "             OpReturn\n"
2359                 "             OpFunctionEnd\n";
2360
2361         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2362         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2363         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2364
2365         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2366
2367         return group.release();
2368 }
2369
2370 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2371 {
2372         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2373         ComputeShaderSpec                               spec;
2374         de::Random                                              rnd                             (deStringHash(group->getName()));
2375         const int                                               numElements             = 100;
2376         vector<float>                                   inputFloats             (numElements, 0);
2377         vector<float>                                   outputFloats    (numElements, 0);
2378
2379         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2380
2381         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2382         floorAll(inputFloats);
2383
2384         for (size_t ndx = 0; ndx < numElements; ++ndx)
2385                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2386
2387         spec.assembly =
2388                 string(getComputeAsmShaderPreamble()) +
2389
2390                 "OpName %main           \"main\"\n"
2391                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2392
2393                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2394
2395                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2396
2397                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2398                 "%three    = OpConstant %u32 3\n"
2399                 "%farr     = OpTypeArray %f32 %three\n"
2400                 "%fst      = OpTypeStruct %f32 %f32\n"
2401
2402                 + string(getComputeAsmInputOutputBuffer()) +
2403
2404                 "%id            = OpVariable %uvec3ptr Input\n"
2405                 "%zero          = OpConstant %i32 0\n"
2406                 "%c_f           = OpConstant %f32 1.5\n"
2407                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2408                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2409                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2410                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2411
2412                 "%main          = OpFunction %void None %voidf\n"
2413                 "%label         = OpLabel\n"
2414                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2415                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2416                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2417                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2418                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2419                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2420                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2421                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2422                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2423                 // Add up. 1.5 * 5 = 7.5.
2424                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2425                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2426                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2427                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2428
2429                 "%idval         = OpLoad %uvec3 %id\n"
2430                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2431                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2432                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2433                 "%inval         = OpLoad %f32 %inloc\n"
2434                 "%add           = OpFAdd %f32 %add4 %inval\n"
2435                 "                 OpStore %outloc %add\n"
2436                 "                 OpReturn\n"
2437                 "                 OpFunctionEnd\n";
2438         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2439         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2440         spec.numWorkGroups = IVec3(numElements, 1, 1);
2441
2442         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2443
2444         return group.release();
2445 }
2446 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2447 //
2448 // #version 430
2449 //
2450 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2451 //   float elements[];
2452 // } input_data;
2453 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2454 //   float elements[];
2455 // } output_data;
2456 //
2457 // void not_called_func() {
2458 //   // place OpUnreachable here
2459 // }
2460 //
2461 // uint modulo4(uint val) {
2462 //   switch (val % uint(4)) {
2463 //     case 0:  return 3;
2464 //     case 1:  return 2;
2465 //     case 2:  return 1;
2466 //     case 3:  return 0;
2467 //     default: return 100; // place OpUnreachable here
2468 //   }
2469 // }
2470 //
2471 // uint const5() {
2472 //   return 5;
2473 //   // place OpUnreachable here
2474 // }
2475 //
2476 // void main() {
2477 //   uint x = gl_GlobalInvocationID.x;
2478 //   if (const5() > modulo4(1000)) {
2479 //     output_data.elements[x] = -input_data.elements[x];
2480 //   } else {
2481 //     // place OpUnreachable here
2482 //     output_data.elements[x] = input_data.elements[x];
2483 //   }
2484 // }
2485
2486 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2487 {
2488         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2489         ComputeShaderSpec                               spec;
2490         de::Random                                              rnd                             (deStringHash(group->getName()));
2491         const int                                               numElements             = 100;
2492         vector<float>                                   positiveFloats  (numElements, 0);
2493         vector<float>                                   negativeFloats  (numElements, 0);
2494
2495         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2496
2497         for (size_t ndx = 0; ndx < numElements; ++ndx)
2498                 negativeFloats[ndx] = -positiveFloats[ndx];
2499
2500         spec.assembly =
2501                 string(getComputeAsmShaderPreamble()) +
2502
2503                 "OpSource GLSL 430\n"
2504                 "OpName %main            \"main\"\n"
2505                 "OpName %func_not_called_func \"not_called_func(\"\n"
2506                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2507                 "OpName %func_const5          \"const5(\"\n"
2508                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2509
2510                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2511
2512                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2513
2514                 "%u32ptr    = OpTypePointer Function %u32\n"
2515                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2516                 "%unitf     = OpTypeFunction %u32\n"
2517
2518                 "%id        = OpVariable %uvec3ptr Input\n"
2519                 "%zero      = OpConstant %u32 0\n"
2520                 "%one       = OpConstant %u32 1\n"
2521                 "%two       = OpConstant %u32 2\n"
2522                 "%three     = OpConstant %u32 3\n"
2523                 "%four      = OpConstant %u32 4\n"
2524                 "%five      = OpConstant %u32 5\n"
2525                 "%hundred   = OpConstant %u32 100\n"
2526                 "%thousand  = OpConstant %u32 1000\n"
2527
2528                 + string(getComputeAsmInputOutputBuffer()) +
2529
2530                 // Main()
2531                 "%main   = OpFunction %void None %voidf\n"
2532                 "%main_entry  = OpLabel\n"
2533                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2534                 "%idval       = OpLoad %uvec3 %id\n"
2535                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2536                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2537                 "%inval       = OpLoad %f32 %inloc\n"
2538                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2539                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2540                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2541                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2542                 "               OpSelectionMerge %if_end None\n"
2543                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2544                 "%if_true     = OpLabel\n"
2545                 "%negate      = OpFNegate %f32 %inval\n"
2546                 "               OpStore %outloc %negate\n"
2547                 "               OpBranch %if_end\n"
2548                 "%if_false    = OpLabel\n"
2549                 "               OpUnreachable\n" // Unreachable else branch for if statement
2550                 "%if_end      = OpLabel\n"
2551                 "               OpReturn\n"
2552                 "               OpFunctionEnd\n"
2553
2554                 // not_called_function()
2555                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2556                 "%not_called_func_entry = OpLabel\n"
2557                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2558                 "                         OpFunctionEnd\n"
2559
2560                 // modulo4()
2561                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2562                 "%valptr        = OpFunctionParameter %u32ptr\n"
2563                 "%modulo4_entry = OpLabel\n"
2564                 "%val           = OpLoad %u32 %valptr\n"
2565                 "%modulo        = OpUMod %u32 %val %four\n"
2566                 "                 OpSelectionMerge %switch_merge None\n"
2567                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2568                 "%case0         = OpLabel\n"
2569                 "                 OpReturnValue %three\n"
2570                 "%case1         = OpLabel\n"
2571                 "                 OpReturnValue %two\n"
2572                 "%case2         = OpLabel\n"
2573                 "                 OpReturnValue %one\n"
2574                 "%case3         = OpLabel\n"
2575                 "                 OpReturnValue %zero\n"
2576                 "%default       = OpLabel\n"
2577                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2578                 "%switch_merge  = OpLabel\n"
2579                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2580                 "                 OpFunctionEnd\n"
2581
2582                 // const5()
2583                 "%func_const5  = OpFunction %u32 None %unitf\n"
2584                 "%const5_entry = OpLabel\n"
2585                 "                OpReturnValue %five\n"
2586                 "%unreachable  = OpLabel\n"
2587                 "                OpUnreachable\n" // Unreachable block in function
2588                 "                OpFunctionEnd\n";
2589         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2590         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2591         spec.numWorkGroups = IVec3(numElements, 1, 1);
2592
2593         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2594
2595         return group.release();
2596 }
2597
2598 // Assembly code used for testing decoration group is based on GLSL source code:
2599 //
2600 // #version 430
2601 //
2602 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2603 //   float elements[];
2604 // } input_data0;
2605 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2606 //   float elements[];
2607 // } input_data1;
2608 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2609 //   float elements[];
2610 // } input_data2;
2611 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2612 //   float elements[];
2613 // } input_data3;
2614 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2615 //   float elements[];
2616 // } input_data4;
2617 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2618 //   float elements[];
2619 // } output_data;
2620 //
2621 // void main() {
2622 //   uint x = gl_GlobalInvocationID.x;
2623 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2624 // }
2625 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2626 {
2627         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2628         ComputeShaderSpec                               spec;
2629         de::Random                                              rnd                             (deStringHash(group->getName()));
2630         const int                                               numElements             = 100;
2631         vector<float>                                   inputFloats0    (numElements, 0);
2632         vector<float>                                   inputFloats1    (numElements, 0);
2633         vector<float>                                   inputFloats2    (numElements, 0);
2634         vector<float>                                   inputFloats3    (numElements, 0);
2635         vector<float>                                   inputFloats4    (numElements, 0);
2636         vector<float>                                   outputFloats    (numElements, 0);
2637
2638         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2639         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2640         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2641         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2642         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2643
2644         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2645         floorAll(inputFloats0);
2646         floorAll(inputFloats1);
2647         floorAll(inputFloats2);
2648         floorAll(inputFloats3);
2649         floorAll(inputFloats4);
2650
2651         for (size_t ndx = 0; ndx < numElements; ++ndx)
2652                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2653
2654         spec.assembly =
2655                 string(getComputeAsmShaderPreamble()) +
2656
2657                 "OpSource GLSL 430\n"
2658                 "OpName %main \"main\"\n"
2659                 "OpName %id \"gl_GlobalInvocationID\"\n"
2660
2661                 // Not using group decoration on variable.
2662                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2663                 // Not using group decoration on type.
2664                 "OpDecorate %f32arr ArrayStride 4\n"
2665
2666                 "OpDecorate %groups BufferBlock\n"
2667                 "OpDecorate %groupm Offset 0\n"
2668                 "%groups = OpDecorationGroup\n"
2669                 "%groupm = OpDecorationGroup\n"
2670
2671                 // Group decoration on multiple structs.
2672                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2673                 // Group decoration on multiple struct members.
2674                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2675
2676                 "OpDecorate %group1 DescriptorSet 0\n"
2677                 "OpDecorate %group3 DescriptorSet 0\n"
2678                 "OpDecorate %group3 NonWritable\n"
2679                 "OpDecorate %group3 Restrict\n"
2680                 "%group0 = OpDecorationGroup\n"
2681                 "%group1 = OpDecorationGroup\n"
2682                 "%group3 = OpDecorationGroup\n"
2683
2684                 // Applying the same decoration group multiple times.
2685                 "OpGroupDecorate %group1 %outdata\n"
2686                 "OpGroupDecorate %group1 %outdata\n"
2687                 "OpGroupDecorate %group1 %outdata\n"
2688                 "OpDecorate %outdata DescriptorSet 0\n"
2689                 "OpDecorate %outdata Binding 5\n"
2690                 // Applying decoration group containing nothing.
2691                 "OpGroupDecorate %group0 %indata0\n"
2692                 "OpDecorate %indata0 DescriptorSet 0\n"
2693                 "OpDecorate %indata0 Binding 0\n"
2694                 // Applying decoration group containing one decoration.
2695                 "OpGroupDecorate %group1 %indata1\n"
2696                 "OpDecorate %indata1 Binding 1\n"
2697                 // Applying decoration group containing multiple decorations.
2698                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2699                 "OpDecorate %indata2 Binding 2\n"
2700                 "OpDecorate %indata3 Binding 3\n"
2701                 // Applying multiple decoration groups (with overlapping).
2702                 "OpGroupDecorate %group0 %indata4\n"
2703                 "OpGroupDecorate %group1 %indata4\n"
2704                 "OpGroupDecorate %group3 %indata4\n"
2705                 "OpDecorate %indata4 Binding 4\n"
2706
2707                 + string(getComputeAsmCommonTypes()) +
2708
2709                 "%id   = OpVariable %uvec3ptr Input\n"
2710                 "%zero = OpConstant %i32 0\n"
2711
2712                 "%outbuf    = OpTypeStruct %f32arr\n"
2713                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2714                 "%outdata   = OpVariable %outbufptr Uniform\n"
2715                 "%inbuf0    = OpTypeStruct %f32arr\n"
2716                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2717                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2718                 "%inbuf1    = OpTypeStruct %f32arr\n"
2719                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2720                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2721                 "%inbuf2    = OpTypeStruct %f32arr\n"
2722                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2723                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2724                 "%inbuf3    = OpTypeStruct %f32arr\n"
2725                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2726                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2727                 "%inbuf4    = OpTypeStruct %f32arr\n"
2728                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2729                 "%indata4   = OpVariable %inbufptr Uniform\n"
2730
2731                 "%main   = OpFunction %void None %voidf\n"
2732                 "%label  = OpLabel\n"
2733                 "%idval  = OpLoad %uvec3 %id\n"
2734                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2735                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2736                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2737                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2738                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2739                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2740                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2741                 "%inval0 = OpLoad %f32 %inloc0\n"
2742                 "%inval1 = OpLoad %f32 %inloc1\n"
2743                 "%inval2 = OpLoad %f32 %inloc2\n"
2744                 "%inval3 = OpLoad %f32 %inloc3\n"
2745                 "%inval4 = OpLoad %f32 %inloc4\n"
2746                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2747                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2748                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2749                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2750                 "          OpStore %outloc %add\n"
2751                 "          OpReturn\n"
2752                 "          OpFunctionEnd\n";
2753         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2754         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2755         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2756         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2757         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2758         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2759         spec.numWorkGroups = IVec3(numElements, 1, 1);
2760
2761         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2762
2763         return group.release();
2764 }
2765
2766 struct SpecConstantTwoIntCase
2767 {
2768         const char*             caseName;
2769         const char*             scDefinition0;
2770         const char*             scDefinition1;
2771         const char*             scResultType;
2772         const char*             scOperation;
2773         deInt32                 scActualValue0;
2774         deInt32                 scActualValue1;
2775         const char*             resultOperation;
2776         vector<deInt32> expectedOutput;
2777         deInt32                 scActualValueLength;
2778
2779                                         SpecConstantTwoIntCase (const char* name,
2780                                                                                         const char* definition0,
2781                                                                                         const char* definition1,
2782                                                                                         const char* resultType,
2783                                                                                         const char* operation,
2784                                                                                         deInt32 value0,
2785                                                                                         deInt32 value1,
2786                                                                                         const char* resultOp,
2787                                                                                         const vector<deInt32>& output,
2788                                                                                         const deInt32   valueLength = sizeof(deInt32))
2789                                                 : caseName                              (name)
2790                                                 , scDefinition0                 (definition0)
2791                                                 , scDefinition1                 (definition1)
2792                                                 , scResultType                  (resultType)
2793                                                 , scOperation                   (operation)
2794                                                 , scActualValue0                (value0)
2795                                                 , scActualValue1                (value1)
2796                                                 , resultOperation               (resultOp)
2797                                                 , expectedOutput                (output)
2798                                                 , scActualValueLength   (valueLength)
2799                                                 {}
2800 };
2801
2802 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2803 {
2804         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2805         vector<SpecConstantTwoIntCase>  cases;
2806         de::Random                                              rnd                             (deStringHash(group->getName()));
2807         const int                                               numElements             = 100;
2808         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2809         vector<deInt32>                                 inputInts               (numElements, 0);
2810         vector<deInt32>                                 outputInts1             (numElements, 0);
2811         vector<deInt32>                                 outputInts2             (numElements, 0);
2812         vector<deInt32>                                 outputInts3             (numElements, 0);
2813         vector<deInt32>                                 outputInts4             (numElements, 0);
2814         const StringTemplate                    shaderTemplate  (
2815                 "${CAPABILITIES:opt}"
2816                 + string(getComputeAsmShaderPreamble()) +
2817
2818                 "OpName %main           \"main\"\n"
2819                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2820
2821                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2822                 "OpDecorate %sc_0  SpecId 0\n"
2823                 "OpDecorate %sc_1  SpecId 1\n"
2824                 "OpDecorate %i32arr ArrayStride 4\n"
2825
2826                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2827
2828                 "${OPTYPE_DEFINITIONS:opt}"
2829                 "%buf     = OpTypeStruct %i32arr\n"
2830                 "%bufptr  = OpTypePointer Uniform %buf\n"
2831                 "%indata    = OpVariable %bufptr Uniform\n"
2832                 "%outdata   = OpVariable %bufptr Uniform\n"
2833
2834                 "%id        = OpVariable %uvec3ptr Input\n"
2835                 "%zero      = OpConstant %i32 0\n"
2836
2837                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2838                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2839                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2840
2841                 "%main      = OpFunction %void None %voidf\n"
2842                 "%label     = OpLabel\n"
2843                 "${TYPE_CONVERT:opt}"
2844                 "%idval     = OpLoad %uvec3 %id\n"
2845                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2846                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2847                 "%inval     = OpLoad %i32 %inloc\n"
2848                 "%final     = ${GEN_RESULT}\n"
2849                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2850                 "             OpStore %outloc %final\n"
2851                 "             OpReturn\n"
2852                 "             OpFunctionEnd\n");
2853
2854         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2855
2856         for (size_t ndx = 0; ndx < numElements; ++ndx)
2857         {
2858                 outputInts1[ndx] = inputInts[ndx] + 42;
2859                 outputInts2[ndx] = inputInts[ndx];
2860                 outputInts3[ndx] = inputInts[ndx] - 11200;
2861                 outputInts4[ndx] = inputInts[ndx] + 1;
2862         }
2863
2864         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2865         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2866         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2867         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2868
2869         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2870         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2871         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2872         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2873         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2874         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2875         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2876         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2877         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2878         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2879         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2880         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2881         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2882         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2883         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2884         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2885         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2886         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2887         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2888         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2889         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2890         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2891         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2892         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2893         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2894         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2895         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2896         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2897         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2898         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2899         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2900         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2901         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2902         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2903         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2904         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2905
2906         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2907         {
2908                 map<string, string>             specializations;
2909                 ComputeShaderSpec               spec;
2910
2911                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2912                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2913                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2914                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2915                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2916
2917                 // Special SPIR-V code for SConvert-case
2918                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2919                 {
2920                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2921                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2922                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2923                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2924                 }
2925
2926                 // Special SPIR-V code for FConvert-case
2927                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2928                 {
2929                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2930                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2931                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2932                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2933                 }
2934
2935                 // Special SPIR-V code for FConvert-case for 16-bit floats
2936                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2937                 {
2938                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2939                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2940                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2941                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2942                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2943                 }
2944
2945                 spec.assembly = shaderTemplate.specialize(specializations);
2946                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2947                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2948                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2949                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2950                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2951
2952                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2953         }
2954
2955         ComputeShaderSpec                               spec;
2956
2957         spec.assembly =
2958                 string(getComputeAsmShaderPreamble()) +
2959
2960                 "OpName %main           \"main\"\n"
2961                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2962
2963                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2964                 "OpDecorate %sc_0  SpecId 0\n"
2965                 "OpDecorate %sc_1  SpecId 1\n"
2966                 "OpDecorate %sc_2  SpecId 2\n"
2967                 "OpDecorate %i32arr ArrayStride 4\n"
2968
2969                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2970
2971                 "%ivec3       = OpTypeVector %i32 3\n"
2972                 "%buf         = OpTypeStruct %i32arr\n"
2973                 "%bufptr      = OpTypePointer Uniform %buf\n"
2974                 "%indata      = OpVariable %bufptr Uniform\n"
2975                 "%outdata     = OpVariable %bufptr Uniform\n"
2976
2977                 "%id          = OpVariable %uvec3ptr Input\n"
2978                 "%zero        = OpConstant %i32 0\n"
2979                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2980                 "%vec3_undef  = OpUndef %ivec3\n"
2981
2982                 "%sc_0        = OpSpecConstant %i32 0\n"
2983                 "%sc_1        = OpSpecConstant %i32 0\n"
2984                 "%sc_2        = OpSpecConstant %i32 0\n"
2985                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2986                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2987                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2988                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2989                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2990                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2991                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2992                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2993                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2994                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2995                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2996                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2997                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2998
2999                 "%main      = OpFunction %void None %voidf\n"
3000                 "%label     = OpLabel\n"
3001                 "%idval     = OpLoad %uvec3 %id\n"
3002                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3003                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
3004                 "%inval     = OpLoad %i32 %inloc\n"
3005                 "%final     = OpIAdd %i32 %inval %sc_final\n"
3006                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
3007                 "             OpStore %outloc %final\n"
3008                 "             OpReturn\n"
3009                 "             OpFunctionEnd\n";
3010         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
3011         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
3012         spec.numWorkGroups = IVec3(numElements, 1, 1);
3013         spec.specConstants.append<deInt32>(123);
3014         spec.specConstants.append<deInt32>(56);
3015         spec.specConstants.append<deInt32>(-77);
3016
3017         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
3018
3019         return group.release();
3020 }
3021
3022 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
3023 {
3024         ComputeShaderSpec       specInt;
3025         ComputeShaderSpec       specFloat;
3026         ComputeShaderSpec       specFloat16;
3027         ComputeShaderSpec       specVec3;
3028         ComputeShaderSpec       specMat4;
3029         ComputeShaderSpec       specArray;
3030         ComputeShaderSpec       specStruct;
3031         de::Random                      rnd                             (deStringHash(group->getName()));
3032         const int                       numElements             = 100;
3033         vector<float>           inputFloats             (numElements, 0);
3034         vector<float>           outputFloats    (numElements, 0);
3035         vector<deFloat16>       inputFloats16   (numElements, 0);
3036         vector<deFloat16>       outputFloats16  (numElements, 0);
3037
3038         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3039
3040         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3041         floorAll(inputFloats);
3042
3043         for (size_t ndx = 0; ndx < numElements; ++ndx)
3044         {
3045                 // Just check if the value is positive or not
3046                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
3047         }
3048
3049         for (size_t ndx = 0; ndx < numElements; ++ndx)
3050         {
3051                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
3052                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
3053         }
3054
3055         // All of the tests are of the form:
3056         //
3057         // testtype r
3058         //
3059         // if (inputdata > 0)
3060         //   r = 1
3061         // else
3062         //   r = -1
3063         //
3064         // return (float)r
3065
3066         specFloat.assembly =
3067                 string(getComputeAsmShaderPreamble()) +
3068
3069                 "OpSource GLSL 430\n"
3070                 "OpName %main \"main\"\n"
3071                 "OpName %id \"gl_GlobalInvocationID\"\n"
3072
3073                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3074
3075                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3076
3077                 "%id = OpVariable %uvec3ptr Input\n"
3078                 "%zero       = OpConstant %i32 0\n"
3079                 "%float_0    = OpConstant %f32 0.0\n"
3080                 "%float_1    = OpConstant %f32 1.0\n"
3081                 "%float_n1   = OpConstant %f32 -1.0\n"
3082
3083                 "%main     = OpFunction %void None %voidf\n"
3084                 "%entry    = OpLabel\n"
3085                 "%idval    = OpLoad %uvec3 %id\n"
3086                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3087                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3088                 "%inval    = OpLoad %f32 %inloc\n"
3089
3090                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3091                 "            OpSelectionMerge %cm None\n"
3092                 "            OpBranchConditional %comp %tb %fb\n"
3093                 "%tb       = OpLabel\n"
3094                 "            OpBranch %cm\n"
3095                 "%fb       = OpLabel\n"
3096                 "            OpBranch %cm\n"
3097                 "%cm       = OpLabel\n"
3098                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
3099
3100                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3101                 "            OpStore %outloc %res\n"
3102                 "            OpReturn\n"
3103
3104                 "            OpFunctionEnd\n";
3105         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3106         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3107         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
3108
3109         specFloat16.assembly =
3110                 "OpCapability Shader\n"
3111                 "OpCapability StorageUniformBufferBlock16\n"
3112                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
3113                 "OpMemoryModel Logical GLSL450\n"
3114                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3115                 "OpExecutionMode %main LocalSize 1 1 1\n"
3116
3117                 "OpSource GLSL 430\n"
3118                 "OpName %main \"main\"\n"
3119                 "OpName %id \"gl_GlobalInvocationID\"\n"
3120
3121                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3122
3123                 "OpDecorate %buf BufferBlock\n"
3124                 "OpDecorate %indata DescriptorSet 0\n"
3125                 "OpDecorate %indata Binding 0\n"
3126                 "OpDecorate %outdata DescriptorSet 0\n"
3127                 "OpDecorate %outdata Binding 1\n"
3128                 "OpDecorate %f16arr ArrayStride 2\n"
3129                 "OpMemberDecorate %buf 0 Offset 0\n"
3130
3131                 "%f16      = OpTypeFloat 16\n"
3132                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3133                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3134
3135                 + string(getComputeAsmCommonTypes()) +
3136
3137                 "%buf      = OpTypeStruct %f16arr\n"
3138                 "%bufptr   = OpTypePointer Uniform %buf\n"
3139                 "%indata   = OpVariable %bufptr Uniform\n"
3140                 "%outdata  = OpVariable %bufptr Uniform\n"
3141
3142                 "%id       = OpVariable %uvec3ptr Input\n"
3143                 "%zero     = OpConstant %i32 0\n"
3144                 "%float_0  = OpConstant %f16 0.0\n"
3145                 "%float_1  = OpConstant %f16 1.0\n"
3146                 "%float_n1 = OpConstant %f16 -1.0\n"
3147
3148                 "%main     = OpFunction %void None %voidf\n"
3149                 "%entry    = OpLabel\n"
3150                 "%idval    = OpLoad %uvec3 %id\n"
3151                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3152                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3153                 "%inval    = OpLoad %f16 %inloc\n"
3154
3155                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3156                 "            OpSelectionMerge %cm None\n"
3157                 "            OpBranchConditional %comp %tb %fb\n"
3158                 "%tb       = OpLabel\n"
3159                 "            OpBranch %cm\n"
3160                 "%fb       = OpLabel\n"
3161                 "            OpBranch %cm\n"
3162                 "%cm       = OpLabel\n"
3163                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3164
3165                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3166                 "            OpStore %outloc %res\n"
3167                 "            OpReturn\n"
3168
3169                 "            OpFunctionEnd\n";
3170         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3171         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3172         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3173         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3174         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3175
3176         specMat4.assembly =
3177                 string(getComputeAsmShaderPreamble()) +
3178
3179                 "OpSource GLSL 430\n"
3180                 "OpName %main \"main\"\n"
3181                 "OpName %id \"gl_GlobalInvocationID\"\n"
3182
3183                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3184
3185                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3186
3187                 "%id = OpVariable %uvec3ptr Input\n"
3188                 "%v4f32      = OpTypeVector %f32 4\n"
3189                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3190                 "%zero       = OpConstant %i32 0\n"
3191                 "%float_0    = OpConstant %f32 0.0\n"
3192                 "%float_1    = OpConstant %f32 1.0\n"
3193                 "%float_n1   = OpConstant %f32 -1.0\n"
3194                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3195                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3196                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3197                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3198                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3199                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3200                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3201                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3202                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3203                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3204
3205                 "%main     = OpFunction %void None %voidf\n"
3206                 "%entry    = OpLabel\n"
3207                 "%idval    = OpLoad %uvec3 %id\n"
3208                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3209                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3210                 "%inval    = OpLoad %f32 %inloc\n"
3211
3212                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3213                 "            OpSelectionMerge %cm None\n"
3214                 "            OpBranchConditional %comp %tb %fb\n"
3215                 "%tb       = OpLabel\n"
3216                 "            OpBranch %cm\n"
3217                 "%fb       = OpLabel\n"
3218                 "            OpBranch %cm\n"
3219                 "%cm       = OpLabel\n"
3220                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3221                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3222
3223                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3224                 "            OpStore %outloc %res\n"
3225                 "            OpReturn\n"
3226
3227                 "            OpFunctionEnd\n";
3228         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3229         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3230         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3231
3232         specVec3.assembly =
3233                 string(getComputeAsmShaderPreamble()) +
3234
3235                 "OpSource GLSL 430\n"
3236                 "OpName %main \"main\"\n"
3237                 "OpName %id \"gl_GlobalInvocationID\"\n"
3238
3239                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3240
3241                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3242
3243                 "%id = OpVariable %uvec3ptr Input\n"
3244                 "%zero       = OpConstant %i32 0\n"
3245                 "%float_0    = OpConstant %f32 0.0\n"
3246                 "%float_1    = OpConstant %f32 1.0\n"
3247                 "%float_n1   = OpConstant %f32 -1.0\n"
3248                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3249                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3250
3251                 "%main     = OpFunction %void None %voidf\n"
3252                 "%entry    = OpLabel\n"
3253                 "%idval    = OpLoad %uvec3 %id\n"
3254                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3255                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3256                 "%inval    = OpLoad %f32 %inloc\n"
3257
3258                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3259                 "            OpSelectionMerge %cm None\n"
3260                 "            OpBranchConditional %comp %tb %fb\n"
3261                 "%tb       = OpLabel\n"
3262                 "            OpBranch %cm\n"
3263                 "%fb       = OpLabel\n"
3264                 "            OpBranch %cm\n"
3265                 "%cm       = OpLabel\n"
3266                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3267                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3268
3269                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3270                 "            OpStore %outloc %res\n"
3271                 "            OpReturn\n"
3272
3273                 "            OpFunctionEnd\n";
3274         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3275         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3276         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3277
3278         specInt.assembly =
3279                 string(getComputeAsmShaderPreamble()) +
3280
3281                 "OpSource GLSL 430\n"
3282                 "OpName %main \"main\"\n"
3283                 "OpName %id \"gl_GlobalInvocationID\"\n"
3284
3285                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3286
3287                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3288
3289                 "%id = OpVariable %uvec3ptr Input\n"
3290                 "%zero       = OpConstant %i32 0\n"
3291                 "%float_0    = OpConstant %f32 0.0\n"
3292                 "%i1         = OpConstant %i32 1\n"
3293                 "%i2         = OpConstant %i32 -1\n"
3294
3295                 "%main     = OpFunction %void None %voidf\n"
3296                 "%entry    = OpLabel\n"
3297                 "%idval    = OpLoad %uvec3 %id\n"
3298                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3299                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3300                 "%inval    = OpLoad %f32 %inloc\n"
3301
3302                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3303                 "            OpSelectionMerge %cm None\n"
3304                 "            OpBranchConditional %comp %tb %fb\n"
3305                 "%tb       = OpLabel\n"
3306                 "            OpBranch %cm\n"
3307                 "%fb       = OpLabel\n"
3308                 "            OpBranch %cm\n"
3309                 "%cm       = OpLabel\n"
3310                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3311                 "%res      = OpConvertSToF %f32 %ires\n"
3312
3313                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3314                 "            OpStore %outloc %res\n"
3315                 "            OpReturn\n"
3316
3317                 "            OpFunctionEnd\n";
3318         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3319         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3320         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3321
3322         specArray.assembly =
3323                 string(getComputeAsmShaderPreamble()) +
3324
3325                 "OpSource GLSL 430\n"
3326                 "OpName %main \"main\"\n"
3327                 "OpName %id \"gl_GlobalInvocationID\"\n"
3328
3329                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3330
3331                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3332
3333                 "%id = OpVariable %uvec3ptr Input\n"
3334                 "%zero       = OpConstant %i32 0\n"
3335                 "%u7         = OpConstant %u32 7\n"
3336                 "%float_0    = OpConstant %f32 0.0\n"
3337                 "%float_1    = OpConstant %f32 1.0\n"
3338                 "%float_n1   = OpConstant %f32 -1.0\n"
3339                 "%f32a7      = OpTypeArray %f32 %u7\n"
3340                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3341                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3342                 "%main     = OpFunction %void None %voidf\n"
3343                 "%entry    = OpLabel\n"
3344                 "%idval    = OpLoad %uvec3 %id\n"
3345                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3346                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3347                 "%inval    = OpLoad %f32 %inloc\n"
3348
3349                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3350                 "            OpSelectionMerge %cm None\n"
3351                 "            OpBranchConditional %comp %tb %fb\n"
3352                 "%tb       = OpLabel\n"
3353                 "            OpBranch %cm\n"
3354                 "%fb       = OpLabel\n"
3355                 "            OpBranch %cm\n"
3356                 "%cm       = OpLabel\n"
3357                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3358                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3359
3360                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3361                 "            OpStore %outloc %res\n"
3362                 "            OpReturn\n"
3363
3364                 "            OpFunctionEnd\n";
3365         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3366         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3367         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3368
3369         specStruct.assembly =
3370                 string(getComputeAsmShaderPreamble()) +
3371
3372                 "OpSource GLSL 430\n"
3373                 "OpName %main \"main\"\n"
3374                 "OpName %id \"gl_GlobalInvocationID\"\n"
3375
3376                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3377
3378                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3379
3380                 "%id = OpVariable %uvec3ptr Input\n"
3381                 "%zero       = OpConstant %i32 0\n"
3382                 "%float_0    = OpConstant %f32 0.0\n"
3383                 "%float_1    = OpConstant %f32 1.0\n"
3384                 "%float_n1   = OpConstant %f32 -1.0\n"
3385
3386                 "%v2f32      = OpTypeVector %f32 2\n"
3387                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3388                 "%Data       = OpTypeStruct %Data2 %f32\n"
3389
3390                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3391                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3392                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3393                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3394                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3395                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3396
3397                 "%main     = OpFunction %void None %voidf\n"
3398                 "%entry    = OpLabel\n"
3399                 "%idval    = OpLoad %uvec3 %id\n"
3400                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3401                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3402                 "%inval    = OpLoad %f32 %inloc\n"
3403
3404                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3405                 "            OpSelectionMerge %cm None\n"
3406                 "            OpBranchConditional %comp %tb %fb\n"
3407                 "%tb       = OpLabel\n"
3408                 "            OpBranch %cm\n"
3409                 "%fb       = OpLabel\n"
3410                 "            OpBranch %cm\n"
3411                 "%cm       = OpLabel\n"
3412                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3413                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3414
3415                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3416                 "            OpStore %outloc %res\n"
3417                 "            OpReturn\n"
3418
3419                 "            OpFunctionEnd\n";
3420         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3421         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3422         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3423
3424         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3425         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3426         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3427         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3428         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3429         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3430         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3431 }
3432
3433 string generateConstantDefinitions (int count)
3434 {
3435         std::ostringstream      r;
3436         for (int i = 0; i < count; i++)
3437                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3438         r << "\n";
3439         return r.str();
3440 }
3441
3442 string generateSwitchCases (int count)
3443 {
3444         std::ostringstream      r;
3445         for (int i = 0; i < count; i++)
3446                 r << " " << i << " %case" << i;
3447         r << "\n";
3448         return r.str();
3449 }
3450
3451 string generateSwitchTargets (int count)
3452 {
3453         std::ostringstream      r;
3454         for (int i = 0; i < count; i++)
3455                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3456         r << "\n";
3457         return r.str();
3458 }
3459
3460 string generateOpPhiParams (int count)
3461 {
3462         std::ostringstream      r;
3463         for (int i = 0; i < count; i++)
3464                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3465         r << "\n";
3466         return r.str();
3467 }
3468
3469 string generateIntWidth (int value)
3470 {
3471         std::ostringstream      r;
3472         r << value;
3473         return r.str();
3474 }
3475
3476 // Expand input string by injecting "ABC" between the input
3477 // string characters. The acc/add/treshold parameters are used
3478 // to skip some of the injections to make the result less
3479 // uniform (and a lot shorter).
3480 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3481 {
3482         std::ostringstream      res;
3483         const char*                     p = s.c_str();
3484
3485         while (*p)
3486         {
3487                 res << *p;
3488                 acc += add;
3489                 if (acc > treshold)
3490                 {
3491                         acc -= treshold;
3492                         res << "ABC";
3493                 }
3494                 p++;
3495         }
3496         return res.str();
3497 }
3498
3499 // Calculate expected result based on the code string
3500 float calcOpPhiCase5 (float val, const string& s)
3501 {
3502         const char*             p               = s.c_str();
3503         float                   x[8];
3504         bool                    b[8];
3505         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3506         const float             v               = deFloatAbs(val);
3507         float                   res             = 0;
3508         int                             depth   = -1;
3509         int                             skip    = 0;
3510
3511         for (int i = 7; i >= 0; --i)
3512                 x[i] = std::fmod((float)v, (float)(2 << i));
3513         for (int i = 7; i >= 0; --i)
3514                 b[i] = x[i] > tv[i];
3515
3516         while (*p)
3517         {
3518                 if (*p == 'A')
3519                 {
3520                         depth++;
3521                         if (skip == 0 && b[depth])
3522                         {
3523                                 res++;
3524                         }
3525                         else
3526                                 skip++;
3527                 }
3528                 if (*p == 'B')
3529                 {
3530                         if (skip)
3531                                 skip--;
3532                         if (b[depth] || skip)
3533                                 skip++;
3534                 }
3535                 if (*p == 'C')
3536                 {
3537                         depth--;
3538                         if (skip)
3539                                 skip--;
3540                 }
3541                 p++;
3542         }
3543         return res;
3544 }
3545
3546 // In the code string, the letters represent the following:
3547 //
3548 // A:
3549 //     if (certain bit is set)
3550 //     {
3551 //       result++;
3552 //
3553 // B:
3554 //     } else {
3555 //
3556 // C:
3557 //     }
3558 //
3559 // examples:
3560 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3561 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3562 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3563 //
3564 // Code generation gets a bit complicated due to the else-branches,
3565 // which do not generate new values. Thus, the generator needs to
3566 // keep track of the previous variable change seen by the else
3567 // branch.
3568 string generateOpPhiCase5 (const string& s)
3569 {
3570         std::stack<int>                         idStack;
3571         std::stack<std::string>         value;
3572         std::stack<std::string>         valueLabel;
3573         std::stack<std::string>         mergeLeft;
3574         std::stack<std::string>         mergeRight;
3575         std::ostringstream                      res;
3576         const char*                                     p                       = s.c_str();
3577         int                                                     depth           = -1;
3578         int                                                     currId          = 0;
3579         int                                                     iter            = 0;
3580
3581         idStack.push(-1);
3582         value.push("%f32_0");
3583         valueLabel.push("%f32_0 %entry");
3584
3585         while (*p)
3586         {
3587                 if (*p == 'A')
3588                 {
3589                         depth++;
3590                         currId = iter;
3591                         idStack.push(currId);
3592                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3593                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3594                         res << "%t" << currId << " = OpLabel\n";
3595                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3596                         std::ostringstream tag;
3597                         tag << "%rt" << currId;
3598                         value.push(tag.str());
3599                         tag << " %t" << currId;
3600                         valueLabel.push(tag.str());
3601                 }
3602
3603                 if (*p == 'B')
3604                 {
3605                         mergeLeft.push(valueLabel.top());
3606                         value.pop();
3607                         valueLabel.pop();
3608                         res << "\tOpBranch %m" << currId << "\n";
3609                         res << "%f" << currId << " = OpLabel\n";
3610                         std::ostringstream tag;
3611                         tag << value.top() << " %f" << currId;
3612                         valueLabel.pop();
3613                         valueLabel.push(tag.str());
3614                 }
3615
3616                 if (*p == 'C')
3617                 {
3618                         mergeRight.push(valueLabel.top());
3619                         res << "\tOpBranch %m" << currId << "\n";
3620                         res << "%m" << currId << " = OpLabel\n";
3621                         if (*(p + 1) == 0)
3622                                 res << "%res"; // last result goes to %res
3623                         else
3624                                 res << "%rm" << currId;
3625                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3626                         std::ostringstream tag;
3627                         tag << "%rm" << currId;
3628                         value.pop();
3629                         value.push(tag.str());
3630                         tag << " %m" << currId;
3631                         valueLabel.pop();
3632                         valueLabel.push(tag.str());
3633                         mergeLeft.pop();
3634                         mergeRight.pop();
3635                         depth--;
3636                         idStack.pop();
3637                         currId = idStack.top();
3638                 }
3639                 p++;
3640                 iter++;
3641         }
3642         return res.str();
3643 }
3644
3645 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3646 {
3647         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3648         ComputeShaderSpec                               spec1;
3649         ComputeShaderSpec                               spec2;
3650         ComputeShaderSpec                               spec3;
3651         ComputeShaderSpec                               spec4;
3652         ComputeShaderSpec                               spec5;
3653         de::Random                                              rnd                             (deStringHash(group->getName()));
3654         const int                                               numElements             = 100;
3655         vector<float>                                   inputFloats             (numElements, 0);
3656         vector<float>                                   outputFloats1   (numElements, 0);
3657         vector<float>                                   outputFloats2   (numElements, 0);
3658         vector<float>                                   outputFloats3   (numElements, 0);
3659         vector<float>                                   outputFloats4   (numElements, 0);
3660         vector<float>                                   outputFloats5   (numElements, 0);
3661         std::string                                             codestring              = "ABC";
3662         const int                                               test4Width              = 1024;
3663
3664         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3665         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3666         // shader code.
3667         for (int i = 0, acc = 0; i < 9; i++)
3668                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3669
3670         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3671
3672         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3673         floorAll(inputFloats);
3674
3675         for (size_t ndx = 0; ndx < numElements; ++ndx)
3676         {
3677                 switch (ndx % 3)
3678                 {
3679                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3680                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3681                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3682                         default:        break;
3683                 }
3684                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3685                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3686
3687                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3688                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3689
3690                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3691         }
3692
3693         spec1.assembly =
3694                 string(getComputeAsmShaderPreamble()) +
3695
3696                 "OpSource GLSL 430\n"
3697                 "OpName %main \"main\"\n"
3698                 "OpName %id \"gl_GlobalInvocationID\"\n"
3699
3700                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3701
3702                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3703
3704                 "%id = OpVariable %uvec3ptr Input\n"
3705                 "%zero       = OpConstant %i32 0\n"
3706                 "%three      = OpConstant %u32 3\n"
3707                 "%constf5p5  = OpConstant %f32 5.5\n"
3708                 "%constf20p5 = OpConstant %f32 20.5\n"
3709                 "%constf1p75 = OpConstant %f32 1.75\n"
3710                 "%constf8p5  = OpConstant %f32 8.5\n"
3711                 "%constf6p5  = OpConstant %f32 6.5\n"
3712
3713                 "%main     = OpFunction %void None %voidf\n"
3714                 "%entry    = OpLabel\n"
3715                 "%idval    = OpLoad %uvec3 %id\n"
3716                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3717                 "%selector = OpUMod %u32 %x %three\n"
3718                 "            OpSelectionMerge %phi None\n"
3719                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3720
3721                 // Case 1 before OpPhi.
3722                 "%case1    = OpLabel\n"
3723                 "            OpBranch %phi\n"
3724
3725                 "%default  = OpLabel\n"
3726                 "            OpUnreachable\n"
3727
3728                 "%phi      = OpLabel\n"
3729                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3730                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3731                 "%inval    = OpLoad %f32 %inloc\n"
3732                 "%add      = OpFAdd %f32 %inval %operand\n"
3733                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3734                 "            OpStore %outloc %add\n"
3735                 "            OpReturn\n"
3736
3737                 // Case 0 after OpPhi.
3738                 "%case0    = OpLabel\n"
3739                 "            OpBranch %phi\n"
3740
3741
3742                 // Case 2 after OpPhi.
3743                 "%case2    = OpLabel\n"
3744                 "            OpBranch %phi\n"
3745
3746                 "            OpFunctionEnd\n";
3747         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3748         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3749         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3750
3751         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3752
3753         spec2.assembly =
3754                 string(getComputeAsmShaderPreamble()) +
3755
3756                 "OpName %main \"main\"\n"
3757                 "OpName %id \"gl_GlobalInvocationID\"\n"
3758
3759                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3760
3761                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3762
3763                 "%id         = OpVariable %uvec3ptr Input\n"
3764                 "%zero       = OpConstant %i32 0\n"
3765                 "%one        = OpConstant %i32 1\n"
3766                 "%three      = OpConstant %i32 3\n"
3767                 "%constf6p5  = OpConstant %f32 6.5\n"
3768
3769                 "%main       = OpFunction %void None %voidf\n"
3770                 "%entry      = OpLabel\n"
3771                 "%idval      = OpLoad %uvec3 %id\n"
3772                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3773                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3774                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3775                 "%inval      = OpLoad %f32 %inloc\n"
3776                 "              OpBranch %phi\n"
3777
3778                 "%phi        = OpLabel\n"
3779                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3780                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3781                 "%step_next  = OpIAdd %i32 %step %one\n"
3782                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3783                 "%still_loop = OpSLessThan %bool %step %three\n"
3784                 "              OpLoopMerge %exit %phi None\n"
3785                 "              OpBranchConditional %still_loop %phi %exit\n"
3786
3787                 "%exit       = OpLabel\n"
3788                 "              OpStore %outloc %accum\n"
3789                 "              OpReturn\n"
3790                 "              OpFunctionEnd\n";
3791         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3792         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3793         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3794
3795         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3796
3797         spec3.assembly =
3798                 string(getComputeAsmShaderPreamble()) +
3799
3800                 "OpName %main \"main\"\n"
3801                 "OpName %id \"gl_GlobalInvocationID\"\n"
3802
3803                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3804
3805                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3806
3807                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3808                 "%id         = OpVariable %uvec3ptr Input\n"
3809                 "%true       = OpConstantTrue %bool\n"
3810                 "%false      = OpConstantFalse %bool\n"
3811                 "%zero       = OpConstant %i32 0\n"
3812                 "%constf8p5  = OpConstant %f32 8.5\n"
3813
3814                 "%main       = OpFunction %void None %voidf\n"
3815                 "%entry      = OpLabel\n"
3816                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3817                 "%idval      = OpLoad %uvec3 %id\n"
3818                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3819                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3820                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3821                 "%a_init     = OpLoad %f32 %inloc\n"
3822                 "%b_init     = OpLoad %f32 %b\n"
3823                 "              OpBranch %phi\n"
3824
3825                 "%phi        = OpLabel\n"
3826                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3827                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3828                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3829                 "              OpLoopMerge %exit %phi None\n"
3830                 "              OpBranchConditional %still_loop %phi %exit\n"
3831
3832                 "%exit       = OpLabel\n"
3833                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3834                 "              OpStore %outloc %sub\n"
3835                 "              OpReturn\n"
3836                 "              OpFunctionEnd\n";
3837         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3838         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3839         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3840
3841         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3842
3843         spec4.assembly =
3844                 "OpCapability Shader\n"
3845                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3846                 "OpMemoryModel Logical GLSL450\n"
3847                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3848                 "OpExecutionMode %main LocalSize 1 1 1\n"
3849
3850                 "OpSource GLSL 430\n"
3851                 "OpName %main \"main\"\n"
3852                 "OpName %id \"gl_GlobalInvocationID\"\n"
3853
3854                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3855
3856                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3857
3858                 "%id       = OpVariable %uvec3ptr Input\n"
3859                 "%zero     = OpConstant %i32 0\n"
3860                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3861
3862                 + generateConstantDefinitions(test4Width) +
3863
3864                 "%main     = OpFunction %void None %voidf\n"
3865                 "%entry    = OpLabel\n"
3866                 "%idval    = OpLoad %uvec3 %id\n"
3867                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3868                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3869                 "%inval    = OpLoad %f32 %inloc\n"
3870                 "%xf       = OpConvertUToF %f32 %x\n"
3871                 "%xm       = OpFMul %f32 %xf %inval\n"
3872                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3873                 "%xi       = OpConvertFToU %u32 %xa\n"
3874                 "%selector = OpUMod %u32 %xi %cimod\n"
3875                 "            OpSelectionMerge %phi None\n"
3876                 "            OpSwitch %selector %default "
3877
3878                 + generateSwitchCases(test4Width) +
3879
3880                 "%default  = OpLabel\n"
3881                 "            OpUnreachable\n"
3882
3883                 + generateSwitchTargets(test4Width) +
3884
3885                 "%phi      = OpLabel\n"
3886                 "%result   = OpPhi %f32"
3887
3888                 + generateOpPhiParams(test4Width) +
3889
3890                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3891                 "            OpStore %outloc %result\n"
3892                 "            OpReturn\n"
3893
3894                 "            OpFunctionEnd\n";
3895         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3896         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3897         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3898
3899         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3900
3901         spec5.assembly =
3902                 "OpCapability Shader\n"
3903                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3904                 "OpMemoryModel Logical GLSL450\n"
3905                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3906                 "OpExecutionMode %main LocalSize 1 1 1\n"
3907                 "%code     = OpString \"" + codestring + "\"\n"
3908
3909                 "OpSource GLSL 430\n"
3910                 "OpName %main \"main\"\n"
3911                 "OpName %id \"gl_GlobalInvocationID\"\n"
3912
3913                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3914
3915                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3916
3917                 "%id       = OpVariable %uvec3ptr Input\n"
3918                 "%zero     = OpConstant %i32 0\n"
3919                 "%f32_0    = OpConstant %f32 0.0\n"
3920                 "%f32_0_5  = OpConstant %f32 0.5\n"
3921                 "%f32_1    = OpConstant %f32 1.0\n"
3922                 "%f32_1_5  = OpConstant %f32 1.5\n"
3923                 "%f32_2    = OpConstant %f32 2.0\n"
3924                 "%f32_3_5  = OpConstant %f32 3.5\n"
3925                 "%f32_4    = OpConstant %f32 4.0\n"
3926                 "%f32_7_5  = OpConstant %f32 7.5\n"
3927                 "%f32_8    = OpConstant %f32 8.0\n"
3928                 "%f32_15_5 = OpConstant %f32 15.5\n"
3929                 "%f32_16   = OpConstant %f32 16.0\n"
3930                 "%f32_31_5 = OpConstant %f32 31.5\n"
3931                 "%f32_32   = OpConstant %f32 32.0\n"
3932                 "%f32_63_5 = OpConstant %f32 63.5\n"
3933                 "%f32_64   = OpConstant %f32 64.0\n"
3934                 "%f32_127_5 = OpConstant %f32 127.5\n"
3935                 "%f32_128  = OpConstant %f32 128.0\n"
3936                 "%f32_256  = OpConstant %f32 256.0\n"
3937
3938                 "%main     = OpFunction %void None %voidf\n"
3939                 "%entry    = OpLabel\n"
3940                 "%idval    = OpLoad %uvec3 %id\n"
3941                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3942                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3943                 "%inval    = OpLoad %f32 %inloc\n"
3944
3945                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3946                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3947                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3948                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3949                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3950                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3951                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3952                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3953                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3954
3955                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3956                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3957                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3958                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3959                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3960                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3961                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3962                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3963
3964                 + generateOpPhiCase5(codestring) +
3965
3966                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3967                 "            OpStore %outloc %res\n"
3968                 "            OpReturn\n"
3969
3970                 "            OpFunctionEnd\n";
3971         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3972         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3973         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3974
3975         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3976
3977         createOpPhiVartypeTests(group, testCtx);
3978
3979         return group.release();
3980 }
3981
3982 // Assembly code used for testing block order is based on GLSL source code:
3983 //
3984 // #version 430
3985 //
3986 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3987 //   float elements[];
3988 // } input_data;
3989 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3990 //   float elements[];
3991 // } output_data;
3992 //
3993 // void main() {
3994 //   uint x = gl_GlobalInvocationID.x;
3995 //   output_data.elements[x] = input_data.elements[x];
3996 //   if (x > uint(50)) {
3997 //     switch (x % uint(3)) {
3998 //       case 0: output_data.elements[x] += 1.5f; break;
3999 //       case 1: output_data.elements[x] += 42.f; break;
4000 //       case 2: output_data.elements[x] -= 27.f; break;
4001 //       default: break;
4002 //     }
4003 //   } else {
4004 //     output_data.elements[x] = -input_data.elements[x];
4005 //   }
4006 // }
4007 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
4008 {
4009         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
4010         ComputeShaderSpec                               spec;
4011         de::Random                                              rnd                             (deStringHash(group->getName()));
4012         const int                                               numElements             = 100;
4013         vector<float>                                   inputFloats             (numElements, 0);
4014         vector<float>                                   outputFloats    (numElements, 0);
4015
4016         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4017
4018         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
4019         floorAll(inputFloats);
4020
4021         for (size_t ndx = 0; ndx <= 50; ++ndx)
4022                 outputFloats[ndx] = -inputFloats[ndx];
4023
4024         for (size_t ndx = 51; ndx < numElements; ++ndx)
4025         {
4026                 switch (ndx % 3)
4027                 {
4028                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
4029                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
4030                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
4031                         default:        break;
4032                 }
4033         }
4034
4035         spec.assembly =
4036                 string(getComputeAsmShaderPreamble()) +
4037
4038                 "OpSource GLSL 430\n"
4039                 "OpName %main \"main\"\n"
4040                 "OpName %id \"gl_GlobalInvocationID\"\n"
4041
4042                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4043
4044                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4045
4046                 "%u32ptr       = OpTypePointer Function %u32\n"
4047                 "%u32ptr_input = OpTypePointer Input %u32\n"
4048
4049                 + string(getComputeAsmInputOutputBuffer()) +
4050
4051                 "%id        = OpVariable %uvec3ptr Input\n"
4052                 "%zero      = OpConstant %i32 0\n"
4053                 "%const3    = OpConstant %u32 3\n"
4054                 "%const50   = OpConstant %u32 50\n"
4055                 "%constf1p5 = OpConstant %f32 1.5\n"
4056                 "%constf27  = OpConstant %f32 27.0\n"
4057                 "%constf42  = OpConstant %f32 42.0\n"
4058
4059                 "%main = OpFunction %void None %voidf\n"
4060
4061                 // entry block.
4062                 "%entry    = OpLabel\n"
4063
4064                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
4065                 "%xvar     = OpVariable %u32ptr Function\n"
4066                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
4067                 "%x        = OpLoad %u32 %xptr\n"
4068                 "            OpStore %xvar %x\n"
4069
4070                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
4071                 "            OpSelectionMerge %if_merge None\n"
4072                 "            OpBranchConditional %cmp %if_true %if_false\n"
4073
4074                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
4075                 "%if_false = OpLabel\n"
4076                 "%x_f      = OpLoad %u32 %xvar\n"
4077                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
4078                 "%inval_f  = OpLoad %f32 %inloc_f\n"
4079                 "%negate   = OpFNegate %f32 %inval_f\n"
4080                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
4081                 "            OpStore %outloc_f %negate\n"
4082                 "            OpBranch %if_merge\n"
4083
4084                 // Merge block for if-statement: placed in the middle of true and false branch.
4085                 "%if_merge = OpLabel\n"
4086                 "            OpReturn\n"
4087
4088                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
4089                 "%if_true  = OpLabel\n"
4090                 "%xval_t   = OpLoad %u32 %xvar\n"
4091                 "%mod      = OpUMod %u32 %xval_t %const3\n"
4092                 "            OpSelectionMerge %switch_merge None\n"
4093                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
4094
4095                 // Merge block for switch-statement: placed before the case
4096                 // bodies.  But it must follow OpSwitch which dominates it.
4097                 "%switch_merge = OpLabel\n"
4098                 "                OpBranch %if_merge\n"
4099
4100                 // Case 1 for switch-statement: placed before case 0.
4101                 // It must follow the OpSwitch that dominates it.
4102                 "%case1    = OpLabel\n"
4103                 "%x_1      = OpLoad %u32 %xvar\n"
4104                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
4105                 "%inval_1  = OpLoad %f32 %inloc_1\n"
4106                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
4107                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
4108                 "            OpStore %outloc_1 %addf42\n"
4109                 "            OpBranch %switch_merge\n"
4110
4111                 // Case 2 for switch-statement.
4112                 "%case2    = OpLabel\n"
4113                 "%x_2      = OpLoad %u32 %xvar\n"
4114                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
4115                 "%inval_2  = OpLoad %f32 %inloc_2\n"
4116                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
4117                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
4118                 "            OpStore %outloc_2 %subf27\n"
4119                 "            OpBranch %switch_merge\n"
4120
4121                 // Default case for switch-statement: placed in the middle of normal cases.
4122                 "%default = OpLabel\n"
4123                 "           OpBranch %switch_merge\n"
4124
4125                 // Case 0 for switch-statement: out of order.
4126                 "%case0    = OpLabel\n"
4127                 "%x_0      = OpLoad %u32 %xvar\n"
4128                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4129                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4130                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4131                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4132                 "            OpStore %outloc_0 %addf1p5\n"
4133                 "            OpBranch %switch_merge\n"
4134
4135                 "            OpFunctionEnd\n";
4136         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4137         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4138         spec.numWorkGroups = IVec3(numElements, 1, 1);
4139
4140         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4141
4142         return group.release();
4143 }
4144
4145 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4146 {
4147         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4148         ComputeShaderSpec                               spec1;
4149         ComputeShaderSpec                               spec2;
4150         de::Random                                              rnd                             (deStringHash(group->getName()));
4151         const int                                               numElements             = 100;
4152         vector<float>                                   inputFloats             (numElements, 0);
4153         vector<float>                                   outputFloats1   (numElements, 0);
4154         vector<float>                                   outputFloats2   (numElements, 0);
4155         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4156
4157         for (size_t ndx = 0; ndx < numElements; ++ndx)
4158         {
4159                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4160                 outputFloats2[ndx] = -inputFloats[ndx];
4161         }
4162
4163         const string assembly(
4164                 "OpCapability Shader\n"
4165                 "OpMemoryModel Logical GLSL450\n"
4166                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4167                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4168                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4169                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4170                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4171                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4172
4173                 "OpName %comp_main1              \"entrypoint1\"\n"
4174                 "OpName %comp_main2              \"entrypoint2\"\n"
4175                 "OpName %vert_main               \"entrypoint2\"\n"
4176                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4177                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4178                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4179                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4180                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4181                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4182                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4183
4184                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4185                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4186                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4187                 "OpDecorate %vert_builtin_st         Block\n"
4188                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4189                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4190                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4191
4192                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4193
4194                 "%zero       = OpConstant %i32 0\n"
4195                 "%one        = OpConstant %u32 1\n"
4196                 "%c_f32_1    = OpConstant %f32 1\n"
4197
4198                 "%i32inputptr         = OpTypePointer Input %i32\n"
4199                 "%vec4                = OpTypeVector %f32 4\n"
4200                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4201                 "%f32arr1             = OpTypeArray %f32 %one\n"
4202                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4203                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4204                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4205
4206                 "%id         = OpVariable %uvec3ptr Input\n"
4207                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4208                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4209                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4210
4211                 // gl_Position = vec4(1.);
4212                 "%vert_main  = OpFunction %void None %voidf\n"
4213                 "%vert_entry = OpLabel\n"
4214                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4215                 "              OpStore %position %c_vec4_1\n"
4216                 "              OpReturn\n"
4217                 "              OpFunctionEnd\n"
4218
4219                 // Double inputs.
4220                 "%comp_main1  = OpFunction %void None %voidf\n"
4221                 "%comp1_entry = OpLabel\n"
4222                 "%idval1      = OpLoad %uvec3 %id\n"
4223                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4224                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4225                 "%inval1      = OpLoad %f32 %inloc1\n"
4226                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4227                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4228                 "               OpStore %outloc1 %add\n"
4229                 "               OpReturn\n"
4230                 "               OpFunctionEnd\n"
4231
4232                 // Negate inputs.
4233                 "%comp_main2  = OpFunction %void None %voidf\n"
4234                 "%comp2_entry = OpLabel\n"
4235                 "%idval2      = OpLoad %uvec3 %id\n"
4236                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4237                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4238                 "%inval2      = OpLoad %f32 %inloc2\n"
4239                 "%neg         = OpFNegate %f32 %inval2\n"
4240                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4241                 "               OpStore %outloc2 %neg\n"
4242                 "               OpReturn\n"
4243                 "               OpFunctionEnd\n");
4244
4245         spec1.assembly = assembly;
4246         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4247         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4248         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4249         spec1.entryPoint = "entrypoint1";
4250
4251         spec2.assembly = assembly;
4252         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4253         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4254         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4255         spec2.entryPoint = "entrypoint2";
4256
4257         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4258         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4259
4260         return group.release();
4261 }
4262
4263 inline std::string makeLongUTF8String (size_t num4ByteChars)
4264 {
4265         // An example of a longest valid UTF-8 character.  Be explicit about the
4266         // character type because Microsoft compilers can otherwise interpret the
4267         // character string as being over wide (16-bit) characters. Ideally, we
4268         // would just use a C++11 UTF-8 string literal, but we want to support older
4269         // Microsoft compilers.
4270         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4271         std::string longString;
4272         longString.reserve(num4ByteChars * 4);
4273         for (size_t count = 0; count < num4ByteChars; count++)
4274         {
4275                 longString += earthAfrica;
4276         }
4277         return longString;
4278 }
4279
4280 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4281 {
4282         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4283         vector<CaseParameter>                   cases;
4284         de::Random                                              rnd                             (deStringHash(group->getName()));
4285         const int                                               numElements             = 100;
4286         vector<float>                                   positiveFloats  (numElements, 0);
4287         vector<float>                                   negativeFloats  (numElements, 0);
4288         const StringTemplate                    shaderTemplate  (
4289                 "OpCapability Shader\n"
4290                 "OpMemoryModel Logical GLSL450\n"
4291
4292                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4293                 "OpExecutionMode %main LocalSize 1 1 1\n"
4294
4295                 "${SOURCE}\n"
4296
4297                 "OpName %main           \"main\"\n"
4298                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4299
4300                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4301
4302                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4303
4304                 "%id        = OpVariable %uvec3ptr Input\n"
4305                 "%zero      = OpConstant %i32 0\n"
4306
4307                 "%main      = OpFunction %void None %voidf\n"
4308                 "%label     = OpLabel\n"
4309                 "%idval     = OpLoad %uvec3 %id\n"
4310                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4311                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4312                 "%inval     = OpLoad %f32 %inloc\n"
4313                 "%neg       = OpFNegate %f32 %inval\n"
4314                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4315                 "             OpStore %outloc %neg\n"
4316                 "             OpReturn\n"
4317                 "             OpFunctionEnd\n");
4318
4319         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4320         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4321         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4322                                                                                                                                                         "OpSource GLSL 430 %fname"));
4323         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4324                                                                                                                                                         "OpSource GLSL 430 %fname"));
4325         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4326                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4327         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4328                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4329         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4330                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4331         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4332                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4333         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4334                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4335                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4336         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4337                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4338                                                                                                                                                         "OpSourceContinued \"\""));
4339         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4340                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4341                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4342         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4343                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4344                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4345         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4346                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4347                                                                                                                                                         "OpSourceContinued \"void\"\n"
4348                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4349                                                                                                                                                         "OpSourceContinued \"{}\""));
4350         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4351                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4352                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4353
4354         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4355
4356         for (size_t ndx = 0; ndx < numElements; ++ndx)
4357                 negativeFloats[ndx] = -positiveFloats[ndx];
4358
4359         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4360         {
4361                 map<string, string>             specializations;
4362                 ComputeShaderSpec               spec;
4363
4364                 specializations["SOURCE"] = cases[caseNdx].param;
4365                 spec.assembly = shaderTemplate.specialize(specializations);
4366                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4367                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4368                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4369
4370                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4371         }
4372
4373         return group.release();
4374 }
4375
4376 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4377 {
4378         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4379         vector<CaseParameter>                   cases;
4380         de::Random                                              rnd                             (deStringHash(group->getName()));
4381         const int                                               numElements             = 100;
4382         vector<float>                                   inputFloats             (numElements, 0);
4383         vector<float>                                   outputFloats    (numElements, 0);
4384         const StringTemplate                    shaderTemplate  (
4385                 string(getComputeAsmShaderPreamble()) +
4386
4387                 "OpSourceExtension \"${EXTENSION}\"\n"
4388
4389                 "OpName %main           \"main\"\n"
4390                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4391
4392                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4393
4394                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4395
4396                 "%id        = OpVariable %uvec3ptr Input\n"
4397                 "%zero      = OpConstant %i32 0\n"
4398
4399                 "%main      = OpFunction %void None %voidf\n"
4400                 "%label     = OpLabel\n"
4401                 "%idval     = OpLoad %uvec3 %id\n"
4402                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4403                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4404                 "%inval     = OpLoad %f32 %inloc\n"
4405                 "%neg       = OpFNegate %f32 %inval\n"
4406                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4407                 "             OpStore %outloc %neg\n"
4408                 "             OpReturn\n"
4409                 "             OpFunctionEnd\n");
4410
4411         cases.push_back(CaseParameter("empty_extension",        ""));
4412         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4413         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4414         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4415         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4416
4417         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4418
4419         for (size_t ndx = 0; ndx < numElements; ++ndx)
4420                 outputFloats[ndx] = -inputFloats[ndx];
4421
4422         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4423         {
4424                 map<string, string>             specializations;
4425                 ComputeShaderSpec               spec;
4426
4427                 specializations["EXTENSION"] = cases[caseNdx].param;
4428                 spec.assembly = shaderTemplate.specialize(specializations);
4429                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4430                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4431                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4432
4433                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4434         }
4435
4436         return group.release();
4437 }
4438
4439 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4440 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4441 {
4442         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4443         vector<CaseParameter>                   cases;
4444         de::Random                                              rnd                             (deStringHash(group->getName()));
4445         const int                                               numElements             = 100;
4446         vector<float>                                   positiveFloats  (numElements, 0);
4447         vector<float>                                   negativeFloats  (numElements, 0);
4448         const StringTemplate                    shaderTemplate  (
4449                 string(getComputeAsmShaderPreamble()) +
4450
4451                 "OpSource GLSL 430\n"
4452                 "OpName %main           \"main\"\n"
4453                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4454
4455                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4456
4457                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4458                 "%uvec2     = OpTypeVector %u32 2\n"
4459                 "%bvec3     = OpTypeVector %bool 3\n"
4460                 "%fvec4     = OpTypeVector %f32 4\n"
4461                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4462                 "%const100  = OpConstant %u32 100\n"
4463                 "%uarr100   = OpTypeArray %i32 %const100\n"
4464                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4465                 "%pointer   = OpTypePointer Function %i32\n"
4466                 + string(getComputeAsmInputOutputBuffer()) +
4467
4468                 "%null      = OpConstantNull ${TYPE}\n"
4469
4470                 "%id        = OpVariable %uvec3ptr Input\n"
4471                 "%zero      = OpConstant %i32 0\n"
4472
4473                 "%main      = OpFunction %void None %voidf\n"
4474                 "%label     = OpLabel\n"
4475                 "%idval     = OpLoad %uvec3 %id\n"
4476                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4477                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4478                 "%inval     = OpLoad %f32 %inloc\n"
4479                 "%neg       = OpFNegate %f32 %inval\n"
4480                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4481                 "             OpStore %outloc %neg\n"
4482                 "             OpReturn\n"
4483                 "             OpFunctionEnd\n");
4484
4485         cases.push_back(CaseParameter("bool",                   "%bool"));
4486         cases.push_back(CaseParameter("sint32",                 "%i32"));
4487         cases.push_back(CaseParameter("uint32",                 "%u32"));
4488         cases.push_back(CaseParameter("float32",                "%f32"));
4489         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4490         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4491         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4492         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4493         cases.push_back(CaseParameter("array",                  "%uarr100"));
4494         cases.push_back(CaseParameter("struct",                 "%struct"));
4495         cases.push_back(CaseParameter("pointer",                "%pointer"));
4496
4497         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4498
4499         for (size_t ndx = 0; ndx < numElements; ++ndx)
4500                 negativeFloats[ndx] = -positiveFloats[ndx];
4501
4502         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4503         {
4504                 map<string, string>             specializations;
4505                 ComputeShaderSpec               spec;
4506
4507                 specializations["TYPE"] = cases[caseNdx].param;
4508                 spec.assembly = shaderTemplate.specialize(specializations);
4509                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4510                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4511                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4512
4513                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4514         }
4515
4516         return group.release();
4517 }
4518
4519 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4520 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4521 {
4522         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4523         vector<CaseParameter>                   cases;
4524         de::Random                                              rnd                             (deStringHash(group->getName()));
4525         const int                                               numElements             = 100;
4526         vector<float>                                   positiveFloats  (numElements, 0);
4527         vector<float>                                   negativeFloats  (numElements, 0);
4528         const StringTemplate                    shaderTemplate  (
4529                 string(getComputeAsmShaderPreamble()) +
4530
4531                 "OpSource GLSL 430\n"
4532                 "OpName %main           \"main\"\n"
4533                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4534
4535                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4536
4537                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4538
4539                 "%id        = OpVariable %uvec3ptr Input\n"
4540                 "%zero      = OpConstant %i32 0\n"
4541
4542                 "${CONSTANT}\n"
4543
4544                 "%main      = OpFunction %void None %voidf\n"
4545                 "%label     = OpLabel\n"
4546                 "%idval     = OpLoad %uvec3 %id\n"
4547                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4548                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4549                 "%inval     = OpLoad %f32 %inloc\n"
4550                 "%neg       = OpFNegate %f32 %inval\n"
4551                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4552                 "             OpStore %outloc %neg\n"
4553                 "             OpReturn\n"
4554                 "             OpFunctionEnd\n");
4555
4556         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4557                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4558         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4559                                                                                                         "%ten = OpConstant %f32 10.\n"
4560                                                                                                         "%fzero = OpConstant %f32 0.\n"
4561                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4562                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4563         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4564                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4565                                                                                                         "%fzero = OpConstant %f32 0.\n"
4566                                                                                                         "%one = OpConstant %f32 1.\n"
4567                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4568                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4569                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4570                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4571         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4572                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4573                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4574                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4575                                                                                                         "%one = OpConstant %u32 1\n"
4576                                                                                                         "%ten = OpConstant %i32 10\n"
4577                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4578                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4579                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4580
4581         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4582
4583         for (size_t ndx = 0; ndx < numElements; ++ndx)
4584                 negativeFloats[ndx] = -positiveFloats[ndx];
4585
4586         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4587         {
4588                 map<string, string>             specializations;
4589                 ComputeShaderSpec               spec;
4590
4591                 specializations["CONSTANT"] = cases[caseNdx].param;
4592                 spec.assembly = shaderTemplate.specialize(specializations);
4593                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4594                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4595                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4596
4597                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4598         }
4599
4600         return group.release();
4601 }
4602
4603 // Creates a floating point number with the given exponent, and significand
4604 // bits set. It can only create normalized numbers. Only the least significant
4605 // 24 bits of the significand will be examined. The final bit of the
4606 // significand will also be ignored. This allows alignment to be written
4607 // similarly to C99 hex-floats.
4608 // For example if you wanted to write 0x1.7f34p-12 you would call
4609 // constructNormalizedFloat(-12, 0x7f3400)
4610 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4611 {
4612         float f = 1.0f;
4613
4614         for (deInt32 idx = 0; idx < 23; ++idx)
4615         {
4616                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4617                 significand <<= 1;
4618         }
4619
4620         return std::ldexp(f, exponent);
4621 }
4622
4623 // Compare instruction for the OpQuantizeF16 compute exact case.
4624 // Returns true if the output is what is expected from the test case.
4625 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4626 {
4627         if (outputAllocs.size() != 1)
4628                 return false;
4629
4630         // Only size is needed because we cannot compare Nans.
4631         size_t byteSize = expectedOutputs[0].getByteSize();
4632
4633         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4634
4635         if (byteSize != 4*sizeof(float)) {
4636                 return false;
4637         }
4638
4639         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4640                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4641                 return false;
4642         }
4643         outputAsFloat++;
4644
4645         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4646                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4647                 return false;
4648         }
4649         outputAsFloat++;
4650
4651         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4652                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4653                 return false;
4654         }
4655         outputAsFloat++;
4656
4657         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4658                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4659                 return false;
4660         }
4661
4662         return true;
4663 }
4664
4665 // Checks that every output from a test-case is a float NaN.
4666 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4667 {
4668         if (outputAllocs.size() != 1)
4669                 return false;
4670
4671         // Only size is needed because we cannot compare Nans.
4672         size_t byteSize = expectedOutputs[0].getByteSize();
4673
4674         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4675
4676         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4677         {
4678                 if (!deFloatIsNaN(output_as_float[idx]))
4679                 {
4680                         return false;
4681                 }
4682         }
4683
4684         return true;
4685 }
4686
4687 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4688 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4689 {
4690         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4691
4692         const std::string shader (
4693                 string(getComputeAsmShaderPreamble()) +
4694
4695                 "OpSource GLSL 430\n"
4696                 "OpName %main           \"main\"\n"
4697                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4698
4699                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4700
4701                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4702
4703                 "%id        = OpVariable %uvec3ptr Input\n"
4704                 "%zero      = OpConstant %i32 0\n"
4705
4706                 "%main      = OpFunction %void None %voidf\n"
4707                 "%label     = OpLabel\n"
4708                 "%idval     = OpLoad %uvec3 %id\n"
4709                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4710                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4711                 "%inval     = OpLoad %f32 %inloc\n"
4712                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4713                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4714                 "             OpStore %outloc %quant\n"
4715                 "             OpReturn\n"
4716                 "             OpFunctionEnd\n");
4717
4718         {
4719                 ComputeShaderSpec       spec;
4720                 const deUint32          numElements             = 100;
4721                 vector<float>           infinities;
4722                 vector<float>           results;
4723
4724                 infinities.reserve(numElements);
4725                 results.reserve(numElements);
4726
4727                 for (size_t idx = 0; idx < numElements; ++idx)
4728                 {
4729                         switch(idx % 4)
4730                         {
4731                                 case 0:
4732                                         infinities.push_back(std::numeric_limits<float>::infinity());
4733                                         results.push_back(std::numeric_limits<float>::infinity());
4734                                         break;
4735                                 case 1:
4736                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4737                                         results.push_back(-std::numeric_limits<float>::infinity());
4738                                         break;
4739                                 case 2:
4740                                         infinities.push_back(std::ldexp(1.0f, 16));
4741                                         results.push_back(std::numeric_limits<float>::infinity());
4742                                         break;
4743                                 case 3:
4744                                         infinities.push_back(std::ldexp(-1.0f, 32));
4745                                         results.push_back(-std::numeric_limits<float>::infinity());
4746                                         break;
4747                         }
4748                 }
4749
4750                 spec.assembly = shader;
4751                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4752                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4753                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4754
4755                 group->addChild(new SpvAsmComputeShaderCase(
4756                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4757         }
4758
4759         {
4760                 ComputeShaderSpec       spec;
4761                 vector<float>           nans;
4762                 const deUint32          numElements             = 100;
4763
4764                 nans.reserve(numElements);
4765
4766                 for (size_t idx = 0; idx < numElements; ++idx)
4767                 {
4768                         if (idx % 2 == 0)
4769                         {
4770                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4771                         }
4772                         else
4773                         {
4774                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4775                         }
4776                 }
4777
4778                 spec.assembly = shader;
4779                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4780                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4781                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4782                 spec.verifyIO = &compareNan;
4783
4784                 group->addChild(new SpvAsmComputeShaderCase(
4785                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4786         }
4787
4788         {
4789                 ComputeShaderSpec       spec;
4790                 vector<float>           small;
4791                 vector<float>           zeros;
4792                 const deUint32          numElements             = 100;
4793
4794                 small.reserve(numElements);
4795                 zeros.reserve(numElements);
4796
4797                 for (size_t idx = 0; idx < numElements; ++idx)
4798                 {
4799                         switch(idx % 6)
4800                         {
4801                                 case 0:
4802                                         small.push_back(0.f);
4803                                         zeros.push_back(0.f);
4804                                         break;
4805                                 case 1:
4806                                         small.push_back(-0.f);
4807                                         zeros.push_back(-0.f);
4808                                         break;
4809                                 case 2:
4810                                         small.push_back(std::ldexp(1.0f, -16));
4811                                         zeros.push_back(0.f);
4812                                         break;
4813                                 case 3:
4814                                         small.push_back(std::ldexp(-1.0f, -32));
4815                                         zeros.push_back(-0.f);
4816                                         break;
4817                                 case 4:
4818                                         small.push_back(std::ldexp(1.0f, -127));
4819                                         zeros.push_back(0.f);
4820                                         break;
4821                                 case 5:
4822                                         small.push_back(-std::ldexp(1.0f, -128));
4823                                         zeros.push_back(-0.f);
4824                                         break;
4825                         }
4826                 }
4827
4828                 spec.assembly = shader;
4829                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4830                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4831                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4832
4833                 group->addChild(new SpvAsmComputeShaderCase(
4834                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4835         }
4836
4837         {
4838                 ComputeShaderSpec       spec;
4839                 vector<float>           exact;
4840                 const deUint32          numElements             = 200;
4841
4842                 exact.reserve(numElements);
4843
4844                 for (size_t idx = 0; idx < numElements; ++idx)
4845                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4846
4847                 spec.assembly = shader;
4848                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4849                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4850                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4851
4852                 group->addChild(new SpvAsmComputeShaderCase(
4853                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4854         }
4855
4856         {
4857                 ComputeShaderSpec       spec;
4858                 vector<float>           inputs;
4859                 const deUint32          numElements             = 4;
4860
4861                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4862                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4863                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4864                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4865
4866                 spec.assembly = shader;
4867                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4868                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4869                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4870                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4871
4872                 group->addChild(new SpvAsmComputeShaderCase(
4873                         testCtx, "rounded", "Check that are rounded when needed", spec));
4874         }
4875
4876         return group.release();
4877 }
4878
4879 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4880 {
4881         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4882
4883         const std::string shader (
4884                 string(getComputeAsmShaderPreamble()) +
4885
4886                 "OpName %main           \"main\"\n"
4887                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4888
4889                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4890
4891                 "OpDecorate %sc_0  SpecId 0\n"
4892                 "OpDecorate %sc_1  SpecId 1\n"
4893                 "OpDecorate %sc_2  SpecId 2\n"
4894                 "OpDecorate %sc_3  SpecId 3\n"
4895                 "OpDecorate %sc_4  SpecId 4\n"
4896                 "OpDecorate %sc_5  SpecId 5\n"
4897
4898                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4899
4900                 "%id        = OpVariable %uvec3ptr Input\n"
4901                 "%zero      = OpConstant %i32 0\n"
4902                 "%c_u32_6   = OpConstant %u32 6\n"
4903
4904                 "%sc_0      = OpSpecConstant %f32 0.\n"
4905                 "%sc_1      = OpSpecConstant %f32 0.\n"
4906                 "%sc_2      = OpSpecConstant %f32 0.\n"
4907                 "%sc_3      = OpSpecConstant %f32 0.\n"
4908                 "%sc_4      = OpSpecConstant %f32 0.\n"
4909                 "%sc_5      = OpSpecConstant %f32 0.\n"
4910
4911                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4912                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4913                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4914                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4915                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4916                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4917
4918                 "%main      = OpFunction %void None %voidf\n"
4919                 "%label     = OpLabel\n"
4920                 "%idval     = OpLoad %uvec3 %id\n"
4921                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4922                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4923                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4924                 "            OpSelectionMerge %exit None\n"
4925                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4926
4927                 "%case0     = OpLabel\n"
4928                 "             OpStore %outloc %sc_0_quant\n"
4929                 "             OpBranch %exit\n"
4930
4931                 "%case1     = OpLabel\n"
4932                 "             OpStore %outloc %sc_1_quant\n"
4933                 "             OpBranch %exit\n"
4934
4935                 "%case2     = OpLabel\n"
4936                 "             OpStore %outloc %sc_2_quant\n"
4937                 "             OpBranch %exit\n"
4938
4939                 "%case3     = OpLabel\n"
4940                 "             OpStore %outloc %sc_3_quant\n"
4941                 "             OpBranch %exit\n"
4942
4943                 "%case4     = OpLabel\n"
4944                 "             OpStore %outloc %sc_4_quant\n"
4945                 "             OpBranch %exit\n"
4946
4947                 "%case5     = OpLabel\n"
4948                 "             OpStore %outloc %sc_5_quant\n"
4949                 "             OpBranch %exit\n"
4950
4951                 "%exit      = OpLabel\n"
4952                 "             OpReturn\n"
4953
4954                 "             OpFunctionEnd\n");
4955
4956         {
4957                 ComputeShaderSpec       spec;
4958                 const deUint8           numCases        = 4;
4959                 vector<float>           inputs          (numCases, 0.f);
4960                 vector<float>           outputs;
4961
4962                 spec.assembly           = shader;
4963                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4964
4965                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4966                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4967                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4968                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4969
4970                 outputs.push_back(std::numeric_limits<float>::infinity());
4971                 outputs.push_back(-std::numeric_limits<float>::infinity());
4972                 outputs.push_back(std::numeric_limits<float>::infinity());
4973                 outputs.push_back(-std::numeric_limits<float>::infinity());
4974
4975                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4976                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4977
4978                 group->addChild(new SpvAsmComputeShaderCase(
4979                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4980         }
4981
4982         {
4983                 ComputeShaderSpec       spec;
4984                 const deUint8           numCases        = 2;
4985                 vector<float>           inputs          (numCases, 0.f);
4986                 vector<float>           outputs;
4987
4988                 spec.assembly           = shader;
4989                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4990                 spec.verifyIO           = &compareNan;
4991
4992                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4993                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4994
4995                 for (deUint8 idx = 0; idx < numCases; ++idx)
4996                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4997
4998                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4999                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5000
5001                 group->addChild(new SpvAsmComputeShaderCase(
5002                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
5003         }
5004
5005         {
5006                 ComputeShaderSpec       spec;
5007                 const deUint8           numCases        = 6;
5008                 vector<float>           inputs          (numCases, 0.f);
5009                 vector<float>           outputs;
5010
5011                 spec.assembly           = shader;
5012                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5013
5014                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
5015                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
5016                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
5017                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
5018                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
5019                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
5020
5021                 outputs.push_back(0.f);
5022                 outputs.push_back(-0.f);
5023                 outputs.push_back(0.f);
5024                 outputs.push_back(-0.f);
5025                 outputs.push_back(0.f);
5026                 outputs.push_back(-0.f);
5027
5028                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5029                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5030
5031                 group->addChild(new SpvAsmComputeShaderCase(
5032                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
5033         }
5034
5035         {
5036                 ComputeShaderSpec       spec;
5037                 const deUint8           numCases        = 6;
5038                 vector<float>           inputs          (numCases, 0.f);
5039                 vector<float>           outputs;
5040
5041                 spec.assembly           = shader;
5042                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5043
5044                 for (deUint8 idx = 0; idx < 6; ++idx)
5045                 {
5046                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
5047                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
5048                         outputs.push_back(f);
5049                 }
5050
5051                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5052                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5053
5054                 group->addChild(new SpvAsmComputeShaderCase(
5055                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
5056         }
5057
5058         {
5059                 ComputeShaderSpec       spec;
5060                 const deUint8           numCases        = 4;
5061                 vector<float>           inputs          (numCases, 0.f);
5062                 vector<float>           outputs;
5063
5064                 spec.assembly           = shader;
5065                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5066                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
5067
5068                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
5069                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
5070                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
5071                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
5072
5073                 for (deUint8 idx = 0; idx < numCases; ++idx)
5074                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
5075
5076                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5077                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5078
5079                 group->addChild(new SpvAsmComputeShaderCase(
5080                         testCtx, "rounded", "Check that are rounded when needed", spec));
5081         }
5082
5083         return group.release();
5084 }
5085
5086 // Checks that constant null/composite values can be used in computation.
5087 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
5088 {
5089         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
5090         ComputeShaderSpec                               spec;
5091         de::Random                                              rnd                             (deStringHash(group->getName()));
5092         const int                                               numElements             = 100;
5093         vector<float>                                   positiveFloats  (numElements, 0);
5094         vector<float>                                   negativeFloats  (numElements, 0);
5095
5096         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5097
5098         for (size_t ndx = 0; ndx < numElements; ++ndx)
5099                 negativeFloats[ndx] = -positiveFloats[ndx];
5100
5101         spec.assembly =
5102                 "OpCapability Shader\n"
5103                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
5104                 "OpMemoryModel Logical GLSL450\n"
5105                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5106                 "OpExecutionMode %main LocalSize 1 1 1\n"
5107
5108                 "OpSource GLSL 430\n"
5109                 "OpName %main           \"main\"\n"
5110                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5111
5112                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5113
5114                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5115
5116                 "%fmat      = OpTypeMatrix %fvec3 3\n"
5117                 "%ten       = OpConstant %u32 10\n"
5118                 "%f32arr10  = OpTypeArray %f32 %ten\n"
5119                 "%fst       = OpTypeStruct %f32 %f32\n"
5120
5121                 + string(getComputeAsmInputOutputBuffer()) +
5122
5123                 "%id        = OpVariable %uvec3ptr Input\n"
5124                 "%zero      = OpConstant %i32 0\n"
5125
5126                 // Create a bunch of null values
5127                 "%unull     = OpConstantNull %u32\n"
5128                 "%fnull     = OpConstantNull %f32\n"
5129                 "%vnull     = OpConstantNull %fvec3\n"
5130                 "%mnull     = OpConstantNull %fmat\n"
5131                 "%anull     = OpConstantNull %f32arr10\n"
5132                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5133
5134                 "%main      = OpFunction %void None %voidf\n"
5135                 "%label     = OpLabel\n"
5136                 "%idval     = OpLoad %uvec3 %id\n"
5137                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5138                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5139                 "%inval     = OpLoad %f32 %inloc\n"
5140                 "%neg       = OpFNegate %f32 %inval\n"
5141
5142                 // Get the abs() of (a certain element of) those null values
5143                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5144                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5145                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5146                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5147                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5148                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5149                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5150                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5151                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5152                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5153                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5154
5155                 // Add them all
5156                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5157                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5158                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5159                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5160                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5161                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5162
5163                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5164                 "             OpStore %outloc %final\n" // write to output
5165                 "             OpReturn\n"
5166                 "             OpFunctionEnd\n";
5167         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5168         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5169         spec.numWorkGroups = IVec3(numElements, 1, 1);
5170
5171         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5172
5173         return group.release();
5174 }
5175
5176 // Assembly code used for testing loop control is based on GLSL source code:
5177 // #version 430
5178 //
5179 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5180 //   float elements[];
5181 // } input_data;
5182 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5183 //   float elements[];
5184 // } output_data;
5185 //
5186 // void main() {
5187 //   uint x = gl_GlobalInvocationID.x;
5188 //   output_data.elements[x] = input_data.elements[x];
5189 //   for (uint i = 0; i < 4; ++i)
5190 //     output_data.elements[x] += 1.f;
5191 // }
5192 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5193 {
5194         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5195         vector<CaseParameter>                   cases;
5196         de::Random                                              rnd                             (deStringHash(group->getName()));
5197         const int                                               numElements             = 100;
5198         vector<float>                                   inputFloats             (numElements, 0);
5199         vector<float>                                   outputFloats    (numElements, 0);
5200         const StringTemplate                    shaderTemplate  (
5201                 string(getComputeAsmShaderPreamble()) +
5202
5203                 "OpSource GLSL 430\n"
5204                 "OpName %main \"main\"\n"
5205                 "OpName %id \"gl_GlobalInvocationID\"\n"
5206
5207                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5208
5209                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5210
5211                 "%u32ptr      = OpTypePointer Function %u32\n"
5212
5213                 "%id          = OpVariable %uvec3ptr Input\n"
5214                 "%zero        = OpConstant %i32 0\n"
5215                 "%uzero       = OpConstant %u32 0\n"
5216                 "%one         = OpConstant %i32 1\n"
5217                 "%constf1     = OpConstant %f32 1.0\n"
5218                 "%four        = OpConstant %u32 4\n"
5219
5220                 "%main        = OpFunction %void None %voidf\n"
5221                 "%entry       = OpLabel\n"
5222                 "%i           = OpVariable %u32ptr Function\n"
5223                 "               OpStore %i %uzero\n"
5224
5225                 "%idval       = OpLoad %uvec3 %id\n"
5226                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5227                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5228                 "%inval       = OpLoad %f32 %inloc\n"
5229                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5230                 "               OpStore %outloc %inval\n"
5231                 "               OpBranch %loop_entry\n"
5232
5233                 "%loop_entry  = OpLabel\n"
5234                 "%i_val       = OpLoad %u32 %i\n"
5235                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5236                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5237                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5238                 "%loop_body   = OpLabel\n"
5239                 "%outval      = OpLoad %f32 %outloc\n"
5240                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5241                 "               OpStore %outloc %addf1\n"
5242                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5243                 "               OpStore %i %new_i\n"
5244                 "               OpBranch %loop_entry\n"
5245                 "%loop_merge  = OpLabel\n"
5246                 "               OpReturn\n"
5247                 "               OpFunctionEnd\n");
5248
5249         cases.push_back(CaseParameter("none",                           "None"));
5250         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5251         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5252
5253         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5254
5255         for (size_t ndx = 0; ndx < numElements; ++ndx)
5256                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5257
5258         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5259         {
5260                 map<string, string>             specializations;
5261                 ComputeShaderSpec               spec;
5262
5263                 specializations["CONTROL"] = cases[caseNdx].param;
5264                 spec.assembly = shaderTemplate.specialize(specializations);
5265                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5266                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5267                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5268
5269                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5270         }
5271
5272         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5273         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5274
5275         return group.release();
5276 }
5277
5278 // Assembly code used for testing selection control is based on GLSL source code:
5279 // #version 430
5280 //
5281 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5282 //   float elements[];
5283 // } input_data;
5284 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5285 //   float elements[];
5286 // } output_data;
5287 //
5288 // void main() {
5289 //   uint x = gl_GlobalInvocationID.x;
5290 //   float val = input_data.elements[x];
5291 //   if (val > 10.f)
5292 //     output_data.elements[x] = val + 1.f;
5293 //   else
5294 //     output_data.elements[x] = val - 1.f;
5295 // }
5296 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5297 {
5298         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5299         vector<CaseParameter>                   cases;
5300         de::Random                                              rnd                             (deStringHash(group->getName()));
5301         const int                                               numElements             = 100;
5302         vector<float>                                   inputFloats             (numElements, 0);
5303         vector<float>                                   outputFloats    (numElements, 0);
5304         const StringTemplate                    shaderTemplate  (
5305                 string(getComputeAsmShaderPreamble()) +
5306
5307                 "OpSource GLSL 430\n"
5308                 "OpName %main \"main\"\n"
5309                 "OpName %id \"gl_GlobalInvocationID\"\n"
5310
5311                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5312
5313                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5314
5315                 "%id       = OpVariable %uvec3ptr Input\n"
5316                 "%zero     = OpConstant %i32 0\n"
5317                 "%constf1  = OpConstant %f32 1.0\n"
5318                 "%constf10 = OpConstant %f32 10.0\n"
5319
5320                 "%main     = OpFunction %void None %voidf\n"
5321                 "%entry    = OpLabel\n"
5322                 "%idval    = OpLoad %uvec3 %id\n"
5323                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5324                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5325                 "%inval    = OpLoad %f32 %inloc\n"
5326                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5327                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5328
5329                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5330                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5331                 "%if_true  = OpLabel\n"
5332                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5333                 "            OpStore %outloc %addf1\n"
5334                 "            OpBranch %if_end\n"
5335                 "%if_false = OpLabel\n"
5336                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5337                 "            OpStore %outloc %subf1\n"
5338                 "            OpBranch %if_end\n"
5339                 "%if_end   = OpLabel\n"
5340                 "            OpReturn\n"
5341                 "            OpFunctionEnd\n");
5342
5343         cases.push_back(CaseParameter("none",                                   "None"));
5344         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5345         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5346         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5347
5348         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5349
5350         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5351         floorAll(inputFloats);
5352
5353         for (size_t ndx = 0; ndx < numElements; ++ndx)
5354                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5355
5356         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5357         {
5358                 map<string, string>             specializations;
5359                 ComputeShaderSpec               spec;
5360
5361                 specializations["CONTROL"] = cases[caseNdx].param;
5362                 spec.assembly = shaderTemplate.specialize(specializations);
5363                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5364                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5365                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5366
5367                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5368         }
5369
5370         return group.release();
5371 }
5372
5373 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5374 {
5375         // Generate a long name.
5376         std::string longname;
5377         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5378
5379         // Some bad names, abusing utf-8 encoding. This may also cause problems
5380         // with the logs.
5381         // 1. Various illegal code points in utf-8
5382         std::string utf8illegal =
5383                 "Illegal bytes in UTF-8: "
5384                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5385                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5386
5387         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5388         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5389
5390         // 3. Some overlong encodings
5391         std::string utf8overlong =
5392                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5393                 "\xf0\x8f\xbf\xbf";
5394
5395         // 4. Internet "zalgo" meme "bleeding text"
5396         std::string utf8zalgo =
5397                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5398                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5399                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5400                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5401                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5402                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5403                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5404                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5405                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5406                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5407                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5408                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5409                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5410                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5411                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5412                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5413                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5414                 "\x93\xcd\x96\xcc\x97\xff";
5415
5416         // General name abuses
5417         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5418         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5419         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5420         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5421         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5422
5423         // GL keywords
5424         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5425         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5426         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5427         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5428         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5429         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5430         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5431         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5432         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5433         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5434         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5435         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5436         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5437         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5438         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5439         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5440         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5441         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5442         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5443         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5444         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5445 }
5446
5447 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5448 {
5449         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5450         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5451         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5452         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5453         vector<CaseParameter>                   cases;
5454         vector<CaseParameter>                   abuseCases;
5455         vector<string>                                  testFunc;
5456         de::Random                                              rnd                             (deStringHash(group->getName()));
5457         const int                                               numElements             = 128;
5458         vector<float>                                   inputFloats             (numElements, 0);
5459         vector<float>                                   outputFloats    (numElements, 0);
5460
5461         getOpNameAbuseCases(abuseCases);
5462
5463         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5464
5465         for(size_t ndx = 0; ndx < numElements; ++ndx)
5466                 outputFloats[ndx] = -inputFloats[ndx];
5467
5468         const string commonShaderHeader =
5469                 "OpCapability Shader\n"
5470                 "OpMemoryModel Logical GLSL450\n"
5471                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5472                 "OpExecutionMode %main LocalSize 1 1 1\n";
5473
5474         const string commonShaderFooter =
5475                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5476
5477                 + string(getComputeAsmInputOutputBufferTraits())
5478                 + string(getComputeAsmCommonTypes())
5479                 + string(getComputeAsmInputOutputBuffer()) +
5480
5481                 "%id        = OpVariable %uvec3ptr Input\n"
5482                 "%zero      = OpConstant %i32 0\n"
5483
5484                 "%func      = OpFunction %void None %voidf\n"
5485                 "%5         = OpLabel\n"
5486                 "             OpReturn\n"
5487                 "             OpFunctionEnd\n"
5488
5489                 "%main      = OpFunction %void None %voidf\n"
5490                 "%entry     = OpLabel\n"
5491                 "%7         = OpFunctionCall %void %func\n"
5492
5493                 "%idval     = OpLoad %uvec3 %id\n"
5494                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5495
5496                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5497                 "%inval     = OpLoad %f32 %inloc\n"
5498                 "%neg       = OpFNegate %f32 %inval\n"
5499                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5500                 "             OpStore %outloc %neg\n"
5501
5502                 "             OpReturn\n"
5503                 "             OpFunctionEnd\n";
5504
5505         const StringTemplate shaderTemplate (
5506                 "OpCapability Shader\n"
5507                 "OpMemoryModel Logical GLSL450\n"
5508                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5509                 "OpExecutionMode %main LocalSize 1 1 1\n"
5510                 "OpName %${ID} \"${NAME}\"\n" +
5511                 commonShaderFooter);
5512
5513         const std::string multipleNames =
5514                 commonShaderHeader +
5515                 "OpName %main \"to_be\"\n"
5516                 "OpName %id   \"or_not\"\n"
5517                 "OpName %main \"to_be\"\n"
5518                 "OpName %main \"makes_no\"\n"
5519                 "OpName %func \"difference\"\n"
5520                 "OpName %5    \"to_me\"\n" +
5521                 commonShaderFooter;
5522
5523         {
5524                 ComputeShaderSpec       spec;
5525
5526                 spec.assembly           = multipleNames;
5527                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5528                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5529                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5530
5531                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5532         }
5533
5534         const std::string everythingNamed =
5535                 commonShaderHeader +
5536                 "OpName %main   \"name1\"\n"
5537                 "OpName %id     \"name2\"\n"
5538                 "OpName %zero   \"name3\"\n"
5539                 "OpName %entry  \"name4\"\n"
5540                 "OpName %func   \"name5\"\n"
5541                 "OpName %5      \"name6\"\n"
5542                 "OpName %7      \"name7\"\n"
5543                 "OpName %idval  \"name8\"\n"
5544                 "OpName %inloc  \"name9\"\n"
5545                 "OpName %inval  \"name10\"\n"
5546                 "OpName %neg    \"name11\"\n"
5547                 "OpName %outloc \"name12\"\n"+
5548                 commonShaderFooter;
5549         {
5550                 ComputeShaderSpec       spec;
5551
5552                 spec.assembly           = everythingNamed;
5553                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5554                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5555                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5556
5557                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5558         }
5559
5560         const std::string everythingNamedTheSame =
5561                 commonShaderHeader +
5562                 "OpName %main   \"the_same\"\n"
5563                 "OpName %id     \"the_same\"\n"
5564                 "OpName %zero   \"the_same\"\n"
5565                 "OpName %entry  \"the_same\"\n"
5566                 "OpName %func   \"the_same\"\n"
5567                 "OpName %5      \"the_same\"\n"
5568                 "OpName %7      \"the_same\"\n"
5569                 "OpName %idval  \"the_same\"\n"
5570                 "OpName %inloc  \"the_same\"\n"
5571                 "OpName %inval  \"the_same\"\n"
5572                 "OpName %neg    \"the_same\"\n"
5573                 "OpName %outloc \"the_same\"\n"+
5574                 commonShaderFooter;
5575         {
5576                 ComputeShaderSpec       spec;
5577
5578                 spec.assembly           = everythingNamedTheSame;
5579                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5580                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5581                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5582
5583                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5584         }
5585
5586         // main_is_...
5587         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5588         {
5589                 map<string, string>     specializations;
5590                 ComputeShaderSpec       spec;
5591
5592                 specializations["ENTRY"]        = "main";
5593                 specializations["ID"]           = "main";
5594                 specializations["NAME"]         = abuseCases[ndx].param;
5595                 spec.assembly                           = shaderTemplate.specialize(specializations);
5596                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5597                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5598                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5599
5600                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5601         }
5602
5603         // x_is_....
5604         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5605         {
5606                 map<string, string>     specializations;
5607                 ComputeShaderSpec       spec;
5608
5609                 specializations["ENTRY"]        = "main";
5610                 specializations["ID"]           = "x";
5611                 specializations["NAME"]         = abuseCases[ndx].param;
5612                 spec.assembly                           = shaderTemplate.specialize(specializations);
5613                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5614                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5615                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5616
5617                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5618         }
5619
5620         cases.push_back(CaseParameter("_is_main", "main"));
5621         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5622         testFunc.push_back("main");
5623         testFunc.push_back("func");
5624
5625         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5626         {
5627                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5628                 {
5629                         map<string, string>     specializations;
5630                         ComputeShaderSpec       spec;
5631
5632                         specializations["ENTRY"]        = "main";
5633                         specializations["ID"]           = testFunc[fNdx];
5634                         specializations["NAME"]         = cases[ndx].param;
5635                         spec.assembly                           = shaderTemplate.specialize(specializations);
5636                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5637                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5638                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5639
5640                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5641                 }
5642         }
5643
5644         cases.push_back(CaseParameter("_is_entry", "rdc"));
5645
5646         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5647         {
5648                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5649                 {
5650                         map<string, string>     specializations;
5651                         ComputeShaderSpec       spec;
5652
5653                         specializations["ENTRY"]        = "rdc";
5654                         specializations["ID"]           = testFunc[fNdx];
5655                         specializations["NAME"]         = cases[ndx].param;
5656                         spec.assembly                           = shaderTemplate.specialize(specializations);
5657                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5658                         spec.entryPoint                         = "rdc";
5659                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5660                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5661
5662                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5663                 }
5664         }
5665
5666         group->addChild(entryMainGroup.release());
5667         group->addChild(entryNotGroup.release());
5668         group->addChild(abuseGroup.release());
5669
5670         return group.release();
5671 }
5672
5673 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5674 {
5675         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5676         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5677         vector<CaseParameter>                   abuseCases;
5678         vector<string>                                  testFunc;
5679         de::Random                                              rnd(deStringHash(group->getName()));
5680         const int                                               numElements = 128;
5681         vector<float>                                   inputFloats(numElements, 0);
5682         vector<float>                                   outputFloats(numElements, 0);
5683
5684         getOpNameAbuseCases(abuseCases);
5685
5686         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5687
5688         for (size_t ndx = 0; ndx < numElements; ++ndx)
5689                 outputFloats[ndx] = -inputFloats[ndx];
5690
5691         const string commonShaderHeader =
5692                 "OpCapability Shader\n"
5693                 "OpMemoryModel Logical GLSL450\n"
5694                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5695                 "OpExecutionMode %main LocalSize 1 1 1\n";
5696
5697         const string commonShaderFooter =
5698                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5699
5700                 + string(getComputeAsmInputOutputBufferTraits())
5701                 + string(getComputeAsmCommonTypes())
5702                 + string(getComputeAsmInputOutputBuffer()) +
5703
5704                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5705
5706                 "%id        = OpVariable %uvec3ptr Input\n"
5707                 "%zero      = OpConstant %i32 0\n"
5708
5709                 "%main      = OpFunction %void None %voidf\n"
5710                 "%entry     = OpLabel\n"
5711
5712                 "%idval     = OpLoad %uvec3 %id\n"
5713                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5714
5715                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5716                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5717
5718                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5719                 "%inval     = OpLoad %f32 %inloc\n"
5720                 "%neg       = OpFNegate %f32 %inval\n"
5721                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5722                 "             OpStore %outloc %neg\n"
5723
5724                 "             OpReturn\n"
5725                 "             OpFunctionEnd\n";
5726
5727         const StringTemplate shaderTemplate(
5728                 commonShaderHeader +
5729                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5730                 commonShaderFooter);
5731
5732         const std::string multipleNames =
5733                 commonShaderHeader +
5734                 "OpMemberName %u3str 0 \"to_be\"\n"
5735                 "OpMemberName %u3str 1 \"or_not\"\n"
5736                 "OpMemberName %u3str 0 \"to_be\"\n"
5737                 "OpMemberName %u3str 2 \"makes_no\"\n"
5738                 "OpMemberName %u3str 0 \"difference\"\n"
5739                 "OpMemberName %u3str 0 \"to_me\"\n" +
5740                 commonShaderFooter;
5741         {
5742                 ComputeShaderSpec       spec;
5743
5744                 spec.assembly = multipleNames;
5745                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5746                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5747                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5748
5749                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5750         }
5751
5752         const std::string everythingNamedTheSame =
5753                 commonShaderHeader +
5754                 "OpMemberName %u3str 0 \"the_same\"\n"
5755                 "OpMemberName %u3str 1 \"the_same\"\n"
5756                 "OpMemberName %u3str 2 \"the_same\"\n" +
5757                 commonShaderFooter;
5758
5759         {
5760                 ComputeShaderSpec       spec;
5761
5762                 spec.assembly = everythingNamedTheSame;
5763                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5764                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5765                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5766
5767                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5768         }
5769
5770         // u3str_x_is_....
5771         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5772         {
5773                 map<string, string>     specializations;
5774                 ComputeShaderSpec       spec;
5775
5776                 specializations["NAME"] = abuseCases[ndx].param;
5777                 spec.assembly = shaderTemplate.specialize(specializations);
5778                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5779                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5780                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5781
5782                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5783         }
5784
5785         group->addChild(abuseGroup.release());
5786
5787         return group.release();
5788 }
5789
5790 // Assembly code used for testing function control is based on GLSL source code:
5791 //
5792 // #version 430
5793 //
5794 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5795 //   float elements[];
5796 // } input_data;
5797 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5798 //   float elements[];
5799 // } output_data;
5800 //
5801 // float const10() { return 10.f; }
5802 //
5803 // void main() {
5804 //   uint x = gl_GlobalInvocationID.x;
5805 //   output_data.elements[x] = input_data.elements[x] + const10();
5806 // }
5807 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5808 {
5809         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5810         vector<CaseParameter>                   cases;
5811         de::Random                                              rnd                             (deStringHash(group->getName()));
5812         const int                                               numElements             = 100;
5813         vector<float>                                   inputFloats             (numElements, 0);
5814         vector<float>                                   outputFloats    (numElements, 0);
5815         const StringTemplate                    shaderTemplate  (
5816                 string(getComputeAsmShaderPreamble()) +
5817
5818                 "OpSource GLSL 430\n"
5819                 "OpName %main \"main\"\n"
5820                 "OpName %func_const10 \"const10(\"\n"
5821                 "OpName %id \"gl_GlobalInvocationID\"\n"
5822
5823                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5824
5825                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5826
5827                 "%f32f = OpTypeFunction %f32\n"
5828                 "%id = OpVariable %uvec3ptr Input\n"
5829                 "%zero = OpConstant %i32 0\n"
5830                 "%constf10 = OpConstant %f32 10.0\n"
5831
5832                 "%main         = OpFunction %void None %voidf\n"
5833                 "%entry        = OpLabel\n"
5834                 "%idval        = OpLoad %uvec3 %id\n"
5835                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5836                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5837                 "%inval        = OpLoad %f32 %inloc\n"
5838                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5839                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5840                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5841                 "                OpStore %outloc %fadd\n"
5842                 "                OpReturn\n"
5843                 "                OpFunctionEnd\n"
5844
5845                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5846                 "%label        = OpLabel\n"
5847                 "                OpReturnValue %constf10\n"
5848                 "                OpFunctionEnd\n");
5849
5850         cases.push_back(CaseParameter("none",                                           "None"));
5851         cases.push_back(CaseParameter("inline",                                         "Inline"));
5852         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5853         cases.push_back(CaseParameter("pure",                                           "Pure"));
5854         cases.push_back(CaseParameter("const",                                          "Const"));
5855         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5856         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5857         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5858         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5859
5860         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5861
5862         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5863         floorAll(inputFloats);
5864
5865         for (size_t ndx = 0; ndx < numElements; ++ndx)
5866                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5867
5868         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5869         {
5870                 map<string, string>             specializations;
5871                 ComputeShaderSpec               spec;
5872
5873                 specializations["CONTROL"] = cases[caseNdx].param;
5874                 spec.assembly = shaderTemplate.specialize(specializations);
5875                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5876                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5877                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5878
5879                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5880         }
5881
5882         return group.release();
5883 }
5884
5885 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5886 {
5887         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5888         vector<CaseParameter>                   cases;
5889         de::Random                                              rnd                             (deStringHash(group->getName()));
5890         const int                                               numElements             = 100;
5891         vector<float>                                   inputFloats             (numElements, 0);
5892         vector<float>                                   outputFloats    (numElements, 0);
5893         const StringTemplate                    shaderTemplate  (
5894                 string(getComputeAsmShaderPreamble()) +
5895
5896                 "OpSource GLSL 430\n"
5897                 "OpName %main           \"main\"\n"
5898                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5899
5900                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5901
5902                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5903
5904                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5905
5906                 "%id        = OpVariable %uvec3ptr Input\n"
5907                 "%zero      = OpConstant %i32 0\n"
5908                 "%four      = OpConstant %i32 4\n"
5909
5910                 "%main      = OpFunction %void None %voidf\n"
5911                 "%label     = OpLabel\n"
5912                 "%copy      = OpVariable %f32ptr_f Function\n"
5913                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5914                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5915                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5916                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5917                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5918                 "%val1      = OpLoad %f32 %copy\n"
5919                 "%val2      = OpLoad %f32 %inloc\n"
5920                 "%add       = OpFAdd %f32 %val1 %val2\n"
5921                 "             OpStore %outloc %add ${ACCESS}\n"
5922                 "             OpReturn\n"
5923                 "             OpFunctionEnd\n");
5924
5925         cases.push_back(CaseParameter("null",                                   ""));
5926         cases.push_back(CaseParameter("none",                                   "None"));
5927         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5928         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5929         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5930         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5931         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5932
5933         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5934
5935         for (size_t ndx = 0; ndx < numElements; ++ndx)
5936                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5937
5938         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5939         {
5940                 map<string, string>             specializations;
5941                 ComputeShaderSpec               spec;
5942
5943                 specializations["ACCESS"] = cases[caseNdx].param;
5944                 spec.assembly = shaderTemplate.specialize(specializations);
5945                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5946                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5947                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5948
5949                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5950         }
5951
5952         return group.release();
5953 }
5954
5955 // Checks that we can get undefined values for various types, without exercising a computation with it.
5956 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5957 {
5958         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5959         vector<CaseParameter>                   cases;
5960         de::Random                                              rnd                             (deStringHash(group->getName()));
5961         const int                                               numElements             = 100;
5962         vector<float>                                   positiveFloats  (numElements, 0);
5963         vector<float>                                   negativeFloats  (numElements, 0);
5964         const StringTemplate                    shaderTemplate  (
5965                 string(getComputeAsmShaderPreamble()) +
5966
5967                 "OpSource GLSL 430\n"
5968                 "OpName %main           \"main\"\n"
5969                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5970
5971                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5972
5973                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5974                 "%uvec2     = OpTypeVector %u32 2\n"
5975                 "%fvec4     = OpTypeVector %f32 4\n"
5976                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5977                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5978                 "%sampler   = OpTypeSampler\n"
5979                 "%simage    = OpTypeSampledImage %image\n"
5980                 "%const100  = OpConstant %u32 100\n"
5981                 "%uarr100   = OpTypeArray %i32 %const100\n"
5982                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5983                 "%pointer   = OpTypePointer Function %i32\n"
5984                 + string(getComputeAsmInputOutputBuffer()) +
5985
5986                 "%id        = OpVariable %uvec3ptr Input\n"
5987                 "%zero      = OpConstant %i32 0\n"
5988
5989                 "%main      = OpFunction %void None %voidf\n"
5990                 "%label     = OpLabel\n"
5991
5992                 "%undef     = OpUndef ${TYPE}\n"
5993
5994                 "%idval     = OpLoad %uvec3 %id\n"
5995                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5996
5997                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5998                 "%inval     = OpLoad %f32 %inloc\n"
5999                 "%neg       = OpFNegate %f32 %inval\n"
6000                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6001                 "             OpStore %outloc %neg\n"
6002                 "             OpReturn\n"
6003                 "             OpFunctionEnd\n");
6004
6005         cases.push_back(CaseParameter("bool",                   "%bool"));
6006         cases.push_back(CaseParameter("sint32",                 "%i32"));
6007         cases.push_back(CaseParameter("uint32",                 "%u32"));
6008         cases.push_back(CaseParameter("float32",                "%f32"));
6009         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
6010         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
6011         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
6012         cases.push_back(CaseParameter("image",                  "%image"));
6013         cases.push_back(CaseParameter("sampler",                "%sampler"));
6014         cases.push_back(CaseParameter("sampledimage",   "%simage"));
6015         cases.push_back(CaseParameter("array",                  "%uarr100"));
6016         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
6017         cases.push_back(CaseParameter("struct",                 "%struct"));
6018         cases.push_back(CaseParameter("pointer",                "%pointer"));
6019
6020         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6021
6022         for (size_t ndx = 0; ndx < numElements; ++ndx)
6023                 negativeFloats[ndx] = -positiveFloats[ndx];
6024
6025         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6026         {
6027                 map<string, string>             specializations;
6028                 ComputeShaderSpec               spec;
6029
6030                 specializations["TYPE"] = cases[caseNdx].param;
6031                 spec.assembly = shaderTemplate.specialize(specializations);
6032                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6033                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6034                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6035
6036                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6037         }
6038
6039                 return group.release();
6040 }
6041
6042 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
6043 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
6044 {
6045         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
6046         vector<CaseParameter>                   cases;
6047         de::Random                                              rnd                             (deStringHash(group->getName()));
6048         const int                                               numElements             = 100;
6049         vector<float>                                   positiveFloats  (numElements, 0);
6050         vector<float>                                   negativeFloats  (numElements, 0);
6051         const StringTemplate                    shaderTemplate  (
6052                 "OpCapability Shader\n"
6053                 "OpCapability Float16\n"
6054                 "OpMemoryModel Logical GLSL450\n"
6055                 "OpEntryPoint GLCompute %main \"main\" %id\n"
6056                 "OpExecutionMode %main LocalSize 1 1 1\n"
6057                 "OpSource GLSL 430\n"
6058                 "OpName %main           \"main\"\n"
6059                 "OpName %id             \"gl_GlobalInvocationID\"\n"
6060
6061                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
6062
6063                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
6064
6065                 "%id        = OpVariable %uvec3ptr Input\n"
6066                 "%zero      = OpConstant %i32 0\n"
6067                 "%f16       = OpTypeFloat 16\n"
6068                 "%c_f16_0   = OpConstant %f16 0.0\n"
6069                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
6070                 "%c_f16_1   = OpConstant %f16 1.0\n"
6071                 "%v2f16     = OpTypeVector %f16 2\n"
6072                 "%v3f16     = OpTypeVector %f16 3\n"
6073                 "%v4f16     = OpTypeVector %f16 4\n"
6074
6075                 "${CONSTANT}\n"
6076
6077                 "%main      = OpFunction %void None %voidf\n"
6078                 "%label     = OpLabel\n"
6079                 "%idval     = OpLoad %uvec3 %id\n"
6080                 "%x         = OpCompositeExtract %u32 %idval 0\n"
6081                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
6082                 "%inval     = OpLoad %f32 %inloc\n"
6083                 "%neg       = OpFNegate %f32 %inval\n"
6084                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6085                 "             OpStore %outloc %neg\n"
6086                 "             OpReturn\n"
6087                 "             OpFunctionEnd\n");
6088
6089
6090         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
6091         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
6092                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6093                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
6094         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
6095                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
6096                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6097                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
6098                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
6099         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
6100                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
6101                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
6102                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
6103                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
6104                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
6105
6106         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6107
6108         for (size_t ndx = 0; ndx < numElements; ++ndx)
6109                 negativeFloats[ndx] = -positiveFloats[ndx];
6110
6111         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6112         {
6113                 map<string, string>             specializations;
6114                 ComputeShaderSpec               spec;
6115
6116                 specializations["CONSTANT"] = cases[caseNdx].param;
6117                 spec.assembly = shaderTemplate.specialize(specializations);
6118                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6119                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6120                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6121
6122                 spec.extensions.push_back("VK_KHR_16bit_storage");
6123                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6124
6125                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6126                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6127
6128                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6129         }
6130
6131         return group.release();
6132 }
6133
6134 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6135 {
6136         const size_t            inDataLength    = inData.size();
6137         vector<deFloat16>       result;
6138
6139         result.reserve(inDataLength * inDataLength);
6140
6141         if (argNo == 0)
6142         {
6143                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6144                         result.insert(result.end(), inData.begin(), inData.end());
6145         }
6146
6147         if (argNo == 1)
6148         {
6149                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6150                 {
6151                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6152
6153                         result.insert(result.end(), tmp.begin(), tmp.end());
6154                 }
6155         }
6156
6157         return result;
6158 }
6159
6160 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6161 {
6162         vector<deFloat16>       vec;
6163         vector<deFloat16>       result;
6164
6165         // Create vectors. vec will contain each possible pair from inData
6166         {
6167                 const size_t    inDataLength    = inData.size();
6168
6169                 DE_ASSERT(inDataLength <= 64);
6170
6171                 vec.reserve(2 * inDataLength * inDataLength);
6172
6173                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6174                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6175                 {
6176                         vec.push_back(inData[numIdxX]);
6177                         vec.push_back(inData[numIdxY]);
6178                 }
6179         }
6180
6181         // Create vector pairs. result will contain each possible pair from vec
6182         {
6183                 const size_t    coordsPerVector = 2;
6184                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6185
6186                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6187
6188                 if (argNo == 0)
6189                 {
6190                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6191                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6192                         {
6193                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6194                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6195                         }
6196                 }
6197
6198                 if (argNo == 1)
6199                 {
6200                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6201                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6202                         {
6203                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6204                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6205                         }
6206                 }
6207         }
6208
6209         return result;
6210 }
6211
6212 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6213 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6214 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6215 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6216 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6217 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6218 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6219 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6220
6221 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6222 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6223 {
6224         if (inputs.size() != 2 || outputAllocs.size() != 1)
6225                 return false;
6226
6227         vector<deUint8> input1Bytes;
6228         vector<deUint8> input2Bytes;
6229
6230         inputs[0].getBytes(input1Bytes);
6231         inputs[1].getBytes(input2Bytes);
6232
6233         const deUint32                  denormModesCount                        = 2;
6234         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6235         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6236         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6237         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6238         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6239         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6240         deUint32                                successfulRuns                          = denormModesCount;
6241         std::string                             results[denormModesCount];
6242         TestedLogicalFunction   testedLogicalFunction;
6243
6244         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6245         {
6246                 const bool flushToZero = (denormMode == 1);
6247
6248                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6249                 {
6250                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6251                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6252                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6253                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6254                         deFloat16                       expectedOutput  = float16zero;
6255
6256                         if (onlyTestFunc)
6257                         {
6258                                 if (testedLogicalFunction(f1, f2))
6259                                         expectedOutput = float16one;
6260                         }
6261                         else
6262                         {
6263                                 const bool      f1nan   = f1.isNaN();
6264                                 const bool      f2nan   = f2.isNaN();
6265
6266                                 // Skip NaN floats if not supported by implementation
6267                                 if (!nanSupported && (f1nan || f2nan))
6268                                         continue;
6269
6270                                 if (unationModeAnd)
6271                                 {
6272                                         const bool      ordered         = !f1nan && !f2nan;
6273
6274                                         if (ordered && testedLogicalFunction(f1, f2))
6275                                                 expectedOutput = float16one;
6276                                 }
6277                                 else
6278                                 {
6279                                         const bool      unordered       = f1nan || f2nan;
6280
6281                                         if (unordered || testedLogicalFunction(f1, f2))
6282                                                 expectedOutput = float16one;
6283                                 }
6284                         }
6285
6286                         if (outputAsFP16[idx] != expectedOutput)
6287                         {
6288                                 std::ostringstream str;
6289
6290                                 str << "ERROR: Sub-case #" << idx
6291                                         << " flushToZero:" << flushToZero
6292                                         << std::hex
6293                                         << " failed, inputs: 0x" << f1.bits()
6294                                         << ";0x" << f2.bits()
6295                                         << " output: 0x" << outputAsFP16[idx]
6296                                         << " expected output: 0x" << expectedOutput;
6297
6298                                 results[denormMode] = str.str();
6299
6300                                 successfulRuns--;
6301
6302                                 break;
6303                         }
6304                 }
6305         }
6306
6307         if (successfulRuns == 0)
6308                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6309                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6310
6311         return successfulRuns > 0;
6312 }
6313
6314 } // anonymous
6315
6316 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6317 {
6318         struct NameCodePair { string name, code; };
6319         RGBA                                                    defaultColors[4];
6320         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6321         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6322         map<string, string>                             fragments                               = passthruFragments();
6323         const NameCodePair                              tests[]                                 =
6324         {
6325                 {"unknown", "OpSource Unknown 321"},
6326                 {"essl", "OpSource ESSL 310"},
6327                 {"glsl", "OpSource GLSL 450"},
6328                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6329                 {"opencl_c", "OpSource OpenCL_C 120"},
6330                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6331                 {"file", opsourceGLSLWithFile},
6332                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6333                 // Longest possible source string: SPIR-V limits instructions to 65535
6334                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6335                 // contain 65530 UTF8 characters (one word each) plus one last word
6336                 // containing 3 ASCII characters and \0.
6337                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6338         };
6339
6340         getDefaultColors(defaultColors);
6341         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6342         {
6343                 fragments["debug"] = tests[testNdx].code;
6344                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6345         }
6346
6347         return opSourceTests.release();
6348 }
6349
6350 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6351 {
6352         struct NameCodePair { string name, code; };
6353         RGBA                                                            defaultColors[4];
6354         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6355         map<string, string>                                     fragments                       = passthruFragments();
6356         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6357         const NameCodePair                                      tests[]                         =
6358         {
6359                 {"empty", opsource + "OpSourceContinued \"\""},
6360                 {"short", opsource + "OpSourceContinued \"abcde\""},
6361                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6362                 // Longest possible source string: SPIR-V limits instructions to 65535
6363                 // words, of which the first one is OpSourceContinued/length; the rest
6364                 // will contain 65533 UTF8 characters (one word each) plus one last word
6365                 // containing 3 ASCII characters and \0.
6366                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6367         };
6368
6369         getDefaultColors(defaultColors);
6370         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6371         {
6372                 fragments["debug"] = tests[testNdx].code;
6373                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6374         }
6375
6376         return opSourceTests.release();
6377 }
6378 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6379 {
6380         RGBA                                                             defaultColors[4];
6381         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6382         map<string, string>                                      fragments;
6383         getDefaultColors(defaultColors);
6384         fragments["debug"]                      =
6385                 "%name = OpString \"name\"\n";
6386
6387         fragments["pre_main"]   =
6388                 "OpNoLine\n"
6389                 "OpNoLine\n"
6390                 "OpLine %name 1 1\n"
6391                 "OpNoLine\n"
6392                 "OpLine %name 1 1\n"
6393                 "OpLine %name 1 1\n"
6394                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6395                 "OpNoLine\n"
6396                 "OpLine %name 1 1\n"
6397                 "OpNoLine\n"
6398                 "OpLine %name 1 1\n"
6399                 "OpLine %name 1 1\n"
6400                 "%second_param1 = OpFunctionParameter %v4f32\n"
6401                 "OpNoLine\n"
6402                 "OpNoLine\n"
6403                 "%label_secondfunction = OpLabel\n"
6404                 "OpNoLine\n"
6405                 "OpReturnValue %second_param1\n"
6406                 "OpFunctionEnd\n"
6407                 "OpNoLine\n"
6408                 "OpNoLine\n";
6409
6410         fragments["testfun"]            =
6411                 // A %test_code function that returns its argument unchanged.
6412                 "OpNoLine\n"
6413                 "OpNoLine\n"
6414                 "OpLine %name 1 1\n"
6415                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6416                 "OpNoLine\n"
6417                 "%param1 = OpFunctionParameter %v4f32\n"
6418                 "OpNoLine\n"
6419                 "OpNoLine\n"
6420                 "%label_testfun = OpLabel\n"
6421                 "OpNoLine\n"
6422                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6423                 "OpReturnValue %val1\n"
6424                 "OpFunctionEnd\n"
6425                 "OpLine %name 1 1\n"
6426                 "OpNoLine\n";
6427
6428         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6429
6430         return opLineTests.release();
6431 }
6432
6433 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6434 {
6435         RGBA                                                            defaultColors[4];
6436         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6437         map<string, string>                                     fragments;
6438         std::vector<std::string>                        noExtensions;
6439         GraphicsResources                                       resources;
6440
6441         getDefaultColors(defaultColors);
6442         resources.verifyBinary = veryfiBinaryShader;
6443         resources.spirvVersion = SPIRV_VERSION_1_3;
6444
6445         fragments["moduleprocessed"]                                                    =
6446                 "OpModuleProcessed \"VULKAN CTS\"\n"
6447                 "OpModuleProcessed \"Negative values\"\n"
6448                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6449
6450         fragments["pre_main"]   =
6451                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6452                 "%second_param1 = OpFunctionParameter %v4f32\n"
6453                 "%label_secondfunction = OpLabel\n"
6454                 "OpReturnValue %second_param1\n"
6455                 "OpFunctionEnd\n";
6456
6457         fragments["testfun"]            =
6458                 // A %test_code function that returns its argument unchanged.
6459                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6460                 "%param1 = OpFunctionParameter %v4f32\n"
6461                 "%label_testfun = OpLabel\n"
6462                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6463                 "OpReturnValue %val1\n"
6464                 "OpFunctionEnd\n";
6465
6466         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6467
6468         return opModuleProcessedTests.release();
6469 }
6470
6471
6472 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6473 {
6474         RGBA                                                                                                    defaultColors[4];
6475         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6476         map<string, string>                                                                             fragments;
6477         std::vector<std::pair<std::string, std::string> >               problemStrings;
6478
6479         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6480         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6481         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6482         getDefaultColors(defaultColors);
6483
6484         fragments["debug"]                      =
6485                 "%other_name = OpString \"other_name\"\n";
6486
6487         fragments["pre_main"]   =
6488                 "OpLine %file_name 32 0\n"
6489                 "OpLine %file_name 32 32\n"
6490                 "OpLine %file_name 32 40\n"
6491                 "OpLine %other_name 32 40\n"
6492                 "OpLine %other_name 0 100\n"
6493                 "OpLine %other_name 0 4294967295\n"
6494                 "OpLine %other_name 4294967295 0\n"
6495                 "OpLine %other_name 32 40\n"
6496                 "OpLine %file_name 0 0\n"
6497                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6498                 "OpLine %file_name 1 0\n"
6499                 "%second_param1 = OpFunctionParameter %v4f32\n"
6500                 "OpLine %file_name 1 3\n"
6501                 "OpLine %file_name 1 2\n"
6502                 "%label_secondfunction = OpLabel\n"
6503                 "OpLine %file_name 0 2\n"
6504                 "OpReturnValue %second_param1\n"
6505                 "OpFunctionEnd\n"
6506                 "OpLine %file_name 0 2\n"
6507                 "OpLine %file_name 0 2\n";
6508
6509         fragments["testfun"]            =
6510                 // A %test_code function that returns its argument unchanged.
6511                 "OpLine %file_name 1 0\n"
6512                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6513                 "OpLine %file_name 16 330\n"
6514                 "%param1 = OpFunctionParameter %v4f32\n"
6515                 "OpLine %file_name 14 442\n"
6516                 "%label_testfun = OpLabel\n"
6517                 "OpLine %file_name 11 1024\n"
6518                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6519                 "OpLine %file_name 2 97\n"
6520                 "OpReturnValue %val1\n"
6521                 "OpFunctionEnd\n"
6522                 "OpLine %file_name 5 32\n";
6523
6524         for (size_t i = 0; i < problemStrings.size(); ++i)
6525         {
6526                 map<string, string> testFragments = fragments;
6527                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6528                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6529         }
6530
6531         return opLineTests.release();
6532 }
6533
6534 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6535 {
6536         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6537         RGBA                                                    colors[4];
6538
6539
6540         const char                                              functionStart[] =
6541                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6542                 "%param1 = OpFunctionParameter %v4f32\n"
6543                 "%lbl    = OpLabel\n";
6544
6545         const char                                              functionEnd[]   =
6546                 "OpReturnValue %transformed_param\n"
6547                 "OpFunctionEnd\n";
6548
6549         struct NameConstantsCode
6550         {
6551                 string name;
6552                 string constants;
6553                 string code;
6554         };
6555
6556         NameConstantsCode tests[] =
6557         {
6558                 {
6559                         "vec4",
6560                         "%cnull = OpConstantNull %v4f32\n",
6561                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6562                 },
6563                 {
6564                         "float",
6565                         "%cnull = OpConstantNull %f32\n",
6566                         "%vp = OpVariable %fp_v4f32 Function\n"
6567                         "%v  = OpLoad %v4f32 %vp\n"
6568                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6569                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6570                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6571                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6572                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6573                 },
6574                 {
6575                         "bool",
6576                         "%cnull             = OpConstantNull %bool\n",
6577                         "%v                 = OpVariable %fp_v4f32 Function\n"
6578                         "                     OpStore %v %param1\n"
6579                         "                     OpSelectionMerge %false_label None\n"
6580                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6581                         "%true_label        = OpLabel\n"
6582                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6583                         "                     OpBranch %false_label\n"
6584                         "%false_label       = OpLabel\n"
6585                         "%transformed_param = OpLoad %v4f32 %v\n"
6586                 },
6587                 {
6588                         "i32",
6589                         "%cnull             = OpConstantNull %i32\n",
6590                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6591                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6592                         "                     OpSelectionMerge %false_label None\n"
6593                         "                     OpBranchConditional %b %true_label %false_label\n"
6594                         "%true_label        = OpLabel\n"
6595                         "                     OpStore %v %param1\n"
6596                         "                     OpBranch %false_label\n"
6597                         "%false_label       = OpLabel\n"
6598                         "%transformed_param = OpLoad %v4f32 %v\n"
6599                 },
6600                 {
6601                         "struct",
6602                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6603                         "%fp_stype          = OpTypePointer Function %stype\n"
6604                         "%cnull             = OpConstantNull %stype\n",
6605                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6606                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6607                         "%f_val             = OpLoad %v4f32 %f\n"
6608                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6609                 },
6610                 {
6611                         "array",
6612                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6613                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6614                         "%cnull             = OpConstantNull %a4_v4f32\n",
6615                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6616                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6617                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6618                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6619                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6620                         "%f_val             = OpLoad %v4f32 %f\n"
6621                         "%f1_val            = OpLoad %v4f32 %f1\n"
6622                         "%f2_val            = OpLoad %v4f32 %f2\n"
6623                         "%f3_val            = OpLoad %v4f32 %f3\n"
6624                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6625                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6626                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6627                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6628                 },
6629                 {
6630                         "matrix",
6631                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6632                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6633                         // Our null matrix * any vector should result in a zero vector.
6634                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6635                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6636                 }
6637         };
6638
6639         getHalfColorsFullAlpha(colors);
6640
6641         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6642         {
6643                 map<string, string> fragments;
6644                 fragments["pre_main"] = tests[testNdx].constants;
6645                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6646                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6647         }
6648         return opConstantNullTests.release();
6649 }
6650 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6651 {
6652         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6653         RGBA                                                    inputColors[4];
6654         RGBA                                                    outputColors[4];
6655
6656
6657         const char                                              functionStart[]  =
6658                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6659                 "%param1 = OpFunctionParameter %v4f32\n"
6660                 "%lbl    = OpLabel\n";
6661
6662         const char                                              functionEnd[]           =
6663                 "OpReturnValue %transformed_param\n"
6664                 "OpFunctionEnd\n";
6665
6666         struct NameConstantsCode
6667         {
6668                 string name;
6669                 string constants;
6670                 string code;
6671         };
6672
6673         NameConstantsCode tests[] =
6674         {
6675                 {
6676                         "vec4",
6677
6678                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6679                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6680                 },
6681                 {
6682                         "struct",
6683
6684                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6685                         "%fp_stype          = OpTypePointer Function %stype\n"
6686                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6687                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6688                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6689                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6690
6691                         "%v                 = OpVariable %fp_stype Function %cval\n"
6692                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6693                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6694                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6695                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6696                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6697                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6698                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6699                 },
6700                 {
6701                         // [1|0|0|0.5] [x] = x + 0.5
6702                         // [0|1|0|0.5] [y] = y + 0.5
6703                         // [0|0|1|0.5] [z] = z + 0.5
6704                         // [0|0|0|1  ] [1] = 1
6705                         "matrix",
6706
6707                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6708                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6709                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6710                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6711                         "%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"
6712                         "%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",
6713
6714                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6715                 },
6716                 {
6717                         "array",
6718
6719                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6720                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6721                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6722                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6723                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6724
6725                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6726                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6727                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6728                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6729                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6730                         "%f_val               = OpLoad %f32 %f\n"
6731                         "%f1_val              = OpLoad %f32 %f1\n"
6732                         "%f2_val              = OpLoad %f32 %f2\n"
6733                         "%f3_val              = OpLoad %f32 %f3\n"
6734                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6735                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6736                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6737                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6738                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6739                 },
6740                 {
6741                         //
6742                         // [
6743                         //   {
6744                         //      0.0,
6745                         //      [ 1.0, 1.0, 1.0, 1.0]
6746                         //   },
6747                         //   {
6748                         //      1.0,
6749                         //      [ 0.0, 0.5, 0.0, 0.0]
6750                         //   }, //     ^^^
6751                         //   {
6752                         //      0.0,
6753                         //      [ 1.0, 1.0, 1.0, 1.0]
6754                         //   }
6755                         // ]
6756                         "array_of_struct_of_array",
6757
6758                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6759                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6760                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6761                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6762                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6763                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6764                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6765                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6766                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6767                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6768
6769                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6770                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6771                         "%f_l                 = OpLoad %f32 %f\n"
6772                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6773                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6774                 }
6775         };
6776
6777         getHalfColorsFullAlpha(inputColors);
6778         outputColors[0] = RGBA(255, 255, 255, 255);
6779         outputColors[1] = RGBA(255, 127, 127, 255);
6780         outputColors[2] = RGBA(127, 255, 127, 255);
6781         outputColors[3] = RGBA(127, 127, 255, 255);
6782
6783         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6784         {
6785                 map<string, string> fragments;
6786                 fragments["pre_main"] = tests[testNdx].constants;
6787                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6788                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6789         }
6790         return opConstantCompositeTests.release();
6791 }
6792
6793 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6794 {
6795         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6796         RGBA                                                    inputColors[4];
6797         RGBA                                                    outputColors[4];
6798         map<string, string>                             fragments;
6799
6800         // vec4 test_code(vec4 param) {
6801         //   vec4 result = param;
6802         //   for (int i = 0; i < 4; ++i) {
6803         //     if (i == 0) result[i] = 0.;
6804         //     else        result[i] = 1. - result[i];
6805         //   }
6806         //   return result;
6807         // }
6808         const char                                              function[]                      =
6809                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6810                 "%param1    = OpFunctionParameter %v4f32\n"
6811                 "%lbl       = OpLabel\n"
6812                 "%iptr      = OpVariable %fp_i32 Function\n"
6813                 "%result    = OpVariable %fp_v4f32 Function\n"
6814                 "             OpStore %iptr %c_i32_0\n"
6815                 "             OpStore %result %param1\n"
6816                 "             OpBranch %loop\n"
6817
6818                 // Loop entry block.
6819                 "%loop      = OpLabel\n"
6820                 "%ival      = OpLoad %i32 %iptr\n"
6821                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6822                 "             OpLoopMerge %exit %if_entry None\n"
6823                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6824
6825                 // Merge block for loop.
6826                 "%exit      = OpLabel\n"
6827                 "%ret       = OpLoad %v4f32 %result\n"
6828                 "             OpReturnValue %ret\n"
6829
6830                 // If-statement entry block.
6831                 "%if_entry  = OpLabel\n"
6832                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6833                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6834                 "             OpSelectionMerge %if_exit None\n"
6835                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6836
6837                 // False branch for if-statement.
6838                 "%if_false  = OpLabel\n"
6839                 "%val       = OpLoad %f32 %loc\n"
6840                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6841                 "             OpStore %loc %sub\n"
6842                 "             OpBranch %if_exit\n"
6843
6844                 // Merge block for if-statement.
6845                 "%if_exit   = OpLabel\n"
6846                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6847                 "             OpStore %iptr %ival_next\n"
6848                 "             OpBranch %loop\n"
6849
6850                 // True branch for if-statement.
6851                 "%if_true   = OpLabel\n"
6852                 "             OpStore %loc %c_f32_0\n"
6853                 "             OpBranch %if_exit\n"
6854
6855                 "             OpFunctionEnd\n";
6856
6857         fragments["testfun"]    = function;
6858
6859         inputColors[0]                  = RGBA(127, 127, 127, 0);
6860         inputColors[1]                  = RGBA(127, 0,   0,   0);
6861         inputColors[2]                  = RGBA(0,   127, 0,   0);
6862         inputColors[3]                  = RGBA(0,   0,   127, 0);
6863
6864         outputColors[0]                 = RGBA(0, 128, 128, 255);
6865         outputColors[1]                 = RGBA(0, 255, 255, 255);
6866         outputColors[2]                 = RGBA(0, 128, 255, 255);
6867         outputColors[3]                 = RGBA(0, 255, 128, 255);
6868
6869         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6870
6871         return group.release();
6872 }
6873
6874 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6875 {
6876         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6877         RGBA                                                    inputColors[4];
6878         RGBA                                                    outputColors[4];
6879         map<string, string>                             fragments;
6880
6881         const char                                              typesAndConstants[]     =
6882                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6883                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6884                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6885                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6886
6887         // vec4 test_code(vec4 param) {
6888         //   vec4 result = param;
6889         //   for (int i = 0; i < 4; ++i) {
6890         //     switch (i) {
6891         //       case 0: result[i] += .2; break;
6892         //       case 1: result[i] += .6; break;
6893         //       case 2: result[i] += .4; break;
6894         //       case 3: result[i] += .8; break;
6895         //       default: break; // unreachable
6896         //     }
6897         //   }
6898         //   return result;
6899         // }
6900         const char                                              function[]                      =
6901                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6902                 "%param1    = OpFunctionParameter %v4f32\n"
6903                 "%lbl       = OpLabel\n"
6904                 "%iptr      = OpVariable %fp_i32 Function\n"
6905                 "%result    = OpVariable %fp_v4f32 Function\n"
6906                 "             OpStore %iptr %c_i32_0\n"
6907                 "             OpStore %result %param1\n"
6908                 "             OpBranch %loop\n"
6909
6910                 // Loop entry block.
6911                 "%loop      = OpLabel\n"
6912                 "%ival      = OpLoad %i32 %iptr\n"
6913                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6914                 "             OpLoopMerge %exit %switch_exit None\n"
6915                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6916
6917                 // Merge block for loop.
6918                 "%exit      = OpLabel\n"
6919                 "%ret       = OpLoad %v4f32 %result\n"
6920                 "             OpReturnValue %ret\n"
6921
6922                 // Switch-statement entry block.
6923                 "%switch_entry   = OpLabel\n"
6924                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6925                 "%val            = OpLoad %f32 %loc\n"
6926                 "                  OpSelectionMerge %switch_exit None\n"
6927                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6928
6929                 "%case2          = OpLabel\n"
6930                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6931                 "                  OpStore %loc %addp4\n"
6932                 "                  OpBranch %switch_exit\n"
6933
6934                 "%switch_default = OpLabel\n"
6935                 "                  OpUnreachable\n"
6936
6937                 "%case3          = OpLabel\n"
6938                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6939                 "                  OpStore %loc %addp8\n"
6940                 "                  OpBranch %switch_exit\n"
6941
6942                 "%case0          = OpLabel\n"
6943                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6944                 "                  OpStore %loc %addp2\n"
6945                 "                  OpBranch %switch_exit\n"
6946
6947                 // Merge block for switch-statement.
6948                 "%switch_exit    = OpLabel\n"
6949                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6950                 "                  OpStore %iptr %ival_next\n"
6951                 "                  OpBranch %loop\n"
6952
6953                 "%case1          = OpLabel\n"
6954                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6955                 "                  OpStore %loc %addp6\n"
6956                 "                  OpBranch %switch_exit\n"
6957
6958                 "                  OpFunctionEnd\n";
6959
6960         fragments["pre_main"]   = typesAndConstants;
6961         fragments["testfun"]    = function;
6962
6963         inputColors[0]                  = RGBA(127, 27,  127, 51);
6964         inputColors[1]                  = RGBA(127, 0,   0,   51);
6965         inputColors[2]                  = RGBA(0,   27,  0,   51);
6966         inputColors[3]                  = RGBA(0,   0,   127, 51);
6967
6968         outputColors[0]                 = RGBA(178, 180, 229, 255);
6969         outputColors[1]                 = RGBA(178, 153, 102, 255);
6970         outputColors[2]                 = RGBA(51,  180, 102, 255);
6971         outputColors[3]                 = RGBA(51,  153, 229, 255);
6972
6973         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6974
6975         return group.release();
6976 }
6977
6978 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6979 {
6980         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6981         RGBA                                                    inputColors[4];
6982         RGBA                                                    outputColors[4];
6983         map<string, string>                             fragments;
6984
6985         const char                                              decorations[]           =
6986                 "OpDecorate %array_group         ArrayStride 4\n"
6987                 "OpDecorate %struct_member_group Offset 0\n"
6988                 "%array_group         = OpDecorationGroup\n"
6989                 "%struct_member_group = OpDecorationGroup\n"
6990
6991                 "OpDecorate %group1 RelaxedPrecision\n"
6992                 "OpDecorate %group3 RelaxedPrecision\n"
6993                 "OpDecorate %group3 Invariant\n"
6994                 "OpDecorate %group3 Restrict\n"
6995                 "%group0 = OpDecorationGroup\n"
6996                 "%group1 = OpDecorationGroup\n"
6997                 "%group3 = OpDecorationGroup\n";
6998
6999         const char                                              typesAndConstants[]     =
7000                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
7001                 "%struct1   = OpTypeStruct %a3f32\n"
7002                 "%struct2   = OpTypeStruct %a3f32\n"
7003                 "%fp_struct1 = OpTypePointer Function %struct1\n"
7004                 "%fp_struct2 = OpTypePointer Function %struct2\n"
7005                 "%c_f32_2    = OpConstant %f32 2.\n"
7006                 "%c_f32_n2   = OpConstant %f32 -2.\n"
7007
7008                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
7009                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
7010                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
7011                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
7012
7013         const char                                              function[]                      =
7014                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7015                 "%param     = OpFunctionParameter %v4f32\n"
7016                 "%entry     = OpLabel\n"
7017                 "%result    = OpVariable %fp_v4f32 Function\n"
7018                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
7019                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
7020                 "             OpStore %result %param\n"
7021                 "             OpStore %v_struct1 %c_struct1\n"
7022                 "             OpStore %v_struct2 %c_struct2\n"
7023                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
7024                 "%val1      = OpLoad %f32 %ptr1\n"
7025                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
7026                 "%val2      = OpLoad %f32 %ptr2\n"
7027                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
7028                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7029                 "%val       = OpLoad %f32 %ptr\n"
7030                 "%addresult = OpFAdd %f32 %addvalues %val\n"
7031                 "             OpStore %ptr %addresult\n"
7032                 "%ret       = OpLoad %v4f32 %result\n"
7033                 "             OpReturnValue %ret\n"
7034                 "             OpFunctionEnd\n";
7035
7036         struct CaseNameDecoration
7037         {
7038                 string name;
7039                 string decoration;
7040         };
7041
7042         CaseNameDecoration tests[] =
7043         {
7044                 {
7045                         "same_decoration_group_on_multiple_types",
7046                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
7047                 },
7048                 {
7049                         "empty_decoration_group",
7050                         "OpGroupDecorate %group0      %a3f32\n"
7051                         "OpGroupDecorate %group0      %result\n"
7052                 },
7053                 {
7054                         "one_element_decoration_group",
7055                         "OpGroupDecorate %array_group %a3f32\n"
7056                 },
7057                 {
7058                         "multiple_elements_decoration_group",
7059                         "OpGroupDecorate %group3      %v_struct1\n"
7060                 },
7061                 {
7062                         "multiple_decoration_groups_on_same_variable",
7063                         "OpGroupDecorate %group0      %v_struct2\n"
7064                         "OpGroupDecorate %group1      %v_struct2\n"
7065                         "OpGroupDecorate %group3      %v_struct2\n"
7066                 },
7067                 {
7068                         "same_decoration_group_multiple_times",
7069                         "OpGroupDecorate %group1      %addvalues\n"
7070                         "OpGroupDecorate %group1      %addvalues\n"
7071                         "OpGroupDecorate %group1      %addvalues\n"
7072                 },
7073
7074         };
7075
7076         getHalfColorsFullAlpha(inputColors);
7077         getHalfColorsFullAlpha(outputColors);
7078
7079         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
7080         {
7081                 fragments["decoration"] = decorations + tests[idx].decoration;
7082                 fragments["pre_main"]   = typesAndConstants;
7083                 fragments["testfun"]    = function;
7084
7085                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
7086         }
7087
7088         return group.release();
7089 }
7090
7091 struct SpecConstantTwoIntGraphicsCase
7092 {
7093         const char*             caseName;
7094         const char*             scDefinition0;
7095         const char*             scDefinition1;
7096         const char*             scResultType;
7097         const char*             scOperation;
7098         deInt32                 scActualValue0;
7099         deInt32                 scActualValue1;
7100         const char*             resultOperation;
7101         RGBA                    expectedColors[4];
7102         deInt32                 scActualValueLength;
7103
7104                                         SpecConstantTwoIntGraphicsCase (const char*             name,
7105                                                                                                         const char*             definition0,
7106                                                                                                         const char*             definition1,
7107                                                                                                         const char*             resultType,
7108                                                                                                         const char*             operation,
7109                                                                                                         const deInt32   value0,
7110                                                                                                         const deInt32   value1,
7111                                                                                                         const char*             resultOp,
7112                                                                                                         const RGBA              (&output)[4],
7113                                                                                                         const deInt32   valueLength = sizeof(deInt32))
7114                                                 : caseName                              (name)
7115                                                 , scDefinition0                 (definition0)
7116                                                 , scDefinition1                 (definition1)
7117                                                 , scResultType                  (resultType)
7118                                                 , scOperation                   (operation)
7119                                                 , scActualValue0                (value0)
7120                                                 , scActualValue1                (value1)
7121                                                 , resultOperation               (resultOp)
7122                                                 , scActualValueLength   (valueLength)
7123         {
7124                 expectedColors[0] = output[0];
7125                 expectedColors[1] = output[1];
7126                 expectedColors[2] = output[2];
7127                 expectedColors[3] = output[3];
7128         }
7129 };
7130
7131 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7132 {
7133         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7134         vector<SpecConstantTwoIntGraphicsCase>  cases;
7135         RGBA                                                    inputColors[4];
7136         RGBA                                                    outputColors0[4];
7137         RGBA                                                    outputColors1[4];
7138         RGBA                                                    outputColors2[4];
7139
7140         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7141
7142         const char      decorations1[]                  =
7143                 "OpDecorate %sc_0  SpecId 0\n"
7144                 "OpDecorate %sc_1  SpecId 1\n";
7145
7146         const char      typesAndConstants1[]    =
7147                 "${OPTYPE_DEFINITIONS:opt}"
7148                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7149                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7150                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7151
7152         const char      function1[]                             =
7153                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7154                 "%param     = OpFunctionParameter %v4f32\n"
7155                 "%label     = OpLabel\n"
7156                 "%result    = OpVariable %fp_v4f32 Function\n"
7157                 "${TYPE_CONVERT:opt}"
7158                 "             OpStore %result %param\n"
7159                 "%gen       = ${GEN_RESULT}\n"
7160                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7161                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7162                 "%val       = OpLoad %f32 %loc\n"
7163                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7164                 "             OpStore %loc %add\n"
7165                 "%ret       = OpLoad %v4f32 %result\n"
7166                 "             OpReturnValue %ret\n"
7167                 "             OpFunctionEnd\n";
7168
7169         inputColors[0] = RGBA(127, 127, 127, 255);
7170         inputColors[1] = RGBA(127, 0,   0,   255);
7171         inputColors[2] = RGBA(0,   127, 0,   255);
7172         inputColors[3] = RGBA(0,   0,   127, 255);
7173
7174         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7175         outputColors0[0] = RGBA(255, 127, 127, 255);
7176         outputColors0[1] = RGBA(255, 0,   0,   255);
7177         outputColors0[2] = RGBA(128, 127, 0,   255);
7178         outputColors0[3] = RGBA(128, 0,   127, 255);
7179
7180         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7181         outputColors1[0] = RGBA(127, 255, 127, 255);
7182         outputColors1[1] = RGBA(127, 128, 0,   255);
7183         outputColors1[2] = RGBA(0,   255, 0,   255);
7184         outputColors1[3] = RGBA(0,   128, 127, 255);
7185
7186         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7187         outputColors2[0] = RGBA(127, 127, 255, 255);
7188         outputColors2[1] = RGBA(127, 0,   128, 255);
7189         outputColors2[2] = RGBA(0,   127, 128, 255);
7190         outputColors2[3] = RGBA(0,   0,   255, 255);
7191
7192         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7193         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7194         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7195         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7196
7197         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7198         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7199         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7200         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7201         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7202         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7203         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7204         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7205         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7206         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7207         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7208         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7209         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7210         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7211         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7212         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7213         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7214         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7215         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7216         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7217         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7218         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7219         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7220         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7221         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7222         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7223         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7224         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7225         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7226         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7227         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7228         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7229         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7230         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7231         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7232         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7233         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7234
7235         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7236         {
7237                 map<string, string>                     specializations;
7238                 map<string, string>                     fragments;
7239                 SpecConstants                           specConstants;
7240                 PushConstants                           noPushConstants;
7241                 GraphicsResources                       noResources;
7242                 GraphicsInterfaces                      noInterfaces;
7243                 vector<string>                          extensions;
7244                 VulkanFeatures                          requiredFeatures;
7245
7246                 // Special SPIR-V code for SConvert-case
7247                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7248                 {
7249                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7250                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7251                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7252                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7253                 }
7254
7255                 // Special SPIR-V code for FConvert-case
7256                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7257                 {
7258                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7259                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7260                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7261                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7262                 }
7263
7264                 // Special SPIR-V code for FConvert-case for 16-bit floats
7265                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7266                 {
7267                         extensions.push_back("VK_KHR_shader_float16_int8");
7268                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7269                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7270                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7271                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7272                 }
7273
7274                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7275                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7276                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7277                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7278                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7279
7280                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7281                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7282                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7283
7284                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7285                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7286
7287                 createTestsForAllStages(
7288                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7289                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7290         }
7291
7292         const char      decorations2[]                  =
7293                 "OpDecorate %sc_0  SpecId 0\n"
7294                 "OpDecorate %sc_1  SpecId 1\n"
7295                 "OpDecorate %sc_2  SpecId 2\n";
7296
7297         const char      typesAndConstants2[]    =
7298                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7299                 "%vec3_undef  = OpUndef %v3i32\n"
7300
7301                 "%sc_0        = OpSpecConstant %i32 0\n"
7302                 "%sc_1        = OpSpecConstant %i32 0\n"
7303                 "%sc_2        = OpSpecConstant %i32 0\n"
7304                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7305                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7306                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7307                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7308                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7309                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7310                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7311                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7312                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7313                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7314                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7315                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7316                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7317
7318         const char      function2[]                             =
7319                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7320                 "%param     = OpFunctionParameter %v4f32\n"
7321                 "%label     = OpLabel\n"
7322                 "%result    = OpVariable %fp_v4f32 Function\n"
7323                 "             OpStore %result %param\n"
7324                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7325                 "%val       = OpLoad %f32 %loc\n"
7326                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7327                 "             OpStore %loc %add\n"
7328                 "%ret       = OpLoad %v4f32 %result\n"
7329                 "             OpReturnValue %ret\n"
7330                 "             OpFunctionEnd\n";
7331
7332         map<string, string>     fragments;
7333         SpecConstants           specConstants;
7334
7335         fragments["decoration"] = decorations2;
7336         fragments["pre_main"]   = typesAndConstants2;
7337         fragments["testfun"]    = function2;
7338
7339         specConstants.append<deInt32>(56789);
7340         specConstants.append<deInt32>(-2);
7341         specConstants.append<deInt32>(56788);
7342
7343         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7344
7345         return group.release();
7346 }
7347
7348 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7349 {
7350         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7351         RGBA                                                    inputColors[4];
7352         RGBA                                                    outputColors1[4];
7353         RGBA                                                    outputColors2[4];
7354         RGBA                                                    outputColors3[4];
7355         RGBA                                                    outputColors4[4];
7356         map<string, string>                             fragments1;
7357         map<string, string>                             fragments2;
7358         map<string, string>                             fragments3;
7359         map<string, string>                             fragments4;
7360         std::vector<std::string>                extensions4;
7361         GraphicsResources                               resources4;
7362         VulkanFeatures                                  vulkanFeatures4;
7363
7364         const char      typesAndConstants1[]    =
7365                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7366                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7367                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7368                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7369
7370         // vec4 test_code(vec4 param) {
7371         //   vec4 result = param;
7372         //   for (int i = 0; i < 4; ++i) {
7373         //     float operand;
7374         //     switch (i) {
7375         //       case 0: operand = .2; break;
7376         //       case 1: operand = .5; break;
7377         //       case 2: operand = .4; break;
7378         //       case 3: operand = .0; break;
7379         //       default: break; // unreachable
7380         //     }
7381         //     result[i] += operand;
7382         //   }
7383         //   return result;
7384         // }
7385         const char      function1[]                             =
7386                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7387                 "%param1    = OpFunctionParameter %v4f32\n"
7388                 "%lbl       = OpLabel\n"
7389                 "%iptr      = OpVariable %fp_i32 Function\n"
7390                 "%result    = OpVariable %fp_v4f32 Function\n"
7391                 "             OpStore %iptr %c_i32_0\n"
7392                 "             OpStore %result %param1\n"
7393                 "             OpBranch %loop\n"
7394
7395                 "%loop      = OpLabel\n"
7396                 "%ival      = OpLoad %i32 %iptr\n"
7397                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7398                 "             OpLoopMerge %exit %phi None\n"
7399                 "             OpBranchConditional %lt_4 %entry %exit\n"
7400
7401                 "%entry     = OpLabel\n"
7402                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7403                 "%val       = OpLoad %f32 %loc\n"
7404                 "             OpSelectionMerge %phi None\n"
7405                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7406
7407                 "%case0     = OpLabel\n"
7408                 "             OpBranch %phi\n"
7409                 "%case1     = OpLabel\n"
7410                 "             OpBranch %phi\n"
7411                 "%case2     = OpLabel\n"
7412                 "             OpBranch %phi\n"
7413                 "%case3     = OpLabel\n"
7414                 "             OpBranch %phi\n"
7415
7416                 "%default   = OpLabel\n"
7417                 "             OpUnreachable\n"
7418
7419                 "%phi       = OpLabel\n"
7420                 "%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
7421                 "%add       = OpFAdd %f32 %val %operand\n"
7422                 "             OpStore %loc %add\n"
7423                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7424                 "             OpStore %iptr %ival_next\n"
7425                 "             OpBranch %loop\n"
7426
7427                 "%exit      = OpLabel\n"
7428                 "%ret       = OpLoad %v4f32 %result\n"
7429                 "             OpReturnValue %ret\n"
7430
7431                 "             OpFunctionEnd\n";
7432
7433         fragments1["pre_main"]  = typesAndConstants1;
7434         fragments1["testfun"]   = function1;
7435
7436         getHalfColorsFullAlpha(inputColors);
7437
7438         outputColors1[0]                = RGBA(178, 255, 229, 255);
7439         outputColors1[1]                = RGBA(178, 127, 102, 255);
7440         outputColors1[2]                = RGBA(51,  255, 102, 255);
7441         outputColors1[3]                = RGBA(51,  127, 229, 255);
7442
7443         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7444
7445         const char      typesAndConstants2[]    =
7446                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7447
7448         // Add .4 to the second element of the given parameter.
7449         const char      function2[]                             =
7450                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7451                 "%param     = OpFunctionParameter %v4f32\n"
7452                 "%entry     = OpLabel\n"
7453                 "%result    = OpVariable %fp_v4f32 Function\n"
7454                 "             OpStore %result %param\n"
7455                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7456                 "%val       = OpLoad %f32 %loc\n"
7457                 "             OpBranch %phi\n"
7458
7459                 "%phi        = OpLabel\n"
7460                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7461                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7462                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7463                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7464                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7465                 "              OpLoopMerge %exit %phi None\n"
7466                 "              OpBranchConditional %still_loop %phi %exit\n"
7467
7468                 "%exit       = OpLabel\n"
7469                 "              OpStore %loc %accum\n"
7470                 "%ret        = OpLoad %v4f32 %result\n"
7471                 "              OpReturnValue %ret\n"
7472
7473                 "              OpFunctionEnd\n";
7474
7475         fragments2["pre_main"]  = typesAndConstants2;
7476         fragments2["testfun"]   = function2;
7477
7478         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7479         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7480         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7481         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7482
7483         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7484
7485         const char      typesAndConstants3[]    =
7486                 "%true      = OpConstantTrue %bool\n"
7487                 "%false     = OpConstantFalse %bool\n"
7488                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7489
7490         // Swap the second and the third element of the given parameter.
7491         const char      function3[]                             =
7492                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7493                 "%param     = OpFunctionParameter %v4f32\n"
7494                 "%entry     = OpLabel\n"
7495                 "%result    = OpVariable %fp_v4f32 Function\n"
7496                 "             OpStore %result %param\n"
7497                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7498                 "%a_init    = OpLoad %f32 %a_loc\n"
7499                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7500                 "%b_init    = OpLoad %f32 %b_loc\n"
7501                 "             OpBranch %phi\n"
7502
7503                 "%phi        = OpLabel\n"
7504                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7505                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7506                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7507                 "              OpLoopMerge %exit %phi None\n"
7508                 "              OpBranchConditional %still_loop %phi %exit\n"
7509
7510                 "%exit       = OpLabel\n"
7511                 "              OpStore %a_loc %a_next\n"
7512                 "              OpStore %b_loc %b_next\n"
7513                 "%ret        = OpLoad %v4f32 %result\n"
7514                 "              OpReturnValue %ret\n"
7515
7516                 "              OpFunctionEnd\n";
7517
7518         fragments3["pre_main"]  = typesAndConstants3;
7519         fragments3["testfun"]   = function3;
7520
7521         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7522         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7523         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7524         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7525
7526         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7527
7528         const char      typesAndConstants4[]    =
7529                 "%f16        = OpTypeFloat 16\n"
7530                 "%v4f16      = OpTypeVector %f16 4\n"
7531                 "%fp_f16     = OpTypePointer Function %f16\n"
7532                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7533                 "%true       = OpConstantTrue %bool\n"
7534                 "%false      = OpConstantFalse %bool\n"
7535                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7536
7537         // Swap the second and the third element of the given parameter.
7538         const char      function4[]                             =
7539                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7540                 "%param      = OpFunctionParameter %v4f32\n"
7541                 "%entry      = OpLabel\n"
7542                 "%result     = OpVariable %fp_v4f16 Function\n"
7543                 "%param16    = OpFConvert %v4f16 %param\n"
7544                 "              OpStore %result %param16\n"
7545                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7546                 "%a_init     = OpLoad %f16 %a_loc\n"
7547                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7548                 "%b_init     = OpLoad %f16 %b_loc\n"
7549                 "              OpBranch %phi\n"
7550
7551                 "%phi        = OpLabel\n"
7552                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7553                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7554                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7555                 "              OpLoopMerge %exit %phi None\n"
7556                 "              OpBranchConditional %still_loop %phi %exit\n"
7557
7558                 "%exit       = OpLabel\n"
7559                 "              OpStore %a_loc %a_next\n"
7560                 "              OpStore %b_loc %b_next\n"
7561                 "%ret16      = OpLoad %v4f16 %result\n"
7562                 "%ret        = OpFConvert %v4f32 %ret16\n"
7563                 "              OpReturnValue %ret\n"
7564
7565                 "              OpFunctionEnd\n";
7566
7567         fragments4["pre_main"]          = typesAndConstants4;
7568         fragments4["testfun"]           = function4;
7569         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7570         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7571
7572         extensions4.push_back("VK_KHR_16bit_storage");
7573         extensions4.push_back("VK_KHR_shader_float16_int8");
7574
7575         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7576         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7577
7578         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7579         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7580         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7581         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7582
7583         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7584
7585         return group.release();
7586 }
7587
7588 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7589 {
7590         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7591         RGBA                                                    inputColors[4];
7592         RGBA                                                    outputColors[4];
7593
7594         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7595         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7596         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7597         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7598         const char                                              constantsAndTypes[]      =
7599                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7600                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7601                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7602                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7603                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7604
7605         const char                                              function[]       =
7606                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7607                 "%param          = OpFunctionParameter %v4f32\n"
7608                 "%label          = OpLabel\n"
7609                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7610                 "%var2           = OpVariable %fp_f32 Function\n"
7611                 "%red            = OpCompositeExtract %f32 %param 0\n"
7612                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7613                 "                  OpStore %var2 %plus_red\n"
7614                 "%val1           = OpLoad %f32 %var1\n"
7615                 "%val2           = OpLoad %f32 %var2\n"
7616                 "%mul            = OpFMul %f32 %val1 %val2\n"
7617                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7618                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7619                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7620                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7621                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7622                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7623                 "                  OpReturnValue %ret\n"
7624                 "                  OpFunctionEnd\n";
7625
7626         struct CaseNameDecoration
7627         {
7628                 string name;
7629                 string decoration;
7630         };
7631
7632
7633         CaseNameDecoration tests[] = {
7634                 {"multiplication",      "OpDecorate %mul NoContraction"},
7635                 {"addition",            "OpDecorate %add NoContraction"},
7636                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7637         };
7638
7639         getHalfColorsFullAlpha(inputColors);
7640
7641         for (deUint8 idx = 0; idx < 4; ++idx)
7642         {
7643                 inputColors[idx].setRed(0);
7644                 outputColors[idx] = RGBA(0, 0, 0, 255);
7645         }
7646
7647         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7648         {
7649                 map<string, string> fragments;
7650
7651                 fragments["decoration"] = tests[testNdx].decoration;
7652                 fragments["pre_main"] = constantsAndTypes;
7653                 fragments["testfun"] = function;
7654
7655                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7656         }
7657
7658         return group.release();
7659 }
7660
7661 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7662 {
7663         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7664         RGBA                                                    colors[4];
7665
7666         const char                                              constantsAndTypes[]      =
7667                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7668                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7669                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7670                 "%fp_stype          = OpTypePointer Function %stype\n";
7671
7672         const char                                              function[]       =
7673                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7674                 "%param1            = OpFunctionParameter %v4f32\n"
7675                 "%lbl               = OpLabel\n"
7676                 "%v1                = OpVariable %fp_v4f32 Function\n"
7677                 "%v2                = OpVariable %fp_a2f32 Function\n"
7678                 "%v3                = OpVariable %fp_f32 Function\n"
7679                 "%v                 = OpVariable %fp_stype Function\n"
7680                 "%vv                = OpVariable %fp_stype Function\n"
7681                 "%vvv               = OpVariable %fp_f32 Function\n"
7682
7683                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7684                 "                     OpStore %v2 %c_a2f32_1\n"
7685                 "                     OpStore %v3 %c_f32_1\n"
7686
7687                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7688                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7689                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7690                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7691                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7692                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7693
7694                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7695                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7696                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7697
7698                 "                    OpCopyMemory %vv %v ${access_type}\n"
7699                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7700
7701                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7702                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7703                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7704
7705                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7706                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7707                 "                    OpReturnValue %ret2\n"
7708                 "                    OpFunctionEnd\n";
7709
7710         struct NameMemoryAccess
7711         {
7712                 string name;
7713                 string accessType;
7714         };
7715
7716
7717         NameMemoryAccess tests[] =
7718         {
7719                 { "none", "" },
7720                 { "volatile", "Volatile" },
7721                 { "aligned",  "Aligned 1" },
7722                 { "volatile_aligned",  "Volatile|Aligned 1" },
7723                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7724                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7725                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7726         };
7727
7728         getHalfColorsFullAlpha(colors);
7729
7730         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7731         {
7732                 map<string, string> fragments;
7733                 map<string, string> memoryAccess;
7734                 memoryAccess["access_type"] = tests[testNdx].accessType;
7735
7736                 fragments["pre_main"] = constantsAndTypes;
7737                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7738                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7739         }
7740         return memoryAccessTests.release();
7741 }
7742 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7743 {
7744         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7745         RGBA                                                            defaultColors[4];
7746         map<string, string>                                     fragments;
7747         getDefaultColors(defaultColors);
7748
7749         // First, simple cases that don't do anything with the OpUndef result.
7750         struct NameCodePair { string name, decl, type; };
7751         const NameCodePair tests[] =
7752         {
7753                 {"bool", "", "%bool"},
7754                 {"vec2uint32", "", "%v2u32"},
7755                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7756                 {"sampler", "%type = OpTypeSampler", "%type"},
7757                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7758                 {"pointer", "", "%fp_i32"},
7759                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7760                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7761                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7762         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7763         {
7764                 fragments["undef_type"] = tests[testNdx].type;
7765                 fragments["testfun"] = StringTemplate(
7766                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7767                         "%param1 = OpFunctionParameter %v4f32\n"
7768                         "%label_testfun = OpLabel\n"
7769                         "%undef = OpUndef ${undef_type}\n"
7770                         "OpReturnValue %param1\n"
7771                         "OpFunctionEnd\n").specialize(fragments);
7772                 fragments["pre_main"] = tests[testNdx].decl;
7773                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7774         }
7775         fragments.clear();
7776
7777         fragments["testfun"] =
7778                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7779                 "%param1 = OpFunctionParameter %v4f32\n"
7780                 "%label_testfun = OpLabel\n"
7781                 "%undef = OpUndef %f32\n"
7782                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7783                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7784                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7785                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7786                 "%b = OpFAdd %f32 %a %actually_zero\n"
7787                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7788                 "OpReturnValue %ret\n"
7789                 "OpFunctionEnd\n";
7790
7791         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7792
7793         fragments["testfun"] =
7794                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7795                 "%param1 = OpFunctionParameter %v4f32\n"
7796                 "%label_testfun = OpLabel\n"
7797                 "%undef = OpUndef %i32\n"
7798                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7799                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7800                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7801                 "OpReturnValue %ret\n"
7802                 "OpFunctionEnd\n";
7803
7804         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7805
7806         fragments["testfun"] =
7807                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7808                 "%param1 = OpFunctionParameter %v4f32\n"
7809                 "%label_testfun = OpLabel\n"
7810                 "%undef = OpUndef %u32\n"
7811                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7812                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7813                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7814                 "OpReturnValue %ret\n"
7815                 "OpFunctionEnd\n";
7816
7817         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7818
7819         fragments["testfun"] =
7820                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7821                 "%param1 = OpFunctionParameter %v4f32\n"
7822                 "%label_testfun = OpLabel\n"
7823                 "%undef = OpUndef %v4f32\n"
7824                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7825                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7826                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7827                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7828                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7829                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7830                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7831                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7832                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7833                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7834                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7835                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7836                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7837                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7838                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7839                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7840                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7841                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7842                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7843                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7844                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7845                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7846                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7847                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7848                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7849                 "OpReturnValue %ret\n"
7850                 "OpFunctionEnd\n";
7851
7852         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7853
7854         fragments["pre_main"] =
7855                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7856         fragments["testfun"] =
7857                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7858                 "%param1 = OpFunctionParameter %v4f32\n"
7859                 "%label_testfun = OpLabel\n"
7860                 "%undef = OpUndef %m2x2f32\n"
7861                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7862                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7863                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7864                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7865                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7866                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7867                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7868                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7869                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7870                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7871                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7872                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7873                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7874                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7875                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7876                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7877                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7878                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7879                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7880                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7881                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7882                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7883                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7884                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7885                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7886                 "OpReturnValue %ret\n"
7887                 "OpFunctionEnd\n";
7888
7889         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7890
7891         return opUndefTests.release();
7892 }
7893
7894 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7895 {
7896         const RGBA              inputColors[4]          =
7897         {
7898                 RGBA(0,         0,              0,              255),
7899                 RGBA(0,         0,              255,    255),
7900                 RGBA(0,         255,    0,              255),
7901                 RGBA(0,         255,    255,    255)
7902         };
7903
7904         const RGBA              expectedColors[4]       =
7905         {
7906                 RGBA(255,        0,              0,              255),
7907                 RGBA(255,        0,              0,              255),
7908                 RGBA(255,        0,              0,              255),
7909                 RGBA(255,        0,              0,              255)
7910         };
7911
7912         const struct SingleFP16Possibility
7913         {
7914                 const char* name;
7915                 const char* constant;  // Value to assign to %test_constant.
7916                 float           valueAsFloat;
7917                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7918         }                               tests[]                         =
7919         {
7920                 {
7921                         "negative",
7922                         "-0x1.3p1\n",
7923                         -constructNormalizedFloat(1, 0x300000),
7924                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7925                 }, // -19
7926                 {
7927                         "positive",
7928                         "0x1.0p7\n",
7929                         constructNormalizedFloat(7, 0x000000),
7930                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7931                 },  // +128
7932                 // SPIR-V requires that OpQuantizeToF16 flushes
7933                 // any numbers that would end up denormalized in F16 to zero.
7934                 {
7935                         "denorm",
7936                         "0x0.0006p-126\n",
7937                         std::ldexp(1.5f, -140),
7938                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7939                 },  // denorm
7940                 {
7941                         "negative_denorm",
7942                         "-0x0.0006p-126\n",
7943                         -std::ldexp(1.5f, -140),
7944                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7945                 }, // -denorm
7946                 {
7947                         "too_small",
7948                         "0x1.0p-16\n",
7949                         std::ldexp(1.0f, -16),
7950                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7951                 },     // too small positive
7952                 {
7953                         "negative_too_small",
7954                         "-0x1.0p-32\n",
7955                         -std::ldexp(1.0f, -32),
7956                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7957                 },      // too small negative
7958                 {
7959                         "negative_inf",
7960                         "-0x1.0p128\n",
7961                         -std::ldexp(1.0f, 128),
7962
7963                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7964                         "%inf = OpIsInf %bool %c\n"
7965                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7966                 },     // -inf to -inf
7967                 {
7968                         "inf",
7969                         "0x1.0p128\n",
7970                         std::ldexp(1.0f, 128),
7971
7972                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7973                         "%inf = OpIsInf %bool %c\n"
7974                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7975                 },     // +inf to +inf
7976                 {
7977                         "round_to_negative_inf",
7978                         "-0x1.0p32\n",
7979                         -std::ldexp(1.0f, 32),
7980
7981                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7982                         "%inf = OpIsInf %bool %c\n"
7983                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7984                 },     // round to -inf
7985                 {
7986                         "round_to_inf",
7987                         "0x1.0p16\n",
7988                         std::ldexp(1.0f, 16),
7989
7990                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7991                         "%inf = OpIsInf %bool %c\n"
7992                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7993                 },     // round to +inf
7994                 {
7995                         "nan",
7996                         "0x1.1p128\n",
7997                         std::numeric_limits<float>::quiet_NaN(),
7998
7999                         // Test for any NaN value, as NaNs are not preserved
8000                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8001                         "%cond = OpIsNan %bool %direct_quant\n"
8002                 }, // nan
8003                 {
8004                         "negative_nan",
8005                         "-0x1.0001p128\n",
8006                         std::numeric_limits<float>::quiet_NaN(),
8007
8008                         // Test for any NaN value, as NaNs are not preserved
8009                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8010                         "%cond = OpIsNan %bool %direct_quant\n"
8011                 } // -nan
8012         };
8013         const char*             constants                       =
8014                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
8015
8016         StringTemplate  function                        (
8017                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8018                 "%param1        = OpFunctionParameter %v4f32\n"
8019                 "%label_testfun = OpLabel\n"
8020                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8021                 "%b             = OpFAdd %f32 %test_constant %a\n"
8022                 "%c             = OpQuantizeToF16 %f32 %b\n"
8023                 "${condition}\n"
8024                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8025                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8026                 "                 OpReturnValue %retval\n"
8027                 "OpFunctionEnd\n"
8028         );
8029
8030         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
8031         const char*             specConstants           =
8032                         "%test_constant = OpSpecConstant %f32 0.\n"
8033                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
8034
8035         StringTemplate  specConstantFunction(
8036                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8037                 "%param1        = OpFunctionParameter %v4f32\n"
8038                 "%label_testfun = OpLabel\n"
8039                 "${condition}\n"
8040                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8041                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8042                 "                 OpReturnValue %retval\n"
8043                 "OpFunctionEnd\n"
8044         );
8045
8046         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8047         {
8048                 map<string, string>                                                             codeSpecialization;
8049                 map<string, string>                                                             fragments;
8050                 codeSpecialization["condition"]                                 = tests[idx].condition;
8051                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
8052                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
8053                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8054         }
8055
8056         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8057         {
8058                 map<string, string>                                                             codeSpecialization;
8059                 map<string, string>                                                             fragments;
8060                 SpecConstants                                                                   passConstants;
8061
8062                 codeSpecialization["condition"]                                 = tests[idx].condition;
8063                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
8064                 fragments["decoration"]                                                 = specDecorations;
8065                 fragments["pre_main"]                                                   = specConstants;
8066
8067                 passConstants.append<float>(tests[idx].valueAsFloat);
8068
8069                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8070         }
8071 }
8072
8073 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
8074 {
8075         RGBA inputColors[4] =  {
8076                 RGBA(0,         0,              0,              255),
8077                 RGBA(0,         0,              255,    255),
8078                 RGBA(0,         255,    0,              255),
8079                 RGBA(0,         255,    255,    255)
8080         };
8081
8082         RGBA expectedColors[4] =
8083         {
8084                 RGBA(255,        0,              0,              255),
8085                 RGBA(255,        0,              0,              255),
8086                 RGBA(255,        0,              0,              255),
8087                 RGBA(255,        0,              0,              255)
8088         };
8089
8090         struct DualFP16Possibility
8091         {
8092                 const char* name;
8093                 const char* input;
8094                 float           inputAsFloat;
8095                 const char* possibleOutput1;
8096                 const char* possibleOutput2;
8097         } tests[] = {
8098                 {
8099                         "positive_round_up_or_round_down",
8100                         "0x1.3003p8",
8101                         constructNormalizedFloat(8, 0x300300),
8102                         "0x1.304p8",
8103                         "0x1.3p8"
8104                 },
8105                 {
8106                         "negative_round_up_or_round_down",
8107                         "-0x1.6008p-7",
8108                         -constructNormalizedFloat(-7, 0x600800),
8109                         "-0x1.6p-7",
8110                         "-0x1.604p-7"
8111                 },
8112                 {
8113                         "carry_bit",
8114                         "0x1.01ep2",
8115                         constructNormalizedFloat(2, 0x01e000),
8116                         "0x1.01cp2",
8117                         "0x1.02p2"
8118                 },
8119                 {
8120                         "carry_to_exponent",
8121                         "0x1.ffep1",
8122                         constructNormalizedFloat(1, 0xffe000),
8123                         "0x1.ffcp1",
8124                         "0x1.0p2"
8125                 },
8126         };
8127         StringTemplate constants (
8128                 "%input_const = OpConstant %f32 ${input}\n"
8129                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8130                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8131                 );
8132
8133         StringTemplate specConstants (
8134                 "%input_const = OpSpecConstant %f32 0.\n"
8135                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8136                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8137         );
8138
8139         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8140
8141         const char* function  =
8142                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8143                 "%param1        = OpFunctionParameter %v4f32\n"
8144                 "%label_testfun = OpLabel\n"
8145                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8146                 // For the purposes of this test we assume that 0.f will always get
8147                 // faithfully passed through the pipeline stages.
8148                 "%b             = OpFAdd %f32 %input_const %a\n"
8149                 "%c             = OpQuantizeToF16 %f32 %b\n"
8150                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8151                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8152                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8153                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8154                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8155                 "                 OpReturnValue %retval\n"
8156                 "OpFunctionEnd\n";
8157
8158         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8159                 map<string, string>                                                                     fragments;
8160                 map<string, string>                                                                     constantSpecialization;
8161
8162                 constantSpecialization["input"]                                         = tests[idx].input;
8163                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8164                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8165                 fragments["testfun"]                                                            = function;
8166                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8167                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8168         }
8169
8170         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8171                 map<string, string>                                                                     fragments;
8172                 map<string, string>                                                                     constantSpecialization;
8173                 SpecConstants                                                                           passConstants;
8174
8175                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8176                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8177                 fragments["testfun"]                                                            = function;
8178                 fragments["decoration"]                                                         = specDecorations;
8179                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8180
8181                 passConstants.append<float>(tests[idx].inputAsFloat);
8182
8183                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8184         }
8185 }
8186
8187 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8188 {
8189         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8190         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8191         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8192         return opQuantizeTests.release();
8193 }
8194
8195 struct ShaderPermutation
8196 {
8197         deUint8 vertexPermutation;
8198         deUint8 geometryPermutation;
8199         deUint8 tesscPermutation;
8200         deUint8 tessePermutation;
8201         deUint8 fragmentPermutation;
8202 };
8203
8204 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8205 {
8206         ShaderPermutation       permutation =
8207         {
8208                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8209                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8210                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8211                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8212                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8213         };
8214         return permutation;
8215 }
8216
8217 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8218 {
8219         RGBA                                                            defaultColors[4];
8220         RGBA                                                            invertedColors[4];
8221         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8222
8223         getDefaultColors(defaultColors);
8224         getInvertedDefaultColors(invertedColors);
8225
8226         // Combined module tests
8227         {
8228                 // Shader stages: vertex and fragment
8229                 {
8230                         const ShaderElement combinedPipeline[]  =
8231                         {
8232                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8233                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8234                         };
8235
8236                         addFunctionCaseWithPrograms<InstanceContext>(
8237                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8238                                 createInstanceContext(combinedPipeline, map<string, string>()));
8239                 }
8240
8241                 // Shader stages: vertex, geometry and fragment
8242                 {
8243                         const ShaderElement combinedPipeline[]  =
8244                         {
8245                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8246                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8247                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8248                         };
8249
8250                         addFunctionCaseWithPrograms<InstanceContext>(
8251                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8252                                 createInstanceContext(combinedPipeline, map<string, string>()));
8253                 }
8254
8255                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8256                 {
8257                         const ShaderElement combinedPipeline[]  =
8258                         {
8259                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8260                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8261                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8262                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8263                         };
8264
8265                         addFunctionCaseWithPrograms<InstanceContext>(
8266                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8267                                 createInstanceContext(combinedPipeline, map<string, string>()));
8268                 }
8269
8270                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8271                 {
8272                         const ShaderElement combinedPipeline[]  =
8273                         {
8274                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8275                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8276                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8277                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8278                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8279                         };
8280
8281                         addFunctionCaseWithPrograms<InstanceContext>(
8282                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8283                                 createInstanceContext(combinedPipeline, map<string, string>()));
8284                 }
8285         }
8286
8287         const char* numbers[] =
8288         {
8289                 "1", "2"
8290         };
8291
8292         for (deInt8 idx = 0; idx < 32; ++idx)
8293         {
8294                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8295                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8296                 const ShaderElement                     pipeline[]              =
8297                 {
8298                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8299                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8300                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8301                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8302                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8303                 };
8304
8305                 // If there are an even number of swaps, then it should be no-op.
8306                 // If there are an odd number, the color should be flipped.
8307                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8308                 {
8309                         addFunctionCaseWithPrograms<InstanceContext>(
8310                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8311                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8312                 }
8313                 else
8314                 {
8315                         addFunctionCaseWithPrograms<InstanceContext>(
8316                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8317                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8318                 }
8319         }
8320         return moduleTests.release();
8321 }
8322
8323 std::string getUnusedVarTestNamePiece(const std::string& prefix, ShaderTask task)
8324 {
8325         switch (task)
8326         {
8327                 case SHADER_TASK_NONE:                  return "";
8328                 case SHADER_TASK_NORMAL:                return prefix + "_normal";
8329                 case SHADER_TASK_UNUSED_VAR:    return prefix + "_unused_var";
8330                 case SHADER_TASK_UNUSED_FUNC:   return prefix + "_unused_func";
8331                 default:                                                DE_ASSERT(DE_FALSE);
8332         }
8333         // unreachable
8334         return "";
8335 }
8336
8337 std::string getShaderTaskIndexName(ShaderTaskIndex index)
8338 {
8339         switch (index)
8340         {
8341         case SHADER_TASK_INDEX_VERTEX:                  return "vertex";
8342         case SHADER_TASK_INDEX_GEOMETRY:                return "geom";
8343         case SHADER_TASK_INDEX_TESS_CONTROL:    return "tessc";
8344         case SHADER_TASK_INDEX_TESS_EVAL:               return "tesse";
8345         case SHADER_TASK_INDEX_FRAGMENT:                return "frag";
8346         default:                                                                DE_ASSERT(DE_FALSE);
8347         }
8348         // unreachable
8349         return "";
8350 }
8351
8352 std::string getUnusedVarTestName(const ShaderTaskArray& shaderTasks, const VariableLocation& location)
8353 {
8354         std::string testName = location.toString();
8355
8356         for (size_t i = 0; i < DE_LENGTH_OF_ARRAY(shaderTasks); ++i)
8357         {
8358                 if (shaderTasks[i] != SHADER_TASK_NONE)
8359                 {
8360                         testName += "_" + getUnusedVarTestNamePiece(getShaderTaskIndexName((ShaderTaskIndex)i), shaderTasks[i]);
8361                 }
8362         }
8363
8364         return testName;
8365 }
8366
8367 tcu::TestCaseGroup* createUnusedVariableTests(tcu::TestContext& testCtx)
8368 {
8369         de::MovePtr<tcu::TestCaseGroup>         moduleTests                             (new tcu::TestCaseGroup(testCtx, "unused_variables", "Graphics shaders with unused variables"));
8370
8371         ShaderTaskArray                                         shaderCombinations[]    =
8372         {
8373                 // Vertex                                       Geometry                                        Tess. Control                           Tess. Evaluation                        Fragment
8374                 { SHADER_TASK_UNUSED_VAR,       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8375                 { SHADER_TASK_UNUSED_FUNC,      SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8376                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR  },
8377                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC },
8378                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8379                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8380                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8381                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8382                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL      },
8383                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL      }
8384         };
8385
8386         const VariableLocation                          testLocations[] =
8387         {
8388                 // Set          Binding
8389                 { 0,            5                       },
8390                 { 5,            5                       },
8391         };
8392
8393         for (size_t combNdx = 0; combNdx < DE_LENGTH_OF_ARRAY(shaderCombinations); ++combNdx)
8394         {
8395                 for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
8396                 {
8397                         const ShaderTaskArray&  shaderTasks             = shaderCombinations[combNdx];
8398                         const VariableLocation& location                = testLocations[locationNdx];
8399                         std::string                             testName                = getUnusedVarTestName(shaderTasks, location);
8400
8401                         addFunctionCaseWithPrograms<UnusedVariableContext>(
8402                                 moduleTests.get(), testName, "", createUnusedVariableModules, runAndVerifyUnusedVariablePipeline,
8403                                 createUnusedVariableContext(shaderTasks, location));
8404                 }
8405         }
8406
8407         return moduleTests.release();
8408 }
8409
8410 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8411 {
8412         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8413         RGBA defaultColors[4];
8414         getDefaultColors(defaultColors);
8415         map<string, string> fragments;
8416         fragments["pre_main"] =
8417                 "%c_f32_5 = OpConstant %f32 5.\n";
8418
8419         // A loop with a single block. The Continue Target is the loop block
8420         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8421         // -- the "continue construct" forms the entire loop.
8422         fragments["testfun"] =
8423                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8424                 "%param1 = OpFunctionParameter %v4f32\n"
8425
8426                 "%entry = OpLabel\n"
8427                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8428                 "OpBranch %loop\n"
8429
8430                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8431                 "%loop = OpLabel\n"
8432                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8433                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8434                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8435                 "%val = OpFAdd %f32 %val1 %delta\n"
8436                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8437                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8438                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8439                 "OpLoopMerge %exit %loop None\n"
8440                 "OpBranchConditional %again %loop %exit\n"
8441
8442                 "%exit = OpLabel\n"
8443                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8444                 "OpReturnValue %result\n"
8445
8446                 "OpFunctionEnd\n";
8447
8448         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8449
8450         // Body comprised of multiple basic blocks.
8451         const StringTemplate multiBlock(
8452                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8453                 "%param1 = OpFunctionParameter %v4f32\n"
8454
8455                 "%entry = OpLabel\n"
8456                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8457                 "OpBranch %loop\n"
8458
8459                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8460                 "%loop = OpLabel\n"
8461                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8462                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8463                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8464                 // There are several possibilities for the Continue Target below.  Each
8465                 // will be specialized into a separate test case.
8466                 "OpLoopMerge %exit ${continue_target} None\n"
8467                 "OpBranch %if\n"
8468
8469                 "%if = OpLabel\n"
8470                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8471                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8472                 "OpSelectionMerge %gather DontFlatten\n"
8473                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8474
8475                 "%odd = OpLabel\n"
8476                 "OpBranch %gather\n"
8477
8478                 "%even = OpLabel\n"
8479                 "OpBranch %gather\n"
8480
8481                 "%gather = OpLabel\n"
8482                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8483                 "%val = OpFAdd %f32 %val1 %delta\n"
8484                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8485                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8486                 "OpBranchConditional %again %loop %exit\n"
8487
8488                 "%exit = OpLabel\n"
8489                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8490                 "OpReturnValue %result\n"
8491
8492                 "OpFunctionEnd\n");
8493
8494         map<string, string> continue_target;
8495
8496         // The Continue Target is the loop block itself.
8497         continue_target["continue_target"] = "%loop";
8498         fragments["testfun"] = multiBlock.specialize(continue_target);
8499         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8500
8501         // The Continue Target is at the end of the loop.
8502         continue_target["continue_target"] = "%gather";
8503         fragments["testfun"] = multiBlock.specialize(continue_target);
8504         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8505
8506         // A loop with continue statement.
8507         fragments["testfun"] =
8508                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8509                 "%param1 = OpFunctionParameter %v4f32\n"
8510
8511                 "%entry = OpLabel\n"
8512                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8513                 "OpBranch %loop\n"
8514
8515                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8516                 "%loop = OpLabel\n"
8517                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8518                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8519                 "OpLoopMerge %exit %continue None\n"
8520                 "OpBranch %if\n"
8521
8522                 "%if = OpLabel\n"
8523                 ";skip if %count==2\n"
8524                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8525                 "OpSelectionMerge %continue DontFlatten\n"
8526                 "OpBranchConditional %eq2 %continue %body\n"
8527
8528                 "%body = OpLabel\n"
8529                 "%fcount = OpConvertSToF %f32 %count\n"
8530                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8531                 "OpBranch %continue\n"
8532
8533                 "%continue = OpLabel\n"
8534                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8535                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8536                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8537                 "OpBranchConditional %again %loop %exit\n"
8538
8539                 "%exit = OpLabel\n"
8540                 "%same = OpFSub %f32 %val %c_f32_8\n"
8541                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8542                 "OpReturnValue %result\n"
8543                 "OpFunctionEnd\n";
8544         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8545
8546         // A loop with break.
8547         fragments["testfun"] =
8548                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8549                 "%param1 = OpFunctionParameter %v4f32\n"
8550
8551                 "%entry = OpLabel\n"
8552                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8553                 "%dot = OpDot %f32 %param1 %param1\n"
8554                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8555                 "%zero = OpConvertFToU %u32 %div\n"
8556                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8557                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8558                 "OpBranch %loop\n"
8559
8560                 ";adds 4 and 3 to %val0 (exits early)\n"
8561                 "%loop = OpLabel\n"
8562                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8563                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8564                 "OpLoopMerge %exit %continue None\n"
8565                 "OpBranch %if\n"
8566
8567                 "%if = OpLabel\n"
8568                 ";end loop if %count==%two\n"
8569                 "%above2 = OpSGreaterThan %bool %count %two\n"
8570                 "OpSelectionMerge %continue DontFlatten\n"
8571                 "OpBranchConditional %above2 %body %exit\n"
8572
8573                 "%body = OpLabel\n"
8574                 "%fcount = OpConvertSToF %f32 %count\n"
8575                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8576                 "OpBranch %continue\n"
8577
8578                 "%continue = OpLabel\n"
8579                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8580                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8581                 "OpBranchConditional %again %loop %exit\n"
8582
8583                 "%exit = OpLabel\n"
8584                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8585                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8586                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8587                 "OpReturnValue %result\n"
8588                 "OpFunctionEnd\n";
8589         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8590
8591         // A loop with return.
8592         fragments["testfun"] =
8593                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8594                 "%param1 = OpFunctionParameter %v4f32\n"
8595
8596                 "%entry = OpLabel\n"
8597                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8598                 "%dot = OpDot %f32 %param1 %param1\n"
8599                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8600                 "%zero = OpConvertFToU %u32 %div\n"
8601                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8602                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8603                 "OpBranch %loop\n"
8604
8605                 ";returns early without modifying %param1\n"
8606                 "%loop = OpLabel\n"
8607                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8608                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8609                 "OpLoopMerge %exit %continue None\n"
8610                 "OpBranch %if\n"
8611
8612                 "%if = OpLabel\n"
8613                 ";return if %count==%two\n"
8614                 "%above2 = OpSGreaterThan %bool %count %two\n"
8615                 "OpSelectionMerge %continue DontFlatten\n"
8616                 "OpBranchConditional %above2 %body %early_exit\n"
8617
8618                 "%early_exit = OpLabel\n"
8619                 "OpReturnValue %param1\n"
8620
8621                 "%body = OpLabel\n"
8622                 "%fcount = OpConvertSToF %f32 %count\n"
8623                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8624                 "OpBranch %continue\n"
8625
8626                 "%continue = OpLabel\n"
8627                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8628                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8629                 "OpBranchConditional %again %loop %exit\n"
8630
8631                 "%exit = OpLabel\n"
8632                 ";should never get here, so return an incorrect result\n"
8633                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8634                 "OpReturnValue %result\n"
8635                 "OpFunctionEnd\n";
8636         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8637
8638         // Continue inside a switch block to break to enclosing loop's merge block.
8639         // Matches roughly the following GLSL code:
8640         // for (; keep_going; keep_going = false)
8641         // {
8642         //     switch (int(param1.x))
8643         //     {
8644         //         case 0: continue;
8645         //         case 1: continue;
8646         //         default: continue;
8647         //     }
8648         //     dead code: modify return value to invalid result.
8649         // }
8650         fragments["pre_main"] =
8651                 "%fp_bool = OpTypePointer Function %bool\n"
8652                 "%true = OpConstantTrue %bool\n"
8653                 "%false = OpConstantFalse %bool\n";
8654
8655         fragments["testfun"] =
8656                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8657                 "%param1 = OpFunctionParameter %v4f32\n"
8658
8659                 "%entry = OpLabel\n"
8660                 "%keep_going = OpVariable %fp_bool Function\n"
8661                 "%val_ptr = OpVariable %fp_f32 Function\n"
8662                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8663                 "OpStore %keep_going %true\n"
8664                 "OpBranch %forloop_begin\n"
8665
8666                 "%forloop_begin = OpLabel\n"
8667                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8668                 "OpBranch %forloop\n"
8669
8670                 "%forloop = OpLabel\n"
8671                 "%for_condition = OpLoad %bool %keep_going\n"
8672                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8673
8674                 "%forloop_body = OpLabel\n"
8675                 "OpStore %val_ptr %param1_x\n"
8676                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8677
8678                 "OpSelectionMerge %switch_merge None\n"
8679                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8680                 "%case_0 = OpLabel\n"
8681                 "OpBranch %forloop_continue\n"
8682                 "%case_1 = OpLabel\n"
8683                 "OpBranch %forloop_continue\n"
8684                 "%default = OpLabel\n"
8685                 "OpBranch %forloop_continue\n"
8686                 "%switch_merge = OpLabel\n"
8687                 ";should never get here, so change the return value to invalid result\n"
8688                 "OpStore %val_ptr %c_f32_1\n"
8689                 "OpBranch %forloop_continue\n"
8690
8691                 "%forloop_continue = OpLabel\n"
8692                 "OpStore %keep_going %false\n"
8693                 "OpBranch %forloop_begin\n"
8694                 "%forloop_merge = OpLabel\n"
8695
8696                 "%val = OpLoad %f32 %val_ptr\n"
8697                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8698                 "OpReturnValue %result\n"
8699                 "OpFunctionEnd\n";
8700         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8701
8702         return testGroup.release();
8703 }
8704
8705 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8706 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8707 {
8708         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8709         map<string, string> fragments;
8710
8711         // A barrier inside a function body.
8712         fragments["pre_main"] =
8713                 "%Workgroup = OpConstant %i32 2\n"
8714                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8715         fragments["testfun"] =
8716                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8717                 "%param1 = OpFunctionParameter %v4f32\n"
8718                 "%label_testfun = OpLabel\n"
8719                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8720                 "OpReturnValue %param1\n"
8721                 "OpFunctionEnd\n";
8722         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8723
8724         // Common setup code for the following tests.
8725         fragments["pre_main"] =
8726                 "%Workgroup = OpConstant %i32 2\n"
8727                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8728                 "%c_f32_5 = OpConstant %f32 5.\n";
8729         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8730                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8731                 "%param1 = OpFunctionParameter %v4f32\n"
8732                 "%entry = OpLabel\n"
8733                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8734                 "%dot = OpDot %f32 %param1 %param1\n"
8735                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8736                 "%zero = OpConvertFToU %u32 %div\n";
8737
8738         // Barriers inside OpSwitch branches.
8739         fragments["testfun"] =
8740                 setupPercentZero +
8741                 "OpSelectionMerge %switch_exit None\n"
8742                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8743
8744                 "%case1 = OpLabel\n"
8745                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8746                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8747                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8748                 "OpBranch %switch_exit\n"
8749
8750                 "%switch_default = OpLabel\n"
8751                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8752                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8753                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8754                 "OpBranch %switch_exit\n"
8755
8756                 "%case0 = OpLabel\n"
8757                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8758                 "OpBranch %switch_exit\n"
8759
8760                 "%switch_exit = OpLabel\n"
8761                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8762                 "OpReturnValue %ret\n"
8763                 "OpFunctionEnd\n";
8764         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8765
8766         // Barriers inside if-then-else.
8767         fragments["testfun"] =
8768                 setupPercentZero +
8769                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8770                 "OpSelectionMerge %exit DontFlatten\n"
8771                 "OpBranchConditional %eq0 %then %else\n"
8772
8773                 "%else = OpLabel\n"
8774                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8775                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8776                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8777                 "OpBranch %exit\n"
8778
8779                 "%then = OpLabel\n"
8780                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8781                 "OpBranch %exit\n"
8782                 "%exit = OpLabel\n"
8783                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8784                 "OpReturnValue %ret\n"
8785                 "OpFunctionEnd\n";
8786         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8787
8788         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8789         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8790         fragments["testfun"] =
8791                 setupPercentZero +
8792                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8793                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8794                 "OpSelectionMerge %exit DontFlatten\n"
8795                 "OpBranchConditional %thread0 %then %else\n"
8796
8797                 "%else = OpLabel\n"
8798                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8799                 "OpBranch %exit\n"
8800
8801                 "%then = OpLabel\n"
8802                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8803                 "OpBranch %exit\n"
8804
8805                 "%exit = OpLabel\n"
8806                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8807                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8808                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8809                 "OpReturnValue %ret\n"
8810                 "OpFunctionEnd\n";
8811         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8812
8813         // A barrier inside a loop.
8814         fragments["pre_main"] =
8815                 "%Workgroup = OpConstant %i32 2\n"
8816                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8817                 "%c_f32_10 = OpConstant %f32 10.\n";
8818         fragments["testfun"] =
8819                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8820                 "%param1 = OpFunctionParameter %v4f32\n"
8821                 "%entry = OpLabel\n"
8822                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8823                 "OpBranch %loop\n"
8824
8825                 ";adds 4, 3, 2, and 1 to %val0\n"
8826                 "%loop = OpLabel\n"
8827                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8828                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8829                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8830                 "%fcount = OpConvertSToF %f32 %count\n"
8831                 "%val = OpFAdd %f32 %val1 %fcount\n"
8832                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8833                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8834                 "OpLoopMerge %exit %loop None\n"
8835                 "OpBranchConditional %again %loop %exit\n"
8836
8837                 "%exit = OpLabel\n"
8838                 "%same = OpFSub %f32 %val %c_f32_10\n"
8839                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8840                 "OpReturnValue %ret\n"
8841                 "OpFunctionEnd\n";
8842         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8843
8844         return testGroup.release();
8845 }
8846
8847 // Test for the OpFRem instruction.
8848 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8849 {
8850         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8851         map<string, string>                                     fragments;
8852         RGBA                                                            inputColors[4];
8853         RGBA                                                            outputColors[4];
8854
8855         fragments["pre_main"]                            =
8856                 "%c_f32_3 = OpConstant %f32 3.0\n"
8857                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8858                 "%c_f32_4 = OpConstant %f32 4.0\n"
8859                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8860                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8861                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8862                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8863
8864         // The test does the following.
8865         // vec4 result = (param1 * 8.0) - 4.0;
8866         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8867         fragments["testfun"]                             =
8868                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8869                 "%param1 = OpFunctionParameter %v4f32\n"
8870                 "%label_testfun = OpLabel\n"
8871                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8872                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8873                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8874                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8875                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8876                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8877                 "OpReturnValue %xy_0_1\n"
8878                 "OpFunctionEnd\n";
8879
8880
8881         inputColors[0]          = RGBA(16,      16,             0, 255);
8882         inputColors[1]          = RGBA(232, 232,        0, 255);
8883         inputColors[2]          = RGBA(232, 16,         0, 255);
8884         inputColors[3]          = RGBA(16,      232,    0, 255);
8885
8886         outputColors[0]         = RGBA(64,      64,             0, 255);
8887         outputColors[1]         = RGBA(255, 255,        0, 255);
8888         outputColors[2]         = RGBA(255, 64,         0, 255);
8889         outputColors[3]         = RGBA(64,      255,    0, 255);
8890
8891         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8892         return testGroup.release();
8893 }
8894
8895 // Test for the OpSRem instruction.
8896 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8897 {
8898         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8899         map<string, string>                                     fragments;
8900
8901         fragments["pre_main"]                            =
8902                 "%c_f32_255 = OpConstant %f32 255.0\n"
8903                 "%c_i32_128 = OpConstant %i32 128\n"
8904                 "%c_i32_255 = OpConstant %i32 255\n"
8905                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8906                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8907                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8908
8909         // The test does the following.
8910         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8911         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8912         // return float(result + 128) / 255.0;
8913         fragments["testfun"]                             =
8914                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8915                 "%param1 = OpFunctionParameter %v4f32\n"
8916                 "%label_testfun = OpLabel\n"
8917                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8918                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8919                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8920                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8921                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8922                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8923                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8924                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8925                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8926                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8927                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8928                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8929                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8930                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8931                 "OpReturnValue %float_out\n"
8932                 "OpFunctionEnd\n";
8933
8934         const struct CaseParams
8935         {
8936                 const char*             name;
8937                 const char*             failMessageTemplate;    // customized status message
8938                 qpTestResult    failResult;                             // override status on failure
8939                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8940                 int                             results[4][3];                  // four (x, y, z) vectors of results
8941         } cases[] =
8942         {
8943                 {
8944                         "positive",
8945                         "${reason}",
8946                         QP_TEST_RESULT_FAIL,
8947                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8948                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8949                 },
8950                 {
8951                         "all",
8952                         "Inconsistent results, but within specification: ${reason}",
8953                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8954                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8955                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8956                 },
8957         };
8958         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8959
8960         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8961         {
8962                 const CaseParams&       params                  = cases[caseNdx];
8963                 RGBA                            inputColors[4];
8964                 RGBA                            outputColors[4];
8965
8966                 for (int i = 0; i < 4; ++i)
8967                 {
8968                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8969                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8970                 }
8971
8972                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8973         }
8974
8975         return testGroup.release();
8976 }
8977
8978 // Test for the OpSMod instruction.
8979 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8980 {
8981         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8982         map<string, string>                                     fragments;
8983
8984         fragments["pre_main"]                            =
8985                 "%c_f32_255 = OpConstant %f32 255.0\n"
8986                 "%c_i32_128 = OpConstant %i32 128\n"
8987                 "%c_i32_255 = OpConstant %i32 255\n"
8988                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8989                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8990                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8991
8992         // The test does the following.
8993         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8994         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8995         // return float(result + 128) / 255.0;
8996         fragments["testfun"]                             =
8997                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8998                 "%param1 = OpFunctionParameter %v4f32\n"
8999                 "%label_testfun = OpLabel\n"
9000                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
9001                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
9002                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
9003                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
9004                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
9005                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
9006                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
9007                 "%x_out = OpSMod %i32 %x_in %y_in\n"
9008                 "%y_out = OpSMod %i32 %y_in %z_in\n"
9009                 "%z_out = OpSMod %i32 %z_in %x_in\n"
9010                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
9011                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
9012                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
9013                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
9014                 "OpReturnValue %float_out\n"
9015                 "OpFunctionEnd\n";
9016
9017         const struct CaseParams
9018         {
9019                 const char*             name;
9020                 const char*             failMessageTemplate;    // customized status message
9021                 qpTestResult    failResult;                             // override status on failure
9022                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
9023                 int                             results[4][3];                  // four (x, y, z) vectors of results
9024         } cases[] =
9025         {
9026                 {
9027                         "positive",
9028                         "${reason}",
9029                         QP_TEST_RESULT_FAIL,
9030                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
9031                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
9032                 },
9033                 {
9034                         "all",
9035                         "Inconsistent results, but within specification: ${reason}",
9036                         negFailResult,                                                                                                                          // negative operands, not required by the spec
9037                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
9038                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
9039                 },
9040         };
9041         // If either operand is negative the result is undefined. Some implementations may still return correct values.
9042
9043         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
9044         {
9045                 const CaseParams&       params                  = cases[caseNdx];
9046                 RGBA                            inputColors[4];
9047                 RGBA                            outputColors[4];
9048
9049                 for (int i = 0; i < 4; ++i)
9050                 {
9051                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
9052                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
9053                 }
9054
9055                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
9056         }
9057         return testGroup.release();
9058 }
9059
9060 enum ConversionDataType
9061 {
9062         DATA_TYPE_SIGNED_8,
9063         DATA_TYPE_SIGNED_16,
9064         DATA_TYPE_SIGNED_32,
9065         DATA_TYPE_SIGNED_64,
9066         DATA_TYPE_UNSIGNED_8,
9067         DATA_TYPE_UNSIGNED_16,
9068         DATA_TYPE_UNSIGNED_32,
9069         DATA_TYPE_UNSIGNED_64,
9070         DATA_TYPE_FLOAT_16,
9071         DATA_TYPE_FLOAT_32,
9072         DATA_TYPE_FLOAT_64,
9073         DATA_TYPE_VEC2_SIGNED_16,
9074         DATA_TYPE_VEC2_SIGNED_32
9075 };
9076
9077 const string getBitWidthStr (ConversionDataType type)
9078 {
9079         switch (type)
9080         {
9081                 case DATA_TYPE_SIGNED_8:
9082                 case DATA_TYPE_UNSIGNED_8:
9083                         return "8";
9084
9085                 case DATA_TYPE_SIGNED_16:
9086                 case DATA_TYPE_UNSIGNED_16:
9087                 case DATA_TYPE_FLOAT_16:
9088                         return "16";
9089
9090                 case DATA_TYPE_SIGNED_32:
9091                 case DATA_TYPE_UNSIGNED_32:
9092                 case DATA_TYPE_FLOAT_32:
9093                 case DATA_TYPE_VEC2_SIGNED_16:
9094                         return "32";
9095
9096                 case DATA_TYPE_SIGNED_64:
9097                 case DATA_TYPE_UNSIGNED_64:
9098                 case DATA_TYPE_FLOAT_64:
9099                 case DATA_TYPE_VEC2_SIGNED_32:
9100                         return "64";
9101
9102                 default:
9103                         DE_ASSERT(false);
9104         }
9105         return "";
9106 }
9107
9108 const string getByteWidthStr (ConversionDataType type)
9109 {
9110         switch (type)
9111         {
9112                 case DATA_TYPE_SIGNED_8:
9113                 case DATA_TYPE_UNSIGNED_8:
9114                         return "1";
9115
9116                 case DATA_TYPE_SIGNED_16:
9117                 case DATA_TYPE_UNSIGNED_16:
9118                 case DATA_TYPE_FLOAT_16:
9119                         return "2";
9120
9121                 case DATA_TYPE_SIGNED_32:
9122                 case DATA_TYPE_UNSIGNED_32:
9123                 case DATA_TYPE_FLOAT_32:
9124                 case DATA_TYPE_VEC2_SIGNED_16:
9125                         return "4";
9126
9127                 case DATA_TYPE_SIGNED_64:
9128                 case DATA_TYPE_UNSIGNED_64:
9129                 case DATA_TYPE_FLOAT_64:
9130                 case DATA_TYPE_VEC2_SIGNED_32:
9131                         return "8";
9132
9133                 default:
9134                         DE_ASSERT(false);
9135         }
9136         return "";
9137 }
9138
9139 bool isSigned (ConversionDataType type)
9140 {
9141         switch (type)
9142         {
9143                 case DATA_TYPE_SIGNED_8:
9144                 case DATA_TYPE_SIGNED_16:
9145                 case DATA_TYPE_SIGNED_32:
9146                 case DATA_TYPE_SIGNED_64:
9147                 case DATA_TYPE_FLOAT_16:
9148                 case DATA_TYPE_FLOAT_32:
9149                 case DATA_TYPE_FLOAT_64:
9150                 case DATA_TYPE_VEC2_SIGNED_16:
9151                 case DATA_TYPE_VEC2_SIGNED_32:
9152                         return true;
9153
9154                 case DATA_TYPE_UNSIGNED_8:
9155                 case DATA_TYPE_UNSIGNED_16:
9156                 case DATA_TYPE_UNSIGNED_32:
9157                 case DATA_TYPE_UNSIGNED_64:
9158                         return false;
9159
9160                 default:
9161                         DE_ASSERT(false);
9162         }
9163         return false;
9164 }
9165
9166 bool isInt (ConversionDataType type)
9167 {
9168         switch (type)
9169         {
9170                 case DATA_TYPE_SIGNED_8:
9171                 case DATA_TYPE_SIGNED_16:
9172                 case DATA_TYPE_SIGNED_32:
9173                 case DATA_TYPE_SIGNED_64:
9174                 case DATA_TYPE_UNSIGNED_8:
9175                 case DATA_TYPE_UNSIGNED_16:
9176                 case DATA_TYPE_UNSIGNED_32:
9177                 case DATA_TYPE_UNSIGNED_64:
9178                         return true;
9179
9180                 case DATA_TYPE_FLOAT_16:
9181                 case DATA_TYPE_FLOAT_32:
9182                 case DATA_TYPE_FLOAT_64:
9183                 case DATA_TYPE_VEC2_SIGNED_16:
9184                 case DATA_TYPE_VEC2_SIGNED_32:
9185                         return false;
9186
9187                 default:
9188                         DE_ASSERT(false);
9189         }
9190         return false;
9191 }
9192
9193 bool isFloat (ConversionDataType type)
9194 {
9195         switch (type)
9196         {
9197                 case DATA_TYPE_SIGNED_8:
9198                 case DATA_TYPE_SIGNED_16:
9199                 case DATA_TYPE_SIGNED_32:
9200                 case DATA_TYPE_SIGNED_64:
9201                 case DATA_TYPE_UNSIGNED_8:
9202                 case DATA_TYPE_UNSIGNED_16:
9203                 case DATA_TYPE_UNSIGNED_32:
9204                 case DATA_TYPE_UNSIGNED_64:
9205                 case DATA_TYPE_VEC2_SIGNED_16:
9206                 case DATA_TYPE_VEC2_SIGNED_32:
9207                         return false;
9208
9209                 case DATA_TYPE_FLOAT_16:
9210                 case DATA_TYPE_FLOAT_32:
9211                 case DATA_TYPE_FLOAT_64:
9212                         return true;
9213
9214                 default:
9215                         DE_ASSERT(false);
9216         }
9217         return false;
9218 }
9219
9220 const string getTypeName (ConversionDataType type)
9221 {
9222         string prefix = isSigned(type) ? "" : "u";
9223
9224         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9225         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9226         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9227         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9228         else                                                                            DE_ASSERT(false);
9229
9230         return "";
9231 }
9232
9233 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9234 {
9235         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9236
9237         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9238 }
9239
9240 const string getAsmTypeName (ConversionDataType type)
9241 {
9242         string prefix;
9243
9244         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9245         else if (isFloat(type))                                         prefix = "f";
9246         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9247         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9248         else                                                                            DE_ASSERT(false);
9249
9250         return prefix + getBitWidthStr(type);
9251 }
9252
9253 template<typename T>
9254 BufferSp getSpecializedBuffer (deInt64 number)
9255 {
9256         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9257 }
9258
9259 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9260 {
9261         switch (type)
9262         {
9263                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9264                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9265                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9266                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9267                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9268                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9269                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9270                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9271                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9272                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9273                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9274                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9275                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9276
9277                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9278         }
9279 }
9280
9281 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9282 {
9283         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9284                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9285 }
9286
9287 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9288 {
9289         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9290                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9291                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9292 }
9293
9294 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9295 {
9296         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9297                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9298                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9299 }
9300
9301 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9302 {
9303         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9304                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9305 }
9306
9307 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9308 {
9309         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9310 }
9311
9312 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9313 {
9314         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9315 }
9316
9317 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9318 {
9319         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9320 }
9321
9322 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9323 {
9324         if (usesInt16(from, to) && !usesInt32(from, to))
9325                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9326
9327         if (usesInt64(from, to))
9328                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9329
9330         if (usesFloat64(from, to))
9331                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9332
9333         if (usesInt16(from, to) || usesFloat16(from, to))
9334         {
9335                 extensions.push_back("VK_KHR_16bit_storage");
9336                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9337         }
9338
9339         if (usesFloat16(from, to) || usesInt8(from, to))
9340         {
9341                 extensions.push_back("VK_KHR_shader_float16_int8");
9342
9343                 if (usesFloat16(from, to))
9344                 {
9345                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9346                 }
9347
9348                 if (usesInt8(from, to))
9349                 {
9350                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9351
9352                         extensions.push_back("VK_KHR_8bit_storage");
9353                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9354                 }
9355         }
9356 }
9357
9358 struct ConvertCase
9359 {
9360         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9361         : m_fromType            (from)
9362         , m_toType                      (to)
9363         , m_name                        (getTestName(from, to, suffix))
9364         , m_inputBuffer         (getBuffer(from, number))
9365         {
9366                 string caps;
9367                 string decl;
9368                 string exts;
9369
9370                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9371                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9372
9373                 if (separateOutput)
9374                         m_outputBuffer = getBuffer(to, outputNumber);
9375                 else
9376                         m_outputBuffer = getBuffer(to, number);
9377
9378                 if (usesInt8(from, to))
9379                 {
9380                         bool requiresInt8Capability = true;
9381                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9382                         {
9383                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9384                                 if (usesInt32(from, to))
9385                                         requiresInt8Capability = false;
9386                         }
9387
9388                         caps += "OpCapability StorageBuffer8BitAccess\n";
9389                         if (requiresInt8Capability)
9390                                 caps += "OpCapability Int8\n";
9391
9392                         decl += "%i8         = OpTypeInt 8 1\n"
9393                                         "%u8         = OpTypeInt 8 0\n";
9394                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9395                 }
9396
9397                 if (usesInt16(from, to))
9398                 {
9399                         bool requiresInt16Capability = true;
9400
9401                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9402                         {
9403                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9404                                 if (usesInt32(from, to) || usesFloat32(from, to))
9405                                         requiresInt16Capability = false;
9406                         }
9407
9408                         decl += "%i16        = OpTypeInt 16 1\n"
9409                                         "%u16        = OpTypeInt 16 0\n"
9410                                         "%i16vec2    = OpTypeVector %i16 2\n";
9411
9412                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9413                         if (requiresInt16Capability)
9414                                 caps += "OpCapability Int16\n";
9415                 }
9416
9417                 if (usesFloat16(from, to))
9418                 {
9419                         decl += "%f16        = OpTypeFloat 16\n";
9420
9421                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9422                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9423                                 caps += "OpCapability Float16\n";
9424                 }
9425
9426                 if (usesInt16(from, to) || usesFloat16(from, to))
9427                 {
9428                         caps += "OpCapability StorageUniformBufferBlock16\n";
9429                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9430                 }
9431
9432                 if (usesInt64(from, to))
9433                 {
9434                         caps += "OpCapability Int64\n";
9435                         decl += "%i64        = OpTypeInt 64 1\n"
9436                                         "%u64        = OpTypeInt 64 0\n";
9437                 }
9438
9439                 if (usesFloat64(from, to))
9440                 {
9441                         caps += "OpCapability Float64\n";
9442                         decl += "%f64        = OpTypeFloat 64\n";
9443                 }
9444
9445                 m_asmTypes["datatype_capabilities"]             = caps;
9446                 m_asmTypes["datatype_additional_decl"]  = decl;
9447                 m_asmTypes["datatype_extensions"]               = exts;
9448         }
9449
9450         ConversionDataType              m_fromType;
9451         ConversionDataType              m_toType;
9452         string                                  m_name;
9453         map<string, string>             m_asmTypes;
9454         BufferSp                                m_inputBuffer;
9455         BufferSp                                m_outputBuffer;
9456 };
9457
9458 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9459 {
9460         map<string, string> params = convertCase.m_asmTypes;
9461
9462         params["instruction"]   = instruction;
9463         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9464         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9465
9466         const StringTemplate shader (
9467                 "OpCapability Shader\n"
9468                 "${datatype_capabilities}"
9469                 "${datatype_extensions:opt}"
9470                 "OpMemoryModel Logical GLSL450\n"
9471                 "OpEntryPoint GLCompute %main \"main\"\n"
9472                 "OpExecutionMode %main LocalSize 1 1 1\n"
9473                 "OpSource GLSL 430\n"
9474                 "OpName %main           \"main\"\n"
9475                 // Decorators
9476                 "OpDecorate %indata DescriptorSet 0\n"
9477                 "OpDecorate %indata Binding 0\n"
9478                 "OpDecorate %outdata DescriptorSet 0\n"
9479                 "OpDecorate %outdata Binding 1\n"
9480                 "OpDecorate %in_buf BufferBlock\n"
9481                 "OpDecorate %out_buf BufferBlock\n"
9482                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9483                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9484                 // Base types
9485                 "%void       = OpTypeVoid\n"
9486                 "%voidf      = OpTypeFunction %void\n"
9487                 "%u32        = OpTypeInt 32 0\n"
9488                 "%i32        = OpTypeInt 32 1\n"
9489                 "%f32        = OpTypeFloat 32\n"
9490                 "%v2i32      = OpTypeVector %i32 2\n"
9491                 "${datatype_additional_decl}"
9492                 "%uvec3      = OpTypeVector %u32 3\n"
9493                 // Derived types
9494                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9495                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9496                 "%in_buf     = OpTypeStruct %${inputType}\n"
9497                 "%out_buf    = OpTypeStruct %${outputType}\n"
9498                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9499                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9500                 "%indata     = OpVariable %in_bufptr Uniform\n"
9501                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9502                 // Constants
9503                 "%zero       = OpConstant %i32 0\n"
9504                 // Main function
9505                 "%main       = OpFunction %void None %voidf\n"
9506                 "%label      = OpLabel\n"
9507                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9508                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9509                 "%inval      = OpLoad %${inputType} %inloc\n"
9510                 "%conv       = ${instruction} %${outputType} %inval\n"
9511                 "              OpStore %outloc %conv\n"
9512                 "              OpReturn\n"
9513                 "              OpFunctionEnd\n"
9514         );
9515
9516         return shader.specialize(params);
9517 }
9518
9519 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9520 {
9521         if (instruction == "OpUConvert")
9522         {
9523                 // Convert unsigned int to unsigned int
9524                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9526                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9527
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9531
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9533                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9534                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9535
9536                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9537                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9538                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9539         }
9540         else if (instruction == "OpSConvert")
9541         {
9542                 // Sign extension int->int
9543                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9544                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9545                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9546                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9548                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9549
9550                 // Truncate for int->int
9551                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9552                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9555                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9556                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9557
9558                 // Sign extension for int->uint
9559                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9560                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9564                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9565
9566                 // Truncate for int->uint
9567                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9572                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9573
9574                 // Sign extension for uint->int
9575                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9576                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9577                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9578                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9579                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9580                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9581
9582                 // Truncate for uint->int
9583                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9584                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9585                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9586                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9587                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9588                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9589
9590                 // Convert i16vec2 to i32vec2 and vice versa
9591                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9592                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9593                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9594                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9595         }
9596         else if (instruction == "OpFConvert")
9597         {
9598                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9599                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9600                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9601
9602                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9603                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9604
9605                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9606                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9607         }
9608         else if (instruction == "OpConvertFToU")
9609         {
9610                 // Normal numbers from uint8 range
9611                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9612                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9613                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9614
9615                 // Maximum uint8 value
9616                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9617                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9618                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9619
9620                 // +0
9621                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9622                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9623                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9624
9625                 // -0
9626                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9627                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9628                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9629
9630                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9631                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9632                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9633                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9634
9635                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9636                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9637                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9638                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9639
9640                 // +0
9641                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9642                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9643                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9644
9645                 // -0
9646                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9647                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9648                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9649
9650                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9651                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9652                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9653                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9654                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9655                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9656         }
9657         else if (instruction == "OpConvertUToF")
9658         {
9659                 // Normal numbers from uint8 range
9660                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9661                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9662                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9663
9664                 // Maximum uint8 value
9665                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9666                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9667                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9668
9669                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9670                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9671                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9672                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9673
9674                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9675                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9676                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9677                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9678
9679                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9680                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9681                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9682                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9683                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9684                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9685         }
9686         else if (instruction == "OpConvertFToS")
9687         {
9688                 // Normal numbers from int8 range
9689                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9690                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9691                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9692
9693                 // Minimum int8 value
9694                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9695                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9696                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9697
9698                 // Maximum int8 value
9699                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9700                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9701                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9702
9703                 // +0
9704                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9705                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9706                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9707
9708                 // -0
9709                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9710                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9711                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9712
9713                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9714                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9715                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9716                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9717
9718                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9719                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9720                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9721                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9722
9723                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9724                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9725                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9726                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9727
9728                 // +0
9729                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9730                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9731                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9732
9733                 // -0
9734                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9735                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9736                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9737
9738                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9739                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9740                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9741                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9742                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9743                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9744                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9745                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9746         }
9747         else if (instruction == "OpConvertSToF")
9748         {
9749                 // Normal numbers from int8 range
9750                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9751                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9752                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9753
9754                 // Minimum int8 value
9755                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9756                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9757                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9758
9759                 // Maximum int8 value
9760                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9761                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9762                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9763
9764                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9765                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9766                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9767                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9768
9769                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9770                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9771                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9772                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9773
9774                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9775                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9776                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9777                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9778
9779                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9780                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9781                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9782                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9783                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9784                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9785         }
9786         else
9787                 DE_FATAL("Unknown instruction");
9788 }
9789
9790 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9791 {
9792         map<string, string> params = convertCase.m_asmTypes;
9793         map<string, string> fragments;
9794
9795         params["instruction"] = instruction;
9796         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9797
9798         const StringTemplate decoration (
9799                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9800                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9801                 "      OpDecorate %SSBOi Binding 0\n"
9802                 "      OpDecorate %SSBOo Binding 1\n"
9803                 "      OpDecorate %s_SSBOi Block\n"
9804                 "      OpDecorate %s_SSBOo Block\n"
9805                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9806                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9807
9808         const StringTemplate pre_main (
9809                 "${datatype_additional_decl:opt}"
9810                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9811                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9812                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9813                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9814                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9815                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9816                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9817                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9818
9819         const StringTemplate testfun (
9820                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9821                 "%param     = OpFunctionParameter %v4f32\n"
9822                 "%label     = OpLabel\n"
9823                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9824                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9825                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9826                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9827                 "             OpStore %oLoc %valOut\n"
9828                 "             OpReturnValue %param\n"
9829                 "             OpFunctionEnd\n");
9830
9831         params["datatype_extensions"] =
9832                 params["datatype_extensions"] +
9833                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9834
9835         fragments["capability"] = params["datatype_capabilities"];
9836         fragments["extension"]  = params["datatype_extensions"];
9837         fragments["decoration"] = decoration.specialize(params);
9838         fragments["pre_main"]   = pre_main.specialize(params);
9839         fragments["testfun"]    = testfun.specialize(params);
9840
9841         return fragments;
9842 }
9843
9844 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9845 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9846 {
9847         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9848         vector<ConvertCase>                                     testCases;
9849         createConvertCases(testCases, instruction);
9850
9851         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9852         {
9853                 ComputeShaderSpec spec;
9854                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9855                 spec.numWorkGroups              = IVec3(1, 1, 1);
9856                 spec.inputs.push_back   (test->m_inputBuffer);
9857                 spec.outputs.push_back  (test->m_outputBuffer);
9858
9859                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9860
9861                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9862         }
9863         return group.release();
9864 }
9865
9866 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9867 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9868 {
9869         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9870         vector<ConvertCase>                                     testCases;
9871         createConvertCases(testCases, instruction);
9872
9873         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9874         {
9875                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9876                 VulkanFeatures          vulkanFeatures;
9877                 GraphicsResources       resources;
9878                 vector<string>          extensions;
9879                 SpecConstants           noSpecConstants;
9880                 PushConstants           noPushConstants;
9881                 GraphicsInterfaces      noInterfaces;
9882                 tcu::RGBA                       defaultColors[4];
9883
9884                 getDefaultColors                        (defaultColors);
9885                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9886                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9887                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9888
9889                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9890
9891                 vulkanFeatures.coreFeatures.vertexPipelineStoresAndAtomics      = true;
9892                 vulkanFeatures.coreFeatures.fragmentStoresAndAtomics            = true;
9893
9894                 createTestsForAllStages(
9895                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9896                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9897         }
9898         return group.release();
9899 }
9900
9901 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9902 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9903 {
9904         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9905         RGBA                                                    inputColors[4];
9906         RGBA                                                    outputColors[4];
9907         vector<string>                                  extensions;
9908         GraphicsResources                               resources;
9909         VulkanFeatures                                  features;
9910
9911         const char                                              functionStart[]  =
9912                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9913                 "%param1                = OpFunctionParameter %v4f32\n"
9914                 "%lbl                   = OpLabel\n";
9915
9916         const char                                              functionEnd[]           =
9917                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9918                 "                         OpReturnValue %transformed_param_32\n"
9919                 "                         OpFunctionEnd\n";
9920
9921         struct NameConstantsCode
9922         {
9923                 string name;
9924                 string constants;
9925                 string code;
9926         };
9927
9928 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9929                         "%f16                  = OpTypeFloat 16\n"                                                 \
9930                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9931                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9932                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9933                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9934                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9935                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9936                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9937                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9938
9939         NameConstantsCode                               tests[] =
9940         {
9941                 {
9942                         "vec4",
9943
9944                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9945                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9946                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9947                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9948                 },
9949                 {
9950                         "struct",
9951
9952                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9953                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9954                         "%fp_stype             = OpTypePointer Function %stype\n"
9955                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9956                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9957                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9958                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9959
9960                         "%v                    = OpVariable %fp_stype Function %cval\n"
9961                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9962                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9963                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9964                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9965                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9966                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9967                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9968                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9969                 },
9970                 {
9971                         // [1|0|0|0.5] [x] = x + 0.5
9972                         // [0|1|0|0.5] [y] = y + 0.5
9973                         // [0|0|1|0.5] [z] = z + 0.5
9974                         // [0|0|0|1  ] [1] = 1
9975                         "matrix",
9976
9977                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9978                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9979                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9980                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9981                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9982                         "%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"
9983                         "%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",
9984
9985                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9986                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9987                 },
9988                 {
9989                         "array",
9990
9991                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9992                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9993                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9994                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9995                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9996                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9997
9998                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9999                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
10000                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
10001                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
10002                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
10003                         "%f_val                = OpLoad %f16 %f\n"
10004                         "%f1_val               = OpLoad %f16 %f1\n"
10005                         "%f2_val               = OpLoad %f16 %f2\n"
10006                         "%f3_val               = OpLoad %f16 %f3\n"
10007                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
10008                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
10009                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
10010                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
10011                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10012                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10013                 },
10014                 {
10015                         //
10016                         // [
10017                         //   {
10018                         //      0.0,
10019                         //      [ 1.0, 1.0, 1.0, 1.0]
10020                         //   },
10021                         //   {
10022                         //      1.0,
10023                         //      [ 0.0, 0.5, 0.0, 0.0]
10024                         //   }, //     ^^^
10025                         //   {
10026                         //      0.0,
10027                         //      [ 1.0, 1.0, 1.0, 1.0]
10028                         //   }
10029                         // ]
10030                         "array_of_struct_of_array",
10031
10032                         FLOAT_16_COMMON_TYPES_AND_CONSTS
10033                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
10034                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
10035                         "%stype                = OpTypeStruct %f16 %a4f16\n"
10036                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
10037                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
10038                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
10039                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
10040                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
10041                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
10042                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
10043
10044                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
10045                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
10046                         "%f_l                  = OpLoad %f16 %f\n"
10047                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
10048                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10049                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10050                 }
10051         };
10052
10053         getHalfColorsFullAlpha(inputColors);
10054         outputColors[0] = RGBA(255, 255, 255, 255);
10055         outputColors[1] = RGBA(255, 127, 127, 255);
10056         outputColors[2] = RGBA(127, 255, 127, 255);
10057         outputColors[3] = RGBA(127, 127, 255, 255);
10058
10059         extensions.push_back("VK_KHR_16bit_storage");
10060         extensions.push_back("VK_KHR_shader_float16_int8");
10061         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10062
10063         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
10064         {
10065                 map<string, string> fragments;
10066
10067                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
10068                 fragments["capability"] = "OpCapability Float16\n";
10069                 fragments["pre_main"]   = tests[testNdx].constants;
10070                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
10071
10072                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
10073         }
10074         return opConstantCompositeTests.release();
10075 }
10076
10077 template<typename T>
10078 void finalizeTestsCreation (T&                                                  specResource,
10079                                                         const map<string, string>&      fragments,
10080                                                         tcu::TestContext&                       testCtx,
10081                                                         tcu::TestCaseGroup&                     testGroup,
10082                                                         const std::string&                      testName,
10083                                                         const VulkanFeatures&           vulkanFeatures,
10084                                                         const vector<string>&           extensions,
10085                                                         const IVec3&                            numWorkGroups);
10086
10087 template<>
10088 void finalizeTestsCreation (GraphicsResources&                  specResource,
10089                                                         const map<string, string>&      fragments,
10090                                                         tcu::TestContext&                       ,
10091                                                         tcu::TestCaseGroup&                     testGroup,
10092                                                         const std::string&                      testName,
10093                                                         const VulkanFeatures&           vulkanFeatures,
10094                                                         const vector<string>&           extensions,
10095                                                         const IVec3&                            )
10096 {
10097         RGBA defaultColors[4];
10098         getDefaultColors(defaultColors);
10099
10100         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
10101 }
10102
10103 template<>
10104 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
10105                                                         const map<string, string>&      fragments,
10106                                                         tcu::TestContext&                       testCtx,
10107                                                         tcu::TestCaseGroup&                     testGroup,
10108                                                         const std::string&                      testName,
10109                                                         const VulkanFeatures&           vulkanFeatures,
10110                                                         const vector<string>&           extensions,
10111                                                         const IVec3&                            numWorkGroups)
10112 {
10113         specResource.numWorkGroups = numWorkGroups;
10114         specResource.requestedVulkanFeatures = vulkanFeatures;
10115         specResource.extensions = extensions;
10116
10117         specResource.assembly = makeComputeShaderAssembly(fragments);
10118
10119         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
10120 }
10121
10122 template<class SpecResource>
10123 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
10124 {
10125         const string                                            nan                                     = nanSupported ? "_nan" : "";
10126         const string                                            groupName                       = "logical" + nan;
10127         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
10128
10129         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10130         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
10131         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
10132         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
10133         const deUint32                                          numDataPoints           = 16;
10134         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
10135         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
10136         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
10137         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
10138         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
10139         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
10140         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
10141
10142         struct TestOp
10143         {
10144                 const char*             opCode;
10145                 VerifyIOFunc    verifyFuncNan;
10146                 VerifyIOFunc    verifyFuncNonNan;
10147                 const deUint32  argCount;
10148         };
10149
10150         const TestOp    testOps[]       =
10151         {
10152                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
10153                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
10154                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
10155                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
10156                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
10157                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
10158                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
10159                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
10160                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
10161                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
10162                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
10163                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
10164                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
10165                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
10166         };
10167
10168         { // scalar cases
10169                 const StringTemplate preMain
10170                 (
10171                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10172                         "      %f16 = OpTypeFloat 16\n"
10173                         "  %c_f16_0 = OpConstant %f16 0.0\n"
10174                         "  %c_f16_1 = OpConstant %f16 1.0\n"
10175                         "   %up_f16 = OpTypePointer Uniform %f16\n"
10176                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10177                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
10178                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10179                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10180                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10181                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10182                 );
10183
10184                 const StringTemplate decoration
10185                 (
10186                         "OpDecorate %ra_f16 ArrayStride 2\n"
10187                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10188                         "OpDecorate %SSBO16 BufferBlock\n"
10189                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10190                         "OpDecorate %ssbo_src0 Binding 0\n"
10191                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10192                         "OpDecorate %ssbo_src1 Binding 1\n"
10193                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10194                         "OpDecorate %ssbo_dst Binding 2\n"
10195                 );
10196
10197                 const StringTemplate testFun
10198                 (
10199                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10200                         "    %param = OpFunctionParameter %v4f32\n"
10201
10202                         "    %entry = OpLabel\n"
10203                         "        %i = OpVariable %fp_i32 Function\n"
10204                         "             OpStore %i %c_i32_0\n"
10205                         "             OpBranch %loop\n"
10206
10207                         "     %loop = OpLabel\n"
10208                         "    %i_cmp = OpLoad %i32 %i\n"
10209                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10210                         "             OpLoopMerge %merge %next None\n"
10211                         "             OpBranchConditional %lt %write %merge\n"
10212
10213                         "    %write = OpLabel\n"
10214                         "      %ndx = OpLoad %i32 %i\n"
10215
10216                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10217                         " %val_src0 = OpLoad %f16 %src0\n"
10218
10219                         "${op_arg1_calc}"
10220
10221                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10222                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10223                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10224                         "             OpStore %dst %val_dst\n"
10225                         "             OpBranch %next\n"
10226
10227                         "     %next = OpLabel\n"
10228                         "    %i_cur = OpLoad %i32 %i\n"
10229                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10230                         "             OpStore %i %i_new\n"
10231                         "             OpBranch %loop\n"
10232
10233                         "    %merge = OpLabel\n"
10234                         "             OpReturnValue %param\n"
10235
10236                         "             OpFunctionEnd\n"
10237                 );
10238
10239                 const StringTemplate arg1Calc
10240                 (
10241                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10242                         " %val_src1 = OpLoad %f16 %src1\n"
10243                 );
10244
10245                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10246                 {
10247                         const size_t            iterations              = float16Data1.size();
10248                         const TestOp&           testOp                  = testOps[testOpsIdx];
10249                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10250                         SpecResource            specResource;
10251                         map<string, string>     specs;
10252                         VulkanFeatures          features;
10253                         map<string, string>     fragments;
10254                         vector<string>          extensions;
10255
10256                         specs["num_data_points"]        = de::toString(iterations);
10257                         specs["op_code"]                        = testOp.opCode;
10258                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10259                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10260
10261                         fragments["extension"]          = spvExtensions;
10262                         fragments["capability"]         = spvCapabilities;
10263                         fragments["execution_mode"]     = spvExecutionMode;
10264                         fragments["decoration"]         = decoration.specialize(specs);
10265                         fragments["pre_main"]           = preMain.specialize(specs);
10266                         fragments["testfun"]            = testFun.specialize(specs);
10267
10268                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10269                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10270                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10271                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10272
10273                         extensions.push_back("VK_KHR_16bit_storage");
10274                         extensions.push_back("VK_KHR_shader_float16_int8");
10275
10276                         if (nanSupported)
10277                         {
10278                                 extensions.push_back("VK_KHR_shader_float_controls");
10279
10280                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10281                         }
10282
10283                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10284                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10285
10286                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10287                 }
10288         }
10289         { // vector cases
10290                 const StringTemplate preMain
10291                 (
10292                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10293                         "     %v2bool = OpTypeVector %bool 2\n"
10294                         "        %f16 = OpTypeFloat 16\n"
10295                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10296                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10297                         "      %v2f16 = OpTypeVector %f16 2\n"
10298                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10299                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10300                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10301                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10302                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10303                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10304                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10305                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10306                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10307                 );
10308
10309                 const StringTemplate decoration
10310                 (
10311                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10312                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10313                         "OpDecorate %SSBO16 BufferBlock\n"
10314                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10315                         "OpDecorate %ssbo_src0 Binding 0\n"
10316                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10317                         "OpDecorate %ssbo_src1 Binding 1\n"
10318                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10319                         "OpDecorate %ssbo_dst Binding 2\n"
10320                 );
10321
10322                 const StringTemplate testFun
10323                 (
10324                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10325                         "    %param = OpFunctionParameter %v4f32\n"
10326
10327                         "    %entry = OpLabel\n"
10328                         "        %i = OpVariable %fp_i32 Function\n"
10329                         "             OpStore %i %c_i32_0\n"
10330                         "             OpBranch %loop\n"
10331
10332                         "     %loop = OpLabel\n"
10333                         "    %i_cmp = OpLoad %i32 %i\n"
10334                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10335                         "             OpLoopMerge %merge %next None\n"
10336                         "             OpBranchConditional %lt %write %merge\n"
10337
10338                         "    %write = OpLabel\n"
10339                         "      %ndx = OpLoad %i32 %i\n"
10340
10341                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10342                         " %val_src0 = OpLoad %v2f16 %src0\n"
10343
10344                         "${op_arg1_calc}"
10345
10346                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10347                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10348                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10349                         "             OpStore %dst %val_dst\n"
10350                         "             OpBranch %next\n"
10351
10352                         "     %next = OpLabel\n"
10353                         "    %i_cur = OpLoad %i32 %i\n"
10354                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10355                         "             OpStore %i %i_new\n"
10356                         "             OpBranch %loop\n"
10357
10358                         "    %merge = OpLabel\n"
10359                         "             OpReturnValue %param\n"
10360
10361                         "             OpFunctionEnd\n"
10362                 );
10363
10364                 const StringTemplate arg1Calc
10365                 (
10366                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10367                         " %val_src1 = OpLoad %v2f16 %src1\n"
10368                 );
10369
10370                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10371                 {
10372                         const deUint32          itemsPerVec     = 2;
10373                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10374                         const TestOp&           testOp          = testOps[testOpsIdx];
10375                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10376                         SpecResource            specResource;
10377                         map<string, string>     specs;
10378                         vector<string>          extensions;
10379                         VulkanFeatures          features;
10380                         map<string, string>     fragments;
10381
10382                         specs["num_data_points"]        = de::toString(iterations);
10383                         specs["op_code"]                        = testOp.opCode;
10384                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10385                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10386
10387                         fragments["extension"]          = spvExtensions;
10388                         fragments["capability"]         = spvCapabilities;
10389                         fragments["execution_mode"]     = spvExecutionMode;
10390                         fragments["decoration"]         = decoration.specialize(specs);
10391                         fragments["pre_main"]           = preMain.specialize(specs);
10392                         fragments["testfun"]            = testFun.specialize(specs);
10393
10394                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10395                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10396                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10397                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10398
10399                         extensions.push_back("VK_KHR_16bit_storage");
10400                         extensions.push_back("VK_KHR_shader_float16_int8");
10401
10402                         if (nanSupported)
10403                         {
10404                                 extensions.push_back("VK_KHR_shader_float_controls");
10405
10406                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10407                         }
10408
10409                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10410                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10411
10412                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10413                 }
10414         }
10415
10416         return testGroup.release();
10417 }
10418
10419 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10420 {
10421         if (inputs.size() != 1 || outputAllocs.size() != 1)
10422                 return false;
10423
10424         vector<deUint8> input1Bytes;
10425
10426         inputs[0].getBytes(input1Bytes);
10427
10428         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10429         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10430         std::string                             error;
10431
10432         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10433         {
10434                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10435                 {
10436                         log << TestLog::Message << error << TestLog::EndMessage;
10437
10438                         return false;
10439                 }
10440         }
10441
10442         return true;
10443 }
10444
10445 template<class SpecResource>
10446 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10447 {
10448         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10449
10450         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10451         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10452         const deUint32                                          numDataPoints           = 256;
10453         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10454         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10455         map<string, string>                                     fragments;
10456
10457         struct TestType
10458         {
10459                 const deUint32  typeComponents;
10460                 const char*             typeName;
10461                 const char*             typeDecls;
10462         };
10463
10464         const TestType  testTypes[]     =
10465         {
10466                 {
10467                         1,
10468                         "f16",
10469                         ""
10470                 },
10471                 {
10472                         2,
10473                         "v2f16",
10474                         "      %v2f16 = OpTypeVector %f16 2\n"
10475                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10476                 },
10477                 {
10478                         4,
10479                         "v4f16",
10480                         "      %v4f16 = OpTypeVector %f16 4\n"
10481                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10482                 },
10483         };
10484
10485         const StringTemplate preMain
10486         (
10487                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10488                 "     %v2bool = OpTypeVector %bool 2\n"
10489                 "        %f16 = OpTypeFloat 16\n"
10490                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10491
10492                 "${type_decls}"
10493
10494                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10495                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10496                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10497                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10498                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10499                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10500                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10501         );
10502
10503         const StringTemplate decoration
10504         (
10505                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10506                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10507                 "OpDecorate %SSBO16 BufferBlock\n"
10508                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10509                 "OpDecorate %ssbo_src Binding 0\n"
10510                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10511                 "OpDecorate %ssbo_dst Binding 1\n"
10512         );
10513
10514         const StringTemplate testFun
10515         (
10516                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10517                 "    %param = OpFunctionParameter %v4f32\n"
10518                 "    %entry = OpLabel\n"
10519
10520                 "        %i = OpVariable %fp_i32 Function\n"
10521                 "             OpStore %i %c_i32_0\n"
10522                 "             OpBranch %loop\n"
10523
10524                 "     %loop = OpLabel\n"
10525                 "    %i_cmp = OpLoad %i32 %i\n"
10526                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10527                 "             OpLoopMerge %merge %next None\n"
10528                 "             OpBranchConditional %lt %write %merge\n"
10529
10530                 "    %write = OpLabel\n"
10531                 "      %ndx = OpLoad %i32 %i\n"
10532
10533                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10534                 "  %val_src = OpLoad %${tt} %src\n"
10535
10536                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10537                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10538                 "             OpStore %dst %val_dst\n"
10539                 "             OpBranch %next\n"
10540
10541                 "     %next = OpLabel\n"
10542                 "    %i_cur = OpLoad %i32 %i\n"
10543                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10544                 "             OpStore %i %i_new\n"
10545                 "             OpBranch %loop\n"
10546
10547                 "    %merge = OpLabel\n"
10548                 "             OpReturnValue %param\n"
10549
10550                 "             OpFunctionEnd\n"
10551
10552                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10553                 "   %param0 = OpFunctionParameter %${tt}\n"
10554                 " %entry_pf = OpLabel\n"
10555                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10556                 "             OpReturnValue %res0\n"
10557                 "             OpFunctionEnd\n"
10558         );
10559
10560         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10561         {
10562                 const TestType&         testType                = testTypes[testTypeIdx];
10563                 const string            testName                = testType.typeName;
10564                 const deUint32          itemsPerType    = testType.typeComponents;
10565                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10566                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10567                 SpecResource            specResource;
10568                 map<string, string>     specs;
10569                 VulkanFeatures          features;
10570                 vector<string>          extensions;
10571
10572                 specs["cap"]                            = "StorageUniformBufferBlock16";
10573                 specs["num_data_points"]        = de::toString(iterations);
10574                 specs["tt"]                                     = testType.typeName;
10575                 specs["tt_stride"]                      = de::toString(typeStride);
10576                 specs["type_decls"]                     = testType.typeDecls;
10577
10578                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10579                 fragments["capability"]         = capabilities.specialize(specs);
10580                 fragments["decoration"]         = decoration.specialize(specs);
10581                 fragments["pre_main"]           = preMain.specialize(specs);
10582                 fragments["testfun"]            = testFun.specialize(specs);
10583
10584                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10585                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10586                 specResource.verifyIO = compareFP16FunctionSetFunc;
10587
10588                 extensions.push_back("VK_KHR_16bit_storage");
10589                 extensions.push_back("VK_KHR_shader_float16_int8");
10590
10591                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10592                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10593
10594                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10595         }
10596
10597         return testGroup.release();
10598 }
10599
10600 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10601 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10602 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10603
10604 template<deUint32 R, deUint32 N>
10605 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10606 {
10607         return N * ((R * y) + x) + n;
10608 }
10609
10610 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10611 struct getFDelta
10612 {
10613         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10614         {
10615                 DE_STATIC_ASSERT(R%2 == 0);
10616                 DE_ASSERT(flavor == 0);
10617                 DE_UNREF(flavor);
10618
10619                 const X0                        x0;
10620                 const X1                        x1;
10621                 const Y0                        y0;
10622                 const Y1                        y1;
10623                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10624                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10625                 const tcu::Float16      f0      = tcu::Float16(v0);
10626                 const tcu::Float16      f1      = tcu::Float16(v1);
10627                 const float                     d0      = f0.asFloat();
10628                 const float                     d1      = f1.asFloat();
10629                 const float                     d       = d1 - d0;
10630
10631                 return d;
10632         }
10633
10634         getFDelta(){}
10635 };
10636
10637 template<deUint32 F, class Class0, class Class1>
10638 struct getFOneOf
10639 {
10640         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10641         {
10642                 DE_ASSERT(flavor < F);
10643
10644                 if (flavor == 0)
10645                 {
10646                         Class0 c;
10647
10648                         return c(data, x, y, n, flavor);
10649                 }
10650                 else
10651                 {
10652                         Class1 c;
10653
10654                         return c(data, x, y, n, flavor - 1);
10655                 }
10656         }
10657
10658         getFOneOf(){}
10659 };
10660
10661 template<class FineX0, class FineX1, class FineY0, class FineY1>
10662 struct calcWidthOf4
10663 {
10664         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10665         {
10666                 DE_ASSERT(flavor < 4);
10667
10668                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10669                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10670                 const getFOneOf<2, FineX0, FineX1>      cx;
10671                 const getFOneOf<2, FineY0, FineY1>      cy;
10672                 float                                                           v               = 0;
10673
10674                 v += fabsf(cx(data, x, y, n, flavorX));
10675                 v += fabsf(cy(data, x, y, n, flavorY));
10676
10677                 return v;
10678         }
10679
10680         calcWidthOf4(){}
10681 };
10682
10683 template<deUint32 R, deUint32 N, class Derivative>
10684 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10685 {
10686         const deUint32          numDataPointsByAxis     = R;
10687         const Derivative        derivativeFunc;
10688
10689         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10690         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10691         for (deUint32 n = 0; n < N; ++n)
10692         {
10693                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10694                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10695                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10696
10697                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10698
10699                 if (reportError)
10700                 {
10701                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10702                         reportError     = !compare16BitFloat(expected, output, error);
10703                 }
10704
10705                 if (reportError)
10706                 {
10707                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10708
10709                         return false;
10710                 }
10711         }
10712
10713         return true;
10714 }
10715
10716 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10717 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10718 {
10719         if (inputs.size() != 1 || outputAllocs.size() != 1)
10720                 return false;
10721
10722         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10723         std::string                     results[FLAVOUR_COUNT];
10724         vector<deUint8>         inputBytes;
10725
10726         inputs[0].getBytes(inputBytes);
10727
10728         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10729         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10730
10731         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10732
10733         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10734                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10735                 {
10736                         break;
10737                 }
10738                 else
10739                 {
10740                         successfulRuns--;
10741                 }
10742
10743         if (successfulRuns == 0)
10744                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10745                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10746
10747         return successfulRuns > 0;
10748 }
10749
10750 template<deUint32 R, deUint32 N>
10751 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10752 {
10753         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10754         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10755
10756         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10757         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10758         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10759         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10760         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10761         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10762
10763         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10764         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10765
10766         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10767         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10768         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10769
10770         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10771         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10772
10773         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10774         const deUint32                                          numDataPointsByAxis     = R;
10775         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10776         vector<deFloat16>                                       float16InputX;
10777         vector<deFloat16>                                       float16InputY;
10778         vector<deFloat16>                                       float16InputW;
10779         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10780         RGBA                                                            defaultColors[4];
10781
10782         getDefaultColors(defaultColors);
10783
10784         float16InputX.reserve(numDataPoints);
10785         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10786         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10787         for (deUint32 n = 0; n < N; ++n)
10788         {
10789                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10790
10791                 if (y%2 == 0)
10792                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10793                 else
10794                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10795         }
10796
10797         float16InputY.reserve(numDataPoints);
10798         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10799         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10800         for (deUint32 n = 0; n < N; ++n)
10801         {
10802                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10803
10804                 if (x%2 == 0)
10805                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10806                 else
10807                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10808         }
10809
10810         const deFloat16 testNumbers[]   =
10811         {
10812                 tcu::Float16( 2.0  ).bits(),
10813                 tcu::Float16( 4.0  ).bits(),
10814                 tcu::Float16( 8.0  ).bits(),
10815                 tcu::Float16( 16.0 ).bits(),
10816                 tcu::Float16( 32.0 ).bits(),
10817                 tcu::Float16( 64.0 ).bits(),
10818                 tcu::Float16( 128.0).bits(),
10819                 tcu::Float16( 256.0).bits(),
10820                 tcu::Float16( 512.0).bits(),
10821                 tcu::Float16(-2.0  ).bits(),
10822                 tcu::Float16(-4.0  ).bits(),
10823                 tcu::Float16(-8.0  ).bits(),
10824                 tcu::Float16(-16.0 ).bits(),
10825                 tcu::Float16(-32.0 ).bits(),
10826                 tcu::Float16(-64.0 ).bits(),
10827                 tcu::Float16(-128.0).bits(),
10828                 tcu::Float16(-256.0).bits(),
10829                 tcu::Float16(-512.0).bits(),
10830         };
10831
10832         float16InputW.reserve(numDataPoints);
10833         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10834         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10835         for (deUint32 n = 0; n < N; ++n)
10836                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10837
10838         struct TestOp
10839         {
10840                 const char*                     opCode;
10841                 vector<deFloat16>&      inputData;
10842                 VerifyIOFunc            verifyFunc;
10843         };
10844
10845         const TestOp    testOps[]       =
10846         {
10847                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10848                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10849                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10850                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10851                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10852                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10853                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10854                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10855                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10856         };
10857
10858         struct TestType
10859         {
10860                 const deUint32  typeComponents;
10861                 const char*             typeName;
10862                 const char*             typeDecls;
10863         };
10864
10865         const TestType  testTypes[]     =
10866         {
10867                 {
10868                         1,
10869                         "f16",
10870                         ""
10871                 },
10872                 {
10873                         2,
10874                         "v2f16",
10875                         "      %v2f16 = OpTypeVector %f16 2\n"
10876                 },
10877                 {
10878                         4,
10879                         "v4f16",
10880                         "      %v4f16 = OpTypeVector %f16 4\n"
10881                 },
10882         };
10883
10884         const deUint32  testTypeNdx     = (N == 1) ? 0
10885                                                                 : (N == 2) ? 1
10886                                                                 : (N == 4) ? 2
10887                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10888         const TestType& testType        =       testTypes[testTypeNdx];
10889
10890         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10891         DE_ASSERT(testType.typeComponents == N);
10892
10893         const StringTemplate preMain
10894         (
10895                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10896                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10897                 "      %f16 = OpTypeFloat 16\n"
10898                 "${type_decls}"
10899                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10900                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10901                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10902                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10903                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10904                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10905         );
10906
10907         const StringTemplate decoration
10908         (
10909                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10910                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10911                 "OpDecorate %SSBO16 BufferBlock\n"
10912                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10913                 "OpDecorate %ssbo_src Binding 0\n"
10914                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10915                 "OpDecorate %ssbo_dst Binding 1\n"
10916         );
10917
10918         const StringTemplate testFun
10919         (
10920                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10921                 "    %param = OpFunctionParameter %v4f32\n"
10922                 "    %entry = OpLabel\n"
10923
10924                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10925                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10926                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10927                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10928                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10929                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10930                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10931                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10932
10933                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10934                 "  %val_src = OpLoad %${tt} %src\n"
10935                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10936                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10937                 "             OpStore %dst %val_dst\n"
10938                 "             OpBranch %merge\n"
10939
10940                 "    %merge = OpLabel\n"
10941                 "             OpReturnValue %param\n"
10942
10943                 "             OpFunctionEnd\n"
10944         );
10945
10946         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10947         {
10948                 const TestOp&           testOp                  = testOps[testOpsIdx];
10949                 const string            testName                = de::toLower(string(testOp.opCode));
10950                 const size_t            typeStride              = N * sizeof(deFloat16);
10951                 GraphicsResources       specResource;
10952                 map<string, string>     specs;
10953                 VulkanFeatures          features;
10954                 vector<string>          extensions;
10955                 map<string, string>     fragments;
10956                 SpecConstants           noSpecConstants;
10957                 PushConstants           noPushConstants;
10958                 GraphicsInterfaces      noInterfaces;
10959
10960                 specs["op_code"]                        = testOp.opCode;
10961                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10962                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10963                 specs["tt"]                                     = testType.typeName;
10964                 specs["tt_stride"]                      = de::toString(typeStride);
10965                 specs["type_decls"]                     = testType.typeDecls;
10966
10967                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10968                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10969                 fragments["decoration"]         = decoration.specialize(specs);
10970                 fragments["pre_main"]           = preMain.specialize(specs);
10971                 fragments["testfun"]            = testFun.specialize(specs);
10972
10973                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10974                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10975                 specResource.verifyIO = testOp.verifyFunc;
10976
10977                 extensions.push_back("VK_KHR_16bit_storage");
10978                 extensions.push_back("VK_KHR_shader_float16_int8");
10979
10980                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10981                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10982
10983                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10984                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10985         }
10986
10987         return testGroup.release();
10988 }
10989
10990 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10991 {
10992         if (inputs.size() != 2 || outputAllocs.size() != 1)
10993                 return false;
10994
10995         vector<deUint8> input1Bytes;
10996         vector<deUint8> input2Bytes;
10997
10998         inputs[0].getBytes(input1Bytes);
10999         inputs[1].getBytes(input2Bytes);
11000
11001         DE_ASSERT(input1Bytes.size() > 0);
11002         DE_ASSERT(input2Bytes.size() > 0);
11003         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11004
11005         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
11006         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11007         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11008         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
11009         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11010         std::string                             error;
11011
11012         DE_ASSERT(components == 2 || components == 4);
11013         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
11014
11015         for (size_t idx = 0; idx < iterations; ++idx)
11016         {
11017                 const deUint32  componentNdx    = inputIndices[idx];
11018
11019                 DE_ASSERT(componentNdx < components);
11020
11021                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
11022
11023                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
11024                 {
11025                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
11026
11027                         return false;
11028                 }
11029         }
11030
11031         return true;
11032 }
11033
11034 template<class SpecResource>
11035 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
11036 {
11037         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
11038
11039         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11040         const deUint32                                          numDataPoints           = 256;
11041         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11042         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11043
11044         struct TestType
11045         {
11046                 const deUint32  typeComponents;
11047                 const size_t    typeStride;
11048                 const char*             typeName;
11049                 const char*             typeDecls;
11050         };
11051
11052         const TestType  testTypes[]     =
11053         {
11054                 {
11055                         2,
11056                         2 * sizeof(deFloat16),
11057                         "v2f16",
11058                         "      %v2f16 = OpTypeVector %f16 2\n"
11059                 },
11060                 {
11061                         3,
11062                         4 * sizeof(deFloat16),
11063                         "v3f16",
11064                         "      %v3f16 = OpTypeVector %f16 3\n"
11065                 },
11066                 {
11067                         4,
11068                         4 * sizeof(deFloat16),
11069                         "v4f16",
11070                         "      %v4f16 = OpTypeVector %f16 4\n"
11071                 },
11072         };
11073
11074         const StringTemplate preMain
11075         (
11076                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11077                 "        %f16 = OpTypeFloat 16\n"
11078
11079                 "${type_decl}"
11080
11081                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11082                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11083                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11084                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11085
11086                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11087                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11088                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11089                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11090
11091                 "     %up_f16 = OpTypePointer Uniform %f16\n"
11092                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11093                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
11094                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11095
11096                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11097                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11098                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11099         );
11100
11101         const StringTemplate decoration
11102         (
11103                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11104                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11105                 "OpDecorate %SSBO_SRC BufferBlock\n"
11106                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11107                 "OpDecorate %ssbo_src Binding 0\n"
11108
11109                 "OpDecorate %ra_u32 ArrayStride 4\n"
11110                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11111                 "OpDecorate %SSBO_IDX BufferBlock\n"
11112                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11113                 "OpDecorate %ssbo_idx Binding 1\n"
11114
11115                 "OpDecorate %ra_f16 ArrayStride 2\n"
11116                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11117                 "OpDecorate %SSBO_DST BufferBlock\n"
11118                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11119                 "OpDecorate %ssbo_dst Binding 2\n"
11120         );
11121
11122         const StringTemplate testFun
11123         (
11124                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11125                 "    %param = OpFunctionParameter %v4f32\n"
11126                 "    %entry = OpLabel\n"
11127
11128                 "        %i = OpVariable %fp_i32 Function\n"
11129                 "             OpStore %i %c_i32_0\n"
11130
11131                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11132                 "             OpSelectionMerge %end_if None\n"
11133                 "             OpBranchConditional %will_run %run_test %end_if\n"
11134
11135                 " %run_test = OpLabel\n"
11136                 "             OpBranch %loop\n"
11137
11138                 "     %loop = OpLabel\n"
11139                 "    %i_cmp = OpLoad %i32 %i\n"
11140                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11141                 "             OpLoopMerge %merge %next None\n"
11142                 "             OpBranchConditional %lt %write %merge\n"
11143
11144                 "    %write = OpLabel\n"
11145                 "      %ndx = OpLoad %i32 %i\n"
11146
11147                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11148                 "  %val_src = OpLoad %${tt} %src\n"
11149
11150                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11151                 "  %val_idx = OpLoad %u32 %src_idx\n"
11152
11153                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
11154                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
11155
11156                 "             OpStore %dst %val_dst\n"
11157                 "             OpBranch %next\n"
11158
11159                 "     %next = OpLabel\n"
11160                 "    %i_cur = OpLoad %i32 %i\n"
11161                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11162                 "             OpStore %i %i_new\n"
11163                 "             OpBranch %loop\n"
11164
11165                 "    %merge = OpLabel\n"
11166                 "             OpBranch %end_if\n"
11167                 "   %end_if = OpLabel\n"
11168                 "             OpReturnValue %param\n"
11169
11170                 "             OpFunctionEnd\n"
11171         );
11172
11173         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11174         {
11175                 const TestType&         testType                = testTypes[testTypeIdx];
11176                 const string            testName                = testType.typeName;
11177                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11178                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11179                 SpecResource            specResource;
11180                 map<string, string>     specs;
11181                 VulkanFeatures          features;
11182                 vector<deUint32>        inputDataNdx;
11183                 map<string, string>     fragments;
11184                 vector<string>          extensions;
11185
11186                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11187                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11188
11189                 specs["num_data_points"]        = de::toString(iterations);
11190                 specs["tt"]                                     = testType.typeName;
11191                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11192                 specs["type_decl"]                      = testType.typeDecls;
11193
11194                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11195                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11196                 fragments["decoration"]         = decoration.specialize(specs);
11197                 fragments["pre_main"]           = preMain.specialize(specs);
11198                 fragments["testfun"]            = testFun.specialize(specs);
11199
11200                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11201                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11202                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11203                 specResource.verifyIO = compareFP16VectorExtractFunc;
11204
11205                 extensions.push_back("VK_KHR_16bit_storage");
11206                 extensions.push_back("VK_KHR_shader_float16_int8");
11207
11208                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11209                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11210
11211                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11212         }
11213
11214         return testGroup.release();
11215 }
11216
11217 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11218 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11219 {
11220         if (inputs.size() != 2 || outputAllocs.size() != 1)
11221                 return false;
11222
11223         vector<deUint8> input1Bytes;
11224         vector<deUint8> input2Bytes;
11225
11226         inputs[0].getBytes(input1Bytes);
11227         inputs[1].getBytes(input2Bytes);
11228
11229         DE_ASSERT(input1Bytes.size() > 0);
11230         DE_ASSERT(input2Bytes.size() > 0);
11231         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11232
11233         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11234         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11235         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11236         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11237         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11238         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11239         std::string                             error;
11240
11241         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11242         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11243
11244         for (size_t idx = 0; idx < iterations; ++idx)
11245         {
11246                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11247                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11248                 const deUint32          replacedCompNdx = inputIndices[idx];
11249
11250                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11251
11252                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11253                 {
11254                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11255
11256                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11257                         {
11258                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11259
11260                                 return false;
11261                         }
11262                 }
11263         }
11264
11265         return true;
11266 }
11267
11268 template<class SpecResource>
11269 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11270 {
11271         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11272
11273         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11274         const deUint32                                          replacement                     = 42;
11275         const deUint32                                          numDataPoints           = 256;
11276         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11277         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11278
11279         struct TestType
11280         {
11281                 const deUint32  typeComponents;
11282                 const size_t    typeStride;
11283                 const char*             typeName;
11284                 const char*             typeDecls;
11285                 VerifyIOFunc    verifyIOFunc;
11286         };
11287
11288         const TestType  testTypes[]     =
11289         {
11290                 {
11291                         2,
11292                         2 * sizeof(deFloat16),
11293                         "v2f16",
11294                         "      %v2f16 = OpTypeVector %f16 2\n",
11295                         compareFP16VectorInsertFunc<2, replacement>
11296                 },
11297                 {
11298                         3,
11299                         4 * sizeof(deFloat16),
11300                         "v3f16",
11301                         "      %v3f16 = OpTypeVector %f16 3\n",
11302                         compareFP16VectorInsertFunc<3, replacement>
11303                 },
11304                 {
11305                         4,
11306                         4 * sizeof(deFloat16),
11307                         "v4f16",
11308                         "      %v4f16 = OpTypeVector %f16 4\n",
11309                         compareFP16VectorInsertFunc<4, replacement>
11310                 },
11311         };
11312
11313         const StringTemplate preMain
11314         (
11315                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11316                 "        %f16 = OpTypeFloat 16\n"
11317                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11318
11319                 "${type_decl}"
11320
11321                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11322                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11323                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11324                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11325
11326                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11327                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11328                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11329                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11330
11331                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11332                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11333
11334                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11335                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11336                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11337         );
11338
11339         const StringTemplate decoration
11340         (
11341                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11342                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11343                 "OpDecorate %SSBO_SRC BufferBlock\n"
11344                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11345                 "OpDecorate %ssbo_src Binding 0\n"
11346
11347                 "OpDecorate %ra_u32 ArrayStride 4\n"
11348                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11349                 "OpDecorate %SSBO_IDX BufferBlock\n"
11350                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11351                 "OpDecorate %ssbo_idx Binding 1\n"
11352
11353                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11354                 "OpDecorate %SSBO_DST BufferBlock\n"
11355                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11356                 "OpDecorate %ssbo_dst Binding 2\n"
11357         );
11358
11359         const StringTemplate testFun
11360         (
11361                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11362                 "    %param = OpFunctionParameter %v4f32\n"
11363                 "    %entry = OpLabel\n"
11364
11365                 "        %i = OpVariable %fp_i32 Function\n"
11366                 "             OpStore %i %c_i32_0\n"
11367
11368                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11369                 "             OpSelectionMerge %end_if None\n"
11370                 "             OpBranchConditional %will_run %run_test %end_if\n"
11371
11372                 " %run_test = OpLabel\n"
11373                 "             OpBranch %loop\n"
11374
11375                 "     %loop = OpLabel\n"
11376                 "    %i_cmp = OpLoad %i32 %i\n"
11377                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11378                 "             OpLoopMerge %merge %next None\n"
11379                 "             OpBranchConditional %lt %write %merge\n"
11380
11381                 "    %write = OpLabel\n"
11382                 "      %ndx = OpLoad %i32 %i\n"
11383
11384                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11385                 "  %val_src = OpLoad %${tt} %src\n"
11386
11387                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11388                 "  %val_idx = OpLoad %u32 %src_idx\n"
11389
11390                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11391                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11392
11393                 "             OpStore %dst %val_dst\n"
11394                 "             OpBranch %next\n"
11395
11396                 "     %next = OpLabel\n"
11397                 "    %i_cur = OpLoad %i32 %i\n"
11398                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11399                 "             OpStore %i %i_new\n"
11400                 "             OpBranch %loop\n"
11401
11402                 "    %merge = OpLabel\n"
11403                 "             OpBranch %end_if\n"
11404                 "   %end_if = OpLabel\n"
11405                 "             OpReturnValue %param\n"
11406
11407                 "             OpFunctionEnd\n"
11408         );
11409
11410         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11411         {
11412                 const TestType&         testType                = testTypes[testTypeIdx];
11413                 const string            testName                = testType.typeName;
11414                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11415                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11416                 SpecResource            specResource;
11417                 map<string, string>     specs;
11418                 VulkanFeatures          features;
11419                 vector<deUint32>        inputDataNdx;
11420                 map<string, string>     fragments;
11421                 vector<string>          extensions;
11422
11423                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11424                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11425
11426                 specs["num_data_points"]        = de::toString(iterations);
11427                 specs["tt"]                                     = testType.typeName;
11428                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11429                 specs["type_decl"]                      = testType.typeDecls;
11430                 specs["replacement"]            = de::toString(replacement);
11431
11432                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11433                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11434                 fragments["decoration"]         = decoration.specialize(specs);
11435                 fragments["pre_main"]           = preMain.specialize(specs);
11436                 fragments["testfun"]            = testFun.specialize(specs);
11437
11438                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11439                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11440                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11441                 specResource.verifyIO = testType.verifyIOFunc;
11442
11443                 extensions.push_back("VK_KHR_16bit_storage");
11444                 extensions.push_back("VK_KHR_shader_float16_int8");
11445
11446                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11447                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11448
11449                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11450         }
11451
11452         return testGroup.release();
11453 }
11454
11455 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)
11456 {
11457         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11458         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11459         size_t                  comp;
11460
11461         switch (componentNdx)
11462         {
11463                 case 0: comp = compNdxLimited / compNdxCount; break;
11464                 case 1: comp = compNdxLimited % compNdxCount; break;
11465                 case 2: comp = 0; break;
11466                 case 3: comp = 1; break;
11467                 default: TCU_THROW(InternalError, "Impossible");
11468         }
11469
11470         if (comp >= vec1Len + vec2Len)
11471         {
11472                 validate = false;
11473                 return 0;
11474         }
11475         else
11476         {
11477                 validate = true;
11478                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11479         }
11480 }
11481
11482 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11483 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11484 {
11485         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11486         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11487         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11488
11489         if (inputs.size() != 2 || outputAllocs.size() != 1)
11490                 return false;
11491
11492         vector<deUint8> input1Bytes;
11493         vector<deUint8> input2Bytes;
11494
11495         inputs[0].getBytes(input1Bytes);
11496         inputs[1].getBytes(input2Bytes);
11497
11498         DE_ASSERT(input1Bytes.size() > 0);
11499         DE_ASSERT(input2Bytes.size() > 0);
11500         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11501
11502         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11503         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11504         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11505         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11506         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11507         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11508         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11509         std::string                             error;
11510
11511         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11512         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11513
11514         for (size_t idx = 0; idx < iterations; ++idx)
11515         {
11516                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11517                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11518                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11519
11520                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11521                 {
11522                         bool            validate        = true;
11523                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11524
11525                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11526                         {
11527                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11528
11529                                 return false;
11530                         }
11531                 }
11532         }
11533
11534         return true;
11535 }
11536
11537 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11538 {
11539         DE_ASSERT(dstComponentsCount <= 4);
11540         DE_ASSERT(src0ComponentsCount <= 4);
11541         DE_ASSERT(src1ComponentsCount <= 4);
11542         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11543
11544         switch (funcCode)
11545         {
11546                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11547                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11548                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11549                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11550                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11551                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11552                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11553                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11554                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11555                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11556                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11557                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11558                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11559                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11560                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11561                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11562                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11563                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11564                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11565                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11566                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11567                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11568                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11569                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11570                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11571                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11572                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11573                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11574         }
11575 }
11576
11577 template<class SpecResource>
11578 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11579 {
11580         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11581         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11582         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11583         de::Random                                                      rnd                                     (seed);
11584         const deUint32                                          numDataPoints           = 128;
11585         map<string, string>                                     fragments;
11586
11587         struct TestType
11588         {
11589                 const deUint32  typeComponents;
11590                 const char*             typeName;
11591         };
11592
11593         const TestType  testTypes[]     =
11594         {
11595                 {
11596                         2,
11597                         "v2f16",
11598                 },
11599                 {
11600                         3,
11601                         "v3f16",
11602                 },
11603                 {
11604                         4,
11605                         "v4f16",
11606                 },
11607         };
11608
11609         const StringTemplate preMain
11610         (
11611                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11612                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11613                 "          %f16 = OpTypeFloat 16\n"
11614                 "        %v2f16 = OpTypeVector %f16 2\n"
11615                 "        %v3f16 = OpTypeVector %f16 3\n"
11616                 "        %v4f16 = OpTypeVector %f16 4\n"
11617
11618                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11619                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11620                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11621                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11622
11623                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11624                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11625                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11626                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11627
11628                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11629                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11630                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11631                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11632
11633                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11634
11635                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11636                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11637                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11638         );
11639
11640         const StringTemplate decoration
11641         (
11642                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11643                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11644                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11645
11646                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11647                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11648
11649                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11650                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11651
11652                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11653                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11654
11655                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11656                 "OpDecorate %ssbo_src0 Binding 0\n"
11657                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11658                 "OpDecorate %ssbo_src1 Binding 1\n"
11659                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11660                 "OpDecorate %ssbo_dst Binding 2\n"
11661         );
11662
11663         const StringTemplate testFun
11664         (
11665                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11666                 "    %param = OpFunctionParameter %v4f32\n"
11667                 "    %entry = OpLabel\n"
11668
11669                 "        %i = OpVariable %fp_i32 Function\n"
11670                 "             OpStore %i %c_i32_0\n"
11671
11672                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11673                 "             OpSelectionMerge %end_if None\n"
11674                 "             OpBranchConditional %will_run %run_test %end_if\n"
11675
11676                 " %run_test = OpLabel\n"
11677                 "             OpBranch %loop\n"
11678
11679                 "     %loop = OpLabel\n"
11680                 "    %i_cmp = OpLoad %i32 %i\n"
11681                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11682                 "             OpLoopMerge %merge %next None\n"
11683                 "             OpBranchConditional %lt %write %merge\n"
11684
11685                 "    %write = OpLabel\n"
11686                 "      %ndx = OpLoad %i32 %i\n"
11687                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11688                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11689                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11690                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11691                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11692                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11693                 "             OpStore %dst %val_dst\n"
11694                 "             OpBranch %next\n"
11695
11696                 "     %next = OpLabel\n"
11697                 "    %i_cur = OpLoad %i32 %i\n"
11698                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11699                 "             OpStore %i %i_new\n"
11700                 "             OpBranch %loop\n"
11701
11702                 "    %merge = OpLabel\n"
11703                 "             OpBranch %end_if\n"
11704                 "   %end_if = OpLabel\n"
11705                 "             OpReturnValue %param\n"
11706                 "             OpFunctionEnd\n"
11707                 "\n"
11708
11709                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11710                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11711                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11712                 "%sw_paramn = OpFunctionParameter %i32\n"
11713                 " %sw_entry = OpLabel\n"
11714                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11715                 "             OpSelectionMerge %switch_e None\n"
11716                 "             OpSwitch %modulo %default ${case_list}\n"
11717                 "${case_bodies}"
11718                 "%default   = OpLabel\n"
11719                 "             OpUnreachable\n" // Unreachable default case for switch statement
11720                 "%switch_e  = OpLabel\n"
11721                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11722                 "             OpFunctionEnd\n"
11723         );
11724
11725         const StringTemplate testCaseBody
11726         (
11727                 "%case_${case_ndx}    = OpLabel\n"
11728                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11729                 "             OpReturnValue %val_dst_${case_ndx}\n"
11730         );
11731
11732         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11733         {
11734                 const TestType& dstType                 = testTypes[dstTypeIdx];
11735
11736                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11737                 {
11738                         const TestType& src0Type        = testTypes[comp0Idx];
11739
11740                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11741                         {
11742                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11743                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11744                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11745                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11746                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11747                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11748                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11749                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11750                                 deUint32                                caseCount                       = 0;
11751                                 SpecResource                    specResource;
11752                                 map<string, string>             specs;
11753                                 vector<string>                  extensions;
11754                                 VulkanFeatures                  features;
11755                                 string                                  caseBodies;
11756                                 string                                  caseList;
11757
11758                                 // Generate case
11759                                 {
11760                                         vector<string>  componentList;
11761
11762                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11763                                         {
11764                                                 deUint32                caseNo          = 0;
11765
11766                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11767                                                         componentList.push_back(de::toString(caseNo++));
11768                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11769                                                         componentList.push_back(de::toString(caseNo++));
11770                                                 componentList.push_back("0xFFFFFFFF");
11771                                         }
11772
11773                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11774                                         {
11775                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11776                                                 {
11777                                                         map<string, string>     specCase;
11778                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11779
11780                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11781                                                                 shuffle += " " + de::toString(compIdx - 2);
11782
11783                                                         specCase["case_ndx"]    = de::toString(caseCount);
11784                                                         specCase["shuffle"]             = shuffle;
11785                                                         specCase["tt_dst"]              = dstType.typeName;
11786
11787                                                         caseBodies      += testCaseBody.specialize(specCase);
11788                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11789
11790                                                         caseCount++;
11791                                                 }
11792                                         }
11793                                 }
11794
11795                                 specs["num_data_points"]        = de::toString(numDataPoints);
11796                                 specs["tt_dst"]                         = dstType.typeName;
11797                                 specs["tt_src0"]                        = src0Type.typeName;
11798                                 specs["tt_src1"]                        = src1Type.typeName;
11799                                 specs["case_bodies"]            = caseBodies;
11800                                 specs["case_list"]                      = caseList;
11801                                 specs["case_count"]                     = de::toString(caseCount);
11802
11803                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11804                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11805                                 fragments["decoration"]         = decoration.specialize(specs);
11806                                 fragments["pre_main"]           = preMain.specialize(specs);
11807                                 fragments["testfun"]            = testFun.specialize(specs);
11808
11809                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11810                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11811                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11812                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11813
11814                                 extensions.push_back("VK_KHR_16bit_storage");
11815                                 extensions.push_back("VK_KHR_shader_float16_int8");
11816
11817                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11818                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11819
11820                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11821                         }
11822                 }
11823         }
11824
11825         return testGroup.release();
11826 }
11827
11828 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11829 {
11830         if (inputs.size() != 1 || outputAllocs.size() != 1)
11831                 return false;
11832
11833         vector<deUint8> input1Bytes;
11834
11835         inputs[0].getBytes(input1Bytes);
11836
11837         DE_ASSERT(input1Bytes.size() > 0);
11838         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11839
11840         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11841         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11842         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11843         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11844         std::string                             error;
11845
11846         for (size_t idx = 0; idx < iterations; ++idx)
11847         {
11848                 if (input1AsFP16[idx] == exceptionValue)
11849                         continue;
11850
11851                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11852                 {
11853                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11854
11855                         return false;
11856                 }
11857         }
11858
11859         return true;
11860 }
11861
11862 template<class SpecResource>
11863 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11864 {
11865         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11866         const deUint32                                          numElements                             = 8;
11867         const string                                            testName                                = "struct";
11868         const deUint32                                          structItemsCount                = 88;
11869         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11870         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11871         const deUint32                                          fieldModifier                   = 2;
11872         const deUint32                                          fieldModifiedMulIndex   = 60;
11873         const deUint32                                          fieldModifiedAddIndex   = 66;
11874
11875         const StringTemplate preMain
11876         (
11877                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11878                 "          %f16 = OpTypeFloat 16\n"
11879                 "        %v2f16 = OpTypeVector %f16 2\n"
11880                 "        %v3f16 = OpTypeVector %f16 3\n"
11881                 "        %v4f16 = OpTypeVector %f16 4\n"
11882                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11883
11884                 "${consts}"
11885
11886                 "      %c_u32_5 = OpConstant %u32 5\n"
11887
11888                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11889                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11890                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11891                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11892                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11893                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11894                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11895                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11896
11897                 "        %up_st = OpTypePointer Uniform %st_test\n"
11898                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11899                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11900                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11901
11902                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11903         );
11904
11905         const StringTemplate decoration
11906         (
11907                 "OpDecorate %SSBO_st BufferBlock\n"
11908                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11909                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11910                 "OpDecorate %ssbo_dst Binding 1\n"
11911
11912                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11913
11914                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11915                 "OpMemberDecorate %struct16 0 Offset 0\n"
11916                 "OpMemberDecorate %struct16 1 Offset 4\n"
11917                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11918                 "OpDecorate %f16arr3 ArrayStride 2\n"
11919                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11920                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11921                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11922
11923                 "OpMemberDecorate %st_test 0 Offset 0\n"
11924                 "OpMemberDecorate %st_test 1 Offset 4\n"
11925                 "OpMemberDecorate %st_test 2 Offset 8\n"
11926                 "OpMemberDecorate %st_test 3 Offset 16\n"
11927                 "OpMemberDecorate %st_test 4 Offset 24\n"
11928                 "OpMemberDecorate %st_test 5 Offset 32\n"
11929                 "OpMemberDecorate %st_test 6 Offset 80\n"
11930                 "OpMemberDecorate %st_test 7 Offset 100\n"
11931                 "OpMemberDecorate %st_test 8 Offset 104\n"
11932                 "OpMemberDecorate %st_test 9 Offset 144\n"
11933         );
11934
11935         const StringTemplate testFun
11936         (
11937                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11938                 "     %param = OpFunctionParameter %v4f32\n"
11939                 "     %entry = OpLabel\n"
11940
11941                 "         %i = OpVariable %fp_i32 Function\n"
11942                 "              OpStore %i %c_i32_0\n"
11943
11944                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11945                 "              OpSelectionMerge %end_if None\n"
11946                 "              OpBranchConditional %will_run %run_test %end_if\n"
11947
11948                 "  %run_test = OpLabel\n"
11949                 "              OpBranch %loop\n"
11950
11951                 "      %loop = OpLabel\n"
11952                 "     %i_cmp = OpLoad %i32 %i\n"
11953                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11954                 "              OpLoopMerge %merge %next None\n"
11955                 "              OpBranchConditional %lt %write %merge\n"
11956
11957                 "     %write = OpLabel\n"
11958                 "       %ndx = OpLoad %i32 %i\n"
11959
11960                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11961                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11962                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11963
11964                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11965
11966                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11967                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11968                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11969                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11970                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11971
11972                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11973                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11974                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11975                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11976                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11977
11978                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11979                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11980                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11981                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11982                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11983
11984                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11985
11986                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11987                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11988                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11989                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11990                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11991                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11992
11993                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11994                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11995                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11996
11997                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11998                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11999                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
12000                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
12001                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
12002                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
12003                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
12004                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
12005
12006                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
12007                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
12008                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
12009                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
12010
12011                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
12012                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
12013                 "              OpStore %dst %st_val\n"
12014
12015                 "              OpBranch %next\n"
12016
12017                 "      %next = OpLabel\n"
12018                 "     %i_cur = OpLoad %i32 %i\n"
12019                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
12020                 "              OpStore %i %i_new\n"
12021                 "              OpBranch %loop\n"
12022
12023                 "     %merge = OpLabel\n"
12024                 "              OpBranch %end_if\n"
12025                 "    %end_if = OpLabel\n"
12026                 "              OpReturnValue %param\n"
12027                 "              OpFunctionEnd\n"
12028         );
12029
12030         {
12031                 SpecResource            specResource;
12032                 map<string, string>     specs;
12033                 VulkanFeatures          features;
12034                 map<string, string>     fragments;
12035                 vector<string>          extensions;
12036                 vector<deFloat16>       expectedOutput;
12037                 string                          consts;
12038
12039                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
12040                 {
12041                         vector<deFloat16>       expectedIterationOutput;
12042
12043                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12044                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
12045
12046                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
12047                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
12048
12049                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
12050                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
12051
12052                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
12053                 }
12054
12055                 for (deUint32 i = 0; i < structItemsCount; ++i)
12056                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
12057
12058                 specs["num_elements"]           = de::toString(numElements);
12059                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
12060                 specs["field_modifier"]         = de::toString(fieldModifier);
12061                 specs["consts"]                         = consts;
12062
12063                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12064                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12065                 fragments["decoration"]         = decoration.specialize(specs);
12066                 fragments["pre_main"]           = preMain.specialize(specs);
12067                 fragments["testfun"]            = testFun.specialize(specs);
12068
12069                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12070                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12071                 specResource.verifyIO = compareFP16CompositeFunc;
12072
12073                 extensions.push_back("VK_KHR_16bit_storage");
12074                 extensions.push_back("VK_KHR_shader_float16_int8");
12075
12076                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12077                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12078
12079                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12080         }
12081
12082         return testGroup.release();
12083 }
12084
12085 template<class SpecResource>
12086 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
12087 {
12088         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
12089         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
12090         const string                                            opName                  (op);
12091         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
12092                                                                                                                 : (opName == "OpCompositeExtract") ? 1
12093                                                                                                                 : -1;
12094
12095         const StringTemplate preMain
12096         (
12097                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
12098                 "         %f16 = OpTypeFloat 16\n"
12099                 "       %v2f16 = OpTypeVector %f16 2\n"
12100                 "       %v3f16 = OpTypeVector %f16 3\n"
12101                 "       %v4f16 = OpTypeVector %f16 4\n"
12102                 "    %c_f16_na = OpConstant %f16 -1.0\n"
12103                 "     %c_u32_5 = OpConstant %u32 5\n"
12104
12105                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
12106                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
12107                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
12108                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
12109                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
12110                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
12111                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
12112                 "%st_test      = OpTypeStruct %${field_type}\n"
12113
12114                 "      %up_f16 = OpTypePointer Uniform %f16\n"
12115                 "       %up_st = OpTypePointer Uniform %st_test\n"
12116                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
12117                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
12118
12119                 "${op_premain_decls}"
12120
12121                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
12122                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
12123
12124                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
12125                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
12126         );
12127
12128         const StringTemplate decoration
12129         (
12130                 "OpDecorate %SSBO_src BufferBlock\n"
12131                 "OpDecorate %SSBO_dst BufferBlock\n"
12132                 "OpDecorate %ra_f16 ArrayStride 2\n"
12133                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
12134                 "OpDecorate %ssbo_src DescriptorSet 0\n"
12135                 "OpDecorate %ssbo_src Binding 0\n"
12136                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
12137                 "OpDecorate %ssbo_dst Binding 1\n"
12138
12139                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
12140                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
12141
12142                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
12143                 "OpMemberDecorate %struct16 0 Offset 0\n"
12144                 "OpMemberDecorate %struct16 1 Offset 4\n"
12145                 "OpDecorate %struct16arr3 ArrayStride 16\n"
12146                 "OpDecorate %f16arr3 ArrayStride 2\n"
12147                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
12148                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
12149                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
12150
12151                 "OpMemberDecorate %st_test 0 Offset 0\n"
12152         );
12153
12154         const StringTemplate testFun
12155         (
12156                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
12157                 "     %param = OpFunctionParameter %v4f32\n"
12158                 "     %entry = OpLabel\n"
12159
12160                 "         %i = OpVariable %fp_i32 Function\n"
12161                 "              OpStore %i %c_i32_0\n"
12162
12163                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
12164                 "              OpSelectionMerge %end_if None\n"
12165                 "              OpBranchConditional %will_run %run_test %end_if\n"
12166
12167                 "  %run_test = OpLabel\n"
12168                 "              OpBranch %loop\n"
12169
12170                 "      %loop = OpLabel\n"
12171                 "     %i_cmp = OpLoad %i32 %i\n"
12172                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
12173                 "              OpLoopMerge %merge %next None\n"
12174                 "              OpBranchConditional %lt %write %merge\n"
12175
12176                 "     %write = OpLabel\n"
12177                 "       %ndx = OpLoad %i32 %i\n"
12178
12179                 "${op_sw_fun_call}"
12180
12181                 "              OpStore %dst %val_dst\n"
12182                 "              OpBranch %next\n"
12183
12184                 "      %next = OpLabel\n"
12185                 "     %i_cur = OpLoad %i32 %i\n"
12186                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
12187                 "              OpStore %i %i_new\n"
12188                 "              OpBranch %loop\n"
12189
12190                 "     %merge = OpLabel\n"
12191                 "              OpBranch %end_if\n"
12192                 "    %end_if = OpLabel\n"
12193                 "              OpReturnValue %param\n"
12194                 "              OpFunctionEnd\n"
12195
12196                 "${op_sw_fun_header}"
12197                 " %sw_param = OpFunctionParameter %st_test\n"
12198                 "%sw_paramn = OpFunctionParameter %i32\n"
12199                 " %sw_entry = OpLabel\n"
12200                 "             OpSelectionMerge %switch_e None\n"
12201                 "             OpSwitch %sw_paramn %default ${case_list}\n"
12202
12203                 "${case_bodies}"
12204
12205                 "%default   = OpLabel\n"
12206                 "             OpReturnValue ${op_case_default_value}\n"
12207                 "%switch_e  = OpLabel\n"
12208                 "             OpUnreachable\n" // Unreachable merge block for switch statement
12209                 "             OpFunctionEnd\n"
12210         );
12211
12212         const StringTemplate testCaseBody
12213         (
12214                 "%case_${case_ndx}    = OpLabel\n"
12215                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12216                 "             OpReturnValue %val_ret_${case_ndx}\n"
12217         );
12218
12219         struct OpParts
12220         {
12221                 const char*     premainDecls;
12222                 const char*     swFunCall;
12223                 const char*     swFunHeader;
12224                 const char*     caseDefaultValue;
12225                 const char*     argsPartial;
12226         };
12227
12228         OpParts                                                         opPartsArray[]                  =
12229         {
12230                 // OpCompositeInsert
12231                 {
12232                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12233                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12234                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12235
12236                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12237                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12238                         "   %val_new = OpLoad %f16 %src\n"
12239                         "   %val_old = OpLoad %st_test %dst\n"
12240                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12241
12242                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12243                         "%sw_paramv = OpFunctionParameter %f16\n",
12244
12245                         "%sw_param",
12246
12247                         "%st_test %sw_paramv %sw_param",
12248                 },
12249                 // OpCompositeExtract
12250                 {
12251                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12252                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12253                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12254
12255                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12256                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12257                         "   %val_src = OpLoad %st_test %src\n"
12258                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12259
12260                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12261
12262                         "%c_f16_na",
12263
12264                         "%f16 %sw_param",
12265                 },
12266         };
12267
12268         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12269
12270         const char*     accessPathF16[] =
12271         {
12272                 "0",                    // %f16
12273                 DE_NULL,
12274         };
12275         const char*     accessPathV2F16[] =
12276         {
12277                 "0 0",                  // %v2f16
12278                 "0 1",
12279         };
12280         const char*     accessPathV3F16[] =
12281         {
12282                 "0 0",                  // %v3f16
12283                 "0 1",
12284                 "0 2",
12285                 DE_NULL,
12286         };
12287         const char*     accessPathV4F16[] =
12288         {
12289                 "0 0",                  // %v4f16"
12290                 "0 1",
12291                 "0 2",
12292                 "0 3",
12293         };
12294         const char*     accessPathF16Arr3[] =
12295         {
12296                 "0 0",                  // %f16arr3
12297                 "0 1",
12298                 "0 2",
12299                 DE_NULL,
12300         };
12301         const char*     accessPathStruct16Arr3[] =
12302         {
12303                 "0 0 0",                // %struct16arr3
12304                 DE_NULL,
12305                 "0 0 1 0 0",
12306                 "0 0 1 0 1",
12307                 "0 0 1 1 0",
12308                 "0 0 1 1 1",
12309                 "0 0 1 2 0",
12310                 "0 0 1 2 1",
12311                 "0 1 0",
12312                 DE_NULL,
12313                 "0 1 1 0 0",
12314                 "0 1 1 0 1",
12315                 "0 1 1 1 0",
12316                 "0 1 1 1 1",
12317                 "0 1 1 2 0",
12318                 "0 1 1 2 1",
12319                 "0 2 0",
12320                 DE_NULL,
12321                 "0 2 1 0 0",
12322                 "0 2 1 0 1",
12323                 "0 2 1 1 0",
12324                 "0 2 1 1 1",
12325                 "0 2 1 2 0",
12326                 "0 2 1 2 1",
12327         };
12328         const char*     accessPathV2F16Arr5[] =
12329         {
12330                 "0 0 0",                // %v2f16arr5
12331                 "0 0 1",
12332                 "0 1 0",
12333                 "0 1 1",
12334                 "0 2 0",
12335                 "0 2 1",
12336                 "0 3 0",
12337                 "0 3 1",
12338                 "0 4 0",
12339                 "0 4 1",
12340         };
12341         const char*     accessPathV3F16Arr5[] =
12342         {
12343                 "0 0 0",                // %v3f16arr5
12344                 "0 0 1",
12345                 "0 0 2",
12346                 DE_NULL,
12347                 "0 1 0",
12348                 "0 1 1",
12349                 "0 1 2",
12350                 DE_NULL,
12351                 "0 2 0",
12352                 "0 2 1",
12353                 "0 2 2",
12354                 DE_NULL,
12355                 "0 3 0",
12356                 "0 3 1",
12357                 "0 3 2",
12358                 DE_NULL,
12359                 "0 4 0",
12360                 "0 4 1",
12361                 "0 4 2",
12362                 DE_NULL,
12363         };
12364         const char*     accessPathV4F16Arr3[] =
12365         {
12366                 "0 0 0",                // %v4f16arr3
12367                 "0 0 1",
12368                 "0 0 2",
12369                 "0 0 3",
12370                 "0 1 0",
12371                 "0 1 1",
12372                 "0 1 2",
12373                 "0 1 3",
12374                 "0 2 0",
12375                 "0 2 1",
12376                 "0 2 2",
12377                 "0 2 3",
12378                 DE_NULL,
12379                 DE_NULL,
12380                 DE_NULL,
12381                 DE_NULL,
12382         };
12383
12384         struct TypeTestParameters
12385         {
12386                 const char*             name;
12387                 size_t                  accessPathLength;
12388                 const char**    accessPath;
12389         };
12390
12391         const TypeTestParameters typeTestParameters[] =
12392         {
12393                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12394                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12395                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12396                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12397                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12398                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12399                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12400                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12401                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12402         };
12403
12404         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12405         {
12406                 const OpParts           opParts                         = opPartsArray[opIndex];
12407                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12408                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12409                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12410                 SpecResource            specResource;
12411                 map<string, string>     specs;
12412                 VulkanFeatures          features;
12413                 map<string, string>     fragments;
12414                 vector<string>          extensions;
12415                 vector<deFloat16>       inputFP16;
12416                 vector<deFloat16>       dummyFP16Output;
12417
12418                 // Generate values for input
12419                 inputFP16.reserve(structItemsCount);
12420                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12421                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12422
12423                 dummyFP16Output.resize(structItemsCount);
12424
12425                 // Generate cases for OpSwitch
12426                 {
12427                         string  caseBodies;
12428                         string  caseList;
12429
12430                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12431                                 if (accessPath[caseNdx] != DE_NULL)
12432                                 {
12433                                         map<string, string>     specCase;
12434
12435                                         specCase["case_ndx"]            = de::toString(caseNdx);
12436                                         specCase["access_path"]         = accessPath[caseNdx];
12437                                         specCase["op_args_part"]        = opParts.argsPartial;
12438                                         specCase["op_name"]                     = opName;
12439
12440                                         caseBodies      += testCaseBody.specialize(specCase);
12441                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12442                                 }
12443
12444                         specs["case_bodies"]    = caseBodies;
12445                         specs["case_list"]              = caseList;
12446                 }
12447
12448                 specs["num_elements"]                   = de::toString(structItemsCount);
12449                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12450                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12451                 specs["op_premain_decls"]               = opParts.premainDecls;
12452                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12453                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12454                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12455
12456                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12457                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12458                 fragments["decoration"]         = decoration.specialize(specs);
12459                 fragments["pre_main"]           = preMain.specialize(specs);
12460                 fragments["testfun"]            = testFun.specialize(specs);
12461
12462                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12463                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12464                 specResource.verifyIO = compareFP16CompositeFunc;
12465
12466                 extensions.push_back("VK_KHR_16bit_storage");
12467                 extensions.push_back("VK_KHR_shader_float16_int8");
12468
12469                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12470                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12471
12472                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12473         }
12474
12475         return testGroup.release();
12476 }
12477
12478 struct fp16PerComponent
12479 {
12480         fp16PerComponent()
12481                 : flavor(0)
12482                 , floatFormat16 (-14, 15, 10, true)
12483                 , outCompCount(0)
12484                 , argCompCount(3, 0)
12485         {
12486         }
12487
12488         bool                    callOncePerComponent    ()                                                                      { return true; }
12489         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12490
12491         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12492         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12493         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12494
12495         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12496         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12497         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12498         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12499
12500         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12501         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12502
12503         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12504         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12505
12506 protected:
12507         size_t                          flavor;
12508         tcu::FloatFormat        floatFormat16;
12509         size_t                          outCompCount;
12510         vector<size_t>          argCompCount;
12511         vector<string>          flavorNames;
12512 };
12513
12514 struct fp16OpFNegate : public fp16PerComponent
12515 {
12516         template <class fp16type>
12517         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12518         {
12519                 const fp16type  x               (*in[0]);
12520                 const double    d               (x.asDouble());
12521                 const double    result  (0.0 - d);
12522
12523                 out[0] = fp16type(result).bits();
12524                 min[0] = getMin(result, getULPs(in));
12525                 max[0] = getMax(result, getULPs(in));
12526
12527                 return true;
12528         }
12529 };
12530
12531 struct fp16Round : public fp16PerComponent
12532 {
12533         fp16Round() : fp16PerComponent()
12534         {
12535                 flavorNames.push_back("Floor(x+0.5)");
12536                 flavorNames.push_back("Floor(x-0.5)");
12537                 flavorNames.push_back("RoundEven");
12538         }
12539
12540         template<class fp16type>
12541         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12542         {
12543                 const fp16type  x               (*in[0]);
12544                 const double    d               (x.asDouble());
12545                 double                  result  (0.0);
12546
12547                 switch (flavor)
12548                 {
12549                         case 0:         result = deRound(d);            break;
12550                         case 1:         result = deFloor(d - 0.5);      break;
12551                         case 2:         result = deRoundEven(d);        break;
12552                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12553                 }
12554
12555                 out[0] = fp16type(result).bits();
12556                 min[0] = getMin(result, getULPs(in));
12557                 max[0] = getMax(result, getULPs(in));
12558
12559                 return true;
12560         }
12561 };
12562
12563 struct fp16RoundEven : public fp16PerComponent
12564 {
12565         template<class fp16type>
12566         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12567         {
12568                 const fp16type  x               (*in[0]);
12569                 const double    d               (x.asDouble());
12570                 const double    result  (deRoundEven(d));
12571
12572                 out[0] = fp16type(result).bits();
12573                 min[0] = getMin(result, getULPs(in));
12574                 max[0] = getMax(result, getULPs(in));
12575
12576                 return true;
12577         }
12578 };
12579
12580 struct fp16Trunc : public fp16PerComponent
12581 {
12582         template<class fp16type>
12583         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12584         {
12585                 const fp16type  x               (*in[0]);
12586                 const double    d               (x.asDouble());
12587                 const double    result  (deTrunc(d));
12588
12589                 out[0] = fp16type(result).bits();
12590                 min[0] = getMin(result, getULPs(in));
12591                 max[0] = getMax(result, getULPs(in));
12592
12593                 return true;
12594         }
12595 };
12596
12597 struct fp16FAbs : public fp16PerComponent
12598 {
12599         template<class fp16type>
12600         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12601         {
12602                 const fp16type  x               (*in[0]);
12603                 const double    d               (x.asDouble());
12604                 const double    result  (deAbs(d));
12605
12606                 out[0] = fp16type(result).bits();
12607                 min[0] = getMin(result, getULPs(in));
12608                 max[0] = getMax(result, getULPs(in));
12609
12610                 return true;
12611         }
12612 };
12613
12614 struct fp16FSign : public fp16PerComponent
12615 {
12616         template<class fp16type>
12617         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12618         {
12619                 const fp16type  x               (*in[0]);
12620                 const double    d               (x.asDouble());
12621                 const double    result  (deSign(d));
12622
12623                 if (x.isNaN())
12624                         return false;
12625
12626                 out[0] = fp16type(result).bits();
12627                 min[0] = getMin(result, getULPs(in));
12628                 max[0] = getMax(result, getULPs(in));
12629
12630                 return true;
12631         }
12632 };
12633
12634 struct fp16Floor : public fp16PerComponent
12635 {
12636         template<class fp16type>
12637         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12638         {
12639                 const fp16type  x               (*in[0]);
12640                 const double    d               (x.asDouble());
12641                 const double    result  (deFloor(d));
12642
12643                 out[0] = fp16type(result).bits();
12644                 min[0] = getMin(result, getULPs(in));
12645                 max[0] = getMax(result, getULPs(in));
12646
12647                 return true;
12648         }
12649 };
12650
12651 struct fp16Ceil : public fp16PerComponent
12652 {
12653         template<class fp16type>
12654         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12655         {
12656                 const fp16type  x               (*in[0]);
12657                 const double    d               (x.asDouble());
12658                 const double    result  (deCeil(d));
12659
12660                 out[0] = fp16type(result).bits();
12661                 min[0] = getMin(result, getULPs(in));
12662                 max[0] = getMax(result, getULPs(in));
12663
12664                 return true;
12665         }
12666 };
12667
12668 struct fp16Fract : public fp16PerComponent
12669 {
12670         template<class fp16type>
12671         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12672         {
12673                 const fp16type  x               (*in[0]);
12674                 const double    d               (x.asDouble());
12675                 const double    result  (deFrac(d));
12676
12677                 out[0] = fp16type(result).bits();
12678                 min[0] = getMin(result, getULPs(in));
12679                 max[0] = getMax(result, getULPs(in));
12680
12681                 return true;
12682         }
12683 };
12684
12685 struct fp16Radians : public fp16PerComponent
12686 {
12687         virtual double getULPs (vector<const deFloat16*>& in)
12688         {
12689                 DE_UNREF(in);
12690
12691                 return 2.5;
12692         }
12693
12694         template<class fp16type>
12695         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12696         {
12697                 const fp16type  x               (*in[0]);
12698                 const float             d               (x.asFloat());
12699                 const float             result  (deFloatRadians(d));
12700
12701                 out[0] = fp16type(result).bits();
12702                 min[0] = getMin(result, getULPs(in));
12703                 max[0] = getMax(result, getULPs(in));
12704
12705                 return true;
12706         }
12707 };
12708
12709 struct fp16Degrees : public fp16PerComponent
12710 {
12711         virtual double getULPs (vector<const deFloat16*>& in)
12712         {
12713                 DE_UNREF(in);
12714
12715                 return 2.5;
12716         }
12717
12718         template<class fp16type>
12719         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12720         {
12721                 const fp16type  x               (*in[0]);
12722                 const float             d               (x.asFloat());
12723                 const float             result  (deFloatDegrees(d));
12724
12725                 out[0] = fp16type(result).bits();
12726                 min[0] = getMin(result, getULPs(in));
12727                 max[0] = getMax(result, getULPs(in));
12728
12729                 return true;
12730         }
12731 };
12732
12733 struct fp16Sin : public fp16PerComponent
12734 {
12735         template<class fp16type>
12736         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12737         {
12738                 const fp16type  x                       (*in[0]);
12739                 const double    d                       (x.asDouble());
12740                 const double    result          (deSin(d));
12741                 const double    unspecUlp       (16.0);
12742                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12743
12744                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12745                         return false;
12746
12747                 out[0] = fp16type(result).bits();
12748                 min[0] = result - err;
12749                 max[0] = result + err;
12750
12751                 return true;
12752         }
12753 };
12754
12755 struct fp16Cos : public fp16PerComponent
12756 {
12757         template<class fp16type>
12758         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12759         {
12760                 const fp16type  x                       (*in[0]);
12761                 const double    d                       (x.asDouble());
12762                 const double    result          (deCos(d));
12763                 const double    unspecUlp       (16.0);
12764                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12765
12766                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12767                         return false;
12768
12769                 out[0] = fp16type(result).bits();
12770                 min[0] = result - err;
12771                 max[0] = result + err;
12772
12773                 return true;
12774         }
12775 };
12776
12777 struct fp16Tan : public fp16PerComponent
12778 {
12779         template<class fp16type>
12780         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12781         {
12782                 const fp16type  x               (*in[0]);
12783                 const double    d               (x.asDouble());
12784                 const double    result  (deTan(d));
12785
12786                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12787                         return false;
12788
12789                 out[0] = fp16type(result).bits();
12790                 {
12791                         const double    err                     = deLdExp(1.0, -7);
12792                         const double    s1                      = deSin(d) + err;
12793                         const double    s2                      = deSin(d) - err;
12794                         const double    c1                      = deCos(d) + err;
12795                         const double    c2                      = deCos(d) - err;
12796                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12797                         double                  edgeLeft        = out[0];
12798                         double                  edgeRight       = out[0];
12799
12800                         if (deSign(c1 * c2) < 0.0)
12801                         {
12802                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12803                                 edgeRight       = +std::numeric_limits<double>::infinity();
12804                         }
12805                         else
12806                         {
12807                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12808                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12809                         }
12810
12811                         min[0] = edgeLeft;
12812                         max[0] = edgeRight;
12813                 }
12814
12815                 return true;
12816         }
12817 };
12818
12819 struct fp16Asin : public fp16PerComponent
12820 {
12821         template<class fp16type>
12822         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12823         {
12824                 const fp16type  x               (*in[0]);
12825                 const double    d               (x.asDouble());
12826                 const double    result  (deAsin(d));
12827                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12828
12829                 if (!x.isNaN() && deAbs(d) > 1.0)
12830                         return false;
12831
12832                 out[0] = fp16type(result).bits();
12833                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12834                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12835
12836                 return true;
12837         }
12838 };
12839
12840 struct fp16Acos : public fp16PerComponent
12841 {
12842         template<class fp16type>
12843         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12844         {
12845                 const fp16type  x               (*in[0]);
12846                 const double    d               (x.asDouble());
12847                 const double    result  (deAcos(d));
12848                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12849
12850                 if (!x.isNaN() && deAbs(d) > 1.0)
12851                         return false;
12852
12853                 out[0] = fp16type(result).bits();
12854                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12855                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12856
12857                 return true;
12858         }
12859 };
12860
12861 struct fp16Atan : public fp16PerComponent
12862 {
12863         virtual double getULPs(vector<const deFloat16*>& in)
12864         {
12865                 DE_UNREF(in);
12866
12867                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12868         }
12869
12870         template<class fp16type>
12871         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12872         {
12873                 const fp16type  x               (*in[0]);
12874                 const double    d               (x.asDouble());
12875                 const double    result  (deAtanOver(d));
12876
12877                 out[0] = fp16type(result).bits();
12878                 min[0] = getMin(result, getULPs(in));
12879                 max[0] = getMax(result, getULPs(in));
12880
12881                 return true;
12882         }
12883 };
12884
12885 struct fp16Sinh : public fp16PerComponent
12886 {
12887         fp16Sinh() : fp16PerComponent()
12888         {
12889                 flavorNames.push_back("Double");
12890                 flavorNames.push_back("ExpFP16");
12891         }
12892
12893         template<class fp16type>
12894         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12895         {
12896                 const fp16type  x               (*in[0]);
12897                 const double    d               (x.asDouble());
12898                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12899                 double                  result  (0.0);
12900                 double                  error   (0.0);
12901
12902                 if (getFlavor() == 0)
12903                 {
12904                         result  = deSinh(d);
12905                         error   = floatFormat16.ulp(deAbs(result), ulps);
12906                 }
12907                 else if (getFlavor() == 1)
12908                 {
12909                         const fp16type  epx     (deExp(d));
12910                         const fp16type  enx     (deExp(-d));
12911                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12912                         const fp16type  sx2     (esx.asDouble() / 2.0);
12913
12914                         result  = sx2.asDouble();
12915                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12916                 }
12917                 else
12918                 {
12919                         TCU_THROW(InternalError, "Unknown flavor");
12920                 }
12921
12922                 out[0] = fp16type(result).bits();
12923                 min[0] = result - error;
12924                 max[0] = result + error;
12925
12926                 return true;
12927         }
12928 };
12929
12930 struct fp16Cosh : public fp16PerComponent
12931 {
12932         fp16Cosh() : fp16PerComponent()
12933         {
12934                 flavorNames.push_back("Double");
12935                 flavorNames.push_back("ExpFP16");
12936         }
12937
12938         template<class fp16type>
12939         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12940         {
12941                 const fp16type  x               (*in[0]);
12942                 const double    d               (x.asDouble());
12943                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12944                 double                  result  (0.0);
12945
12946                 if (getFlavor() == 0)
12947                 {
12948                         result = deCosh(d);
12949                 }
12950                 else if (getFlavor() == 1)
12951                 {
12952                         const fp16type  epx     (deExp(d));
12953                         const fp16type  enx     (deExp(-d));
12954                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12955                         const fp16type  sx2     (esx.asDouble() / 2.0);
12956
12957                         result = sx2.asDouble();
12958                 }
12959                 else
12960                 {
12961                         TCU_THROW(InternalError, "Unknown flavor");
12962                 }
12963
12964                 out[0] = fp16type(result).bits();
12965                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12966                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12967
12968                 return true;
12969         }
12970 };
12971
12972 struct fp16Tanh : public fp16PerComponent
12973 {
12974         fp16Tanh() : fp16PerComponent()
12975         {
12976                 flavorNames.push_back("Tanh");
12977                 flavorNames.push_back("SinhCosh");
12978                 flavorNames.push_back("SinhCoshFP16");
12979                 flavorNames.push_back("PolyFP16");
12980         }
12981
12982         virtual double getULPs (vector<const deFloat16*>& in)
12983         {
12984                 const tcu::Float16      x       (*in[0]);
12985                 const double            d       (x.asDouble());
12986
12987                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12988         }
12989
12990         template<class fp16type>
12991         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12992         {
12993                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12994                 const fp16type  sx2     (esx.asDouble() / 2.0);
12995                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12996                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12997                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12998                 const double    rez     (tg.asDouble());
12999
13000                 return rez;
13001         }
13002
13003         template<class fp16type>
13004         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13005         {
13006                 const fp16type  x               (*in[0]);
13007                 const double    d               (x.asDouble());
13008                 double                  result  (0.0);
13009
13010                 if (getFlavor() == 0)
13011                 {
13012                         result  = deTanh(d);
13013                         min[0]  = getMin(result, getULPs(in));
13014                         max[0]  = getMax(result, getULPs(in));
13015                 }
13016                 else if (getFlavor() == 1)
13017                 {
13018                         result  = deSinh(d) / deCosh(d);
13019                         min[0]  = getMin(result, getULPs(in));
13020                         max[0]  = getMax(result, getULPs(in));
13021                 }
13022                 else if (getFlavor() == 2)
13023                 {
13024                         const fp16type  s       (deSinh(d));
13025                         const fp16type  c       (deCosh(d));
13026
13027                         result  = s.asDouble() / c.asDouble();
13028                         min[0]  = getMin(result, getULPs(in));
13029                         max[0]  = getMax(result, getULPs(in));
13030                 }
13031                 else if (getFlavor() == 3)
13032                 {
13033                         const double    ulps    (getULPs(in));
13034                         const double    epxm    (deExp( d));
13035                         const double    enxm    (deExp(-d));
13036                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
13037                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
13038                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
13039                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
13040                         const fp16type  epxm16  (epxm);
13041                         const fp16type  enxm16  (enxm);
13042                         vector<double>  tgs;
13043
13044                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
13045                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
13046                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
13047                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
13048                         {
13049                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
13050
13051                                 tgs.push_back(tgh);
13052                         }
13053
13054                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
13055                         min[0] = *std::min_element(tgs.begin(), tgs.end());
13056                         max[0] = *std::max_element(tgs.begin(), tgs.end());
13057                 }
13058                 else
13059                 {
13060                         TCU_THROW(InternalError, "Unknown flavor");
13061                 }
13062
13063                 out[0] = fp16type(result).bits();
13064
13065                 return true;
13066         }
13067 };
13068
13069 struct fp16Asinh : public fp16PerComponent
13070 {
13071         fp16Asinh() : fp16PerComponent()
13072         {
13073                 flavorNames.push_back("Double");
13074                 flavorNames.push_back("PolyFP16Wiki");
13075                 flavorNames.push_back("PolyFP16Abs");
13076         }
13077
13078         virtual double getULPs (vector<const deFloat16*>& in)
13079         {
13080                 DE_UNREF(in);
13081
13082                 return 256.0; // This is not a precision test. Value is not from spec
13083         }
13084
13085         template<class fp16type>
13086         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13087         {
13088                 const fp16type  x               (*in[0]);
13089                 const double    d               (x.asDouble());
13090                 double                  result  (0.0);
13091
13092                 if (getFlavor() == 0)
13093                 {
13094                         result = deAsinh(d);
13095                 }
13096                 else if (getFlavor() == 1)
13097                 {
13098                         const fp16type  x2              (d * d);
13099                         const fp16type  x2p1    (x2.asDouble() + 1.0);
13100                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
13101                         const fp16type  sxsq    (d + sq.asDouble());
13102                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13103
13104                         if (lsxsq.isInf())
13105                                 return false;
13106
13107                         result = lsxsq.asDouble();
13108                 }
13109                 else if (getFlavor() == 2)
13110                 {
13111                         const fp16type  x2              (d * d);
13112                         const fp16type  x2p1    (x2.asDouble() + 1.0);
13113                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
13114                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
13115                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13116
13117                         result = deSign(d) * lsxsq.asDouble();
13118                 }
13119                 else
13120                 {
13121                         TCU_THROW(InternalError, "Unknown flavor");
13122                 }
13123
13124                 out[0] = fp16type(result).bits();
13125                 min[0] = getMin(result, getULPs(in));
13126                 max[0] = getMax(result, getULPs(in));
13127
13128                 return true;
13129         }
13130 };
13131
13132 struct fp16Acosh : public fp16PerComponent
13133 {
13134         fp16Acosh() : fp16PerComponent()
13135         {
13136                 flavorNames.push_back("Double");
13137                 flavorNames.push_back("PolyFP16");
13138         }
13139
13140         virtual double getULPs (vector<const deFloat16*>& in)
13141         {
13142                 DE_UNREF(in);
13143
13144                 return 16.0; // This is not a precision test. Value is not from spec
13145         }
13146
13147         template<class fp16type>
13148         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13149         {
13150                 const fp16type  x               (*in[0]);
13151                 const double    d               (x.asDouble());
13152                 double                  result  (0.0);
13153
13154                 if (!x.isNaN() && d < 1.0)
13155                         return false;
13156
13157                 if (getFlavor() == 0)
13158                 {
13159                         result = deAcosh(d);
13160                 }
13161                 else if (getFlavor() == 1)
13162                 {
13163                         const fp16type  x2              (d * d);
13164                         const fp16type  x2m1    (x2.asDouble() - 1.0);
13165                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
13166                         const fp16type  sxsq    (d + sq.asDouble());
13167                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13168
13169                         result = lsxsq.asDouble();
13170                 }
13171                 else
13172                 {
13173                         TCU_THROW(InternalError, "Unknown flavor");
13174                 }
13175
13176                 out[0] = fp16type(result).bits();
13177                 min[0] = getMin(result, getULPs(in));
13178                 max[0] = getMax(result, getULPs(in));
13179
13180                 return true;
13181         }
13182 };
13183
13184 struct fp16Atanh : public fp16PerComponent
13185 {
13186         fp16Atanh() : fp16PerComponent()
13187         {
13188                 flavorNames.push_back("Double");
13189                 flavorNames.push_back("PolyFP16");
13190         }
13191
13192         template<class fp16type>
13193         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13194         {
13195                 const fp16type  x               (*in[0]);
13196                 const double    d               (x.asDouble());
13197                 double                  result  (0.0);
13198
13199                 if (deAbs(d) >= 1.0)
13200                         return false;
13201
13202                 if (getFlavor() == 0)
13203                 {
13204                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
13205
13206                         result = deAtanh(d);
13207                         min[0] = getMin(result, ulps);
13208                         max[0] = getMax(result, ulps);
13209                 }
13210                 else if (getFlavor() == 1)
13211                 {
13212                         const fp16type  x1a             (1.0 + d);
13213                         const fp16type  x1b             (1.0 - d);
13214                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13215                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13216                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13217                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13218
13219                         result = lx1d2.asDouble();
13220                         min[0] = result - error;
13221                         max[0] = result + error;
13222                 }
13223                 else
13224                 {
13225                         TCU_THROW(InternalError, "Unknown flavor");
13226                 }
13227
13228                 out[0] = fp16type(result).bits();
13229
13230                 return true;
13231         }
13232 };
13233
13234 struct fp16Exp : public fp16PerComponent
13235 {
13236         template<class fp16type>
13237         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13238         {
13239                 const fp16type  x               (*in[0]);
13240                 const double    d               (x.asDouble());
13241                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13242                 const double    result  (deExp(d));
13243
13244                 out[0] = fp16type(result).bits();
13245                 min[0] = getMin(result, ulps);
13246                 max[0] = getMax(result, ulps);
13247
13248                 return true;
13249         }
13250 };
13251
13252 struct fp16Log : public fp16PerComponent
13253 {
13254         template<class fp16type>
13255         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13256         {
13257                 const fp16type  x               (*in[0]);
13258                 const double    d               (x.asDouble());
13259                 const double    result  (deLog(d));
13260                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13261
13262                 if (d <= 0.0)
13263                         return false;
13264
13265                 out[0] = fp16type(result).bits();
13266                 min[0] = result - error;
13267                 max[0] = result + error;
13268
13269                 return true;
13270         }
13271 };
13272
13273 struct fp16Exp2 : public fp16PerComponent
13274 {
13275         template<class fp16type>
13276         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13277         {
13278                 const fp16type  x               (*in[0]);
13279                 const double    d               (x.asDouble());
13280                 const double    result  (deExp2(d));
13281                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13282
13283                 out[0] = fp16type(result).bits();
13284                 min[0] = getMin(result, ulps);
13285                 max[0] = getMax(result, ulps);
13286
13287                 return true;
13288         }
13289 };
13290
13291 struct fp16Log2 : public fp16PerComponent
13292 {
13293         template<class fp16type>
13294         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13295         {
13296                 const fp16type  x               (*in[0]);
13297                 const double    d               (x.asDouble());
13298                 const double    result  (deLog2(d));
13299                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13300
13301                 if (d <= 0.0)
13302                         return false;
13303
13304                 out[0] = fp16type(result).bits();
13305                 min[0] = result - error;
13306                 max[0] = result + error;
13307
13308                 return true;
13309         }
13310 };
13311
13312 struct fp16Sqrt : public fp16PerComponent
13313 {
13314         virtual double getULPs (vector<const deFloat16*>& in)
13315         {
13316                 DE_UNREF(in);
13317
13318                 return 6.0;
13319         }
13320
13321         template<class fp16type>
13322         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13323         {
13324                 const fp16type  x               (*in[0]);
13325                 const double    d               (x.asDouble());
13326                 const double    result  (deSqrt(d));
13327
13328                 if (!x.isNaN() && d < 0.0)
13329                         return false;
13330
13331                 out[0] = fp16type(result).bits();
13332                 min[0] = getMin(result, getULPs(in));
13333                 max[0] = getMax(result, getULPs(in));
13334
13335                 return true;
13336         }
13337 };
13338
13339 struct fp16InverseSqrt : public fp16PerComponent
13340 {
13341         virtual double getULPs (vector<const deFloat16*>& in)
13342         {
13343                 DE_UNREF(in);
13344
13345                 return 2.0;
13346         }
13347
13348         template<class fp16type>
13349         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13350         {
13351                 const fp16type  x               (*in[0]);
13352                 const double    d               (x.asDouble());
13353                 const double    result  (1.0/deSqrt(d));
13354
13355                 if (!x.isNaN() && d <= 0.0)
13356                         return false;
13357
13358                 out[0] = fp16type(result).bits();
13359                 min[0] = getMin(result, getULPs(in));
13360                 max[0] = getMax(result, getULPs(in));
13361
13362                 return true;
13363         }
13364 };
13365
13366 struct fp16ModfFrac : public fp16PerComponent
13367 {
13368         template<class fp16type>
13369         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13370         {
13371                 const fp16type  x               (*in[0]);
13372                 const double    d               (x.asDouble());
13373                 double                  i               (0.0);
13374                 const double    result  (deModf(d, &i));
13375
13376                 if (x.isInf() || x.isNaN())
13377                         return false;
13378
13379                 out[0] = fp16type(result).bits();
13380                 min[0] = getMin(result, getULPs(in));
13381                 max[0] = getMax(result, getULPs(in));
13382
13383                 return true;
13384         }
13385 };
13386
13387 struct fp16ModfInt : public fp16PerComponent
13388 {
13389         template<class fp16type>
13390         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13391         {
13392                 const fp16type  x               (*in[0]);
13393                 const double    d               (x.asDouble());
13394                 double                  i               (0.0);
13395                 const double    dummy   (deModf(d, &i));
13396                 const double    result  (i);
13397
13398                 DE_UNREF(dummy);
13399
13400                 if (x.isInf() || x.isNaN())
13401                         return false;
13402
13403                 out[0] = fp16type(result).bits();
13404                 min[0] = getMin(result, getULPs(in));
13405                 max[0] = getMax(result, getULPs(in));
13406
13407                 return true;
13408         }
13409 };
13410
13411 struct fp16FrexpS : public fp16PerComponent
13412 {
13413         template<class fp16type>
13414         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13415         {
13416                 const fp16type  x               (*in[0]);
13417                 const double    d               (x.asDouble());
13418                 int                             e               (0);
13419                 const double    result  (deFrExp(d, &e));
13420
13421                 if (x.isNaN() || x.isInf())
13422                         return false;
13423
13424                 out[0] = fp16type(result).bits();
13425                 min[0] = getMin(result, getULPs(in));
13426                 max[0] = getMax(result, getULPs(in));
13427
13428                 return true;
13429         }
13430 };
13431
13432 struct fp16FrexpE : public fp16PerComponent
13433 {
13434         template<class fp16type>
13435         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13436         {
13437                 const fp16type  x               (*in[0]);
13438                 const double    d               (x.asDouble());
13439                 int                             e               (0);
13440                 const double    dummy   (deFrExp(d, &e));
13441                 const double    result  (static_cast<double>(e));
13442
13443                 DE_UNREF(dummy);
13444
13445                 if (x.isNaN() || x.isInf())
13446                         return false;
13447
13448                 out[0] = fp16type(result).bits();
13449                 min[0] = getMin(result, getULPs(in));
13450                 max[0] = getMax(result, getULPs(in));
13451
13452                 return true;
13453         }
13454 };
13455
13456 struct fp16OpFAdd : public fp16PerComponent
13457 {
13458         template<class fp16type>
13459         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13460         {
13461                 const fp16type  x               (*in[0]);
13462                 const fp16type  y               (*in[1]);
13463                 const double    xd              (x.asDouble());
13464                 const double    yd              (y.asDouble());
13465                 const double    result  (xd + yd);
13466
13467                 out[0] = fp16type(result).bits();
13468                 min[0] = getMin(result, getULPs(in));
13469                 max[0] = getMax(result, getULPs(in));
13470
13471                 return true;
13472         }
13473 };
13474
13475 struct fp16OpFSub : public fp16PerComponent
13476 {
13477         template<class fp16type>
13478         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13479         {
13480                 const fp16type  x               (*in[0]);
13481                 const fp16type  y               (*in[1]);
13482                 const double    xd              (x.asDouble());
13483                 const double    yd              (y.asDouble());
13484                 const double    result  (xd - yd);
13485
13486                 out[0] = fp16type(result).bits();
13487                 min[0] = getMin(result, getULPs(in));
13488                 max[0] = getMax(result, getULPs(in));
13489
13490                 return true;
13491         }
13492 };
13493
13494 struct fp16OpFMul : public fp16PerComponent
13495 {
13496         template<class fp16type>
13497         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13498         {
13499                 const fp16type  x               (*in[0]);
13500                 const fp16type  y               (*in[1]);
13501                 const double    xd              (x.asDouble());
13502                 const double    yd              (y.asDouble());
13503                 const double    result  (xd * yd);
13504
13505                 out[0] = fp16type(result).bits();
13506                 min[0] = getMin(result, getULPs(in));
13507                 max[0] = getMax(result, getULPs(in));
13508
13509                 return true;
13510         }
13511 };
13512
13513 struct fp16OpFDiv : public fp16PerComponent
13514 {
13515         fp16OpFDiv() : fp16PerComponent()
13516         {
13517                 flavorNames.push_back("DirectDiv");
13518                 flavorNames.push_back("InverseDiv");
13519         }
13520
13521         template<class fp16type>
13522         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13523         {
13524                 const fp16type  x                       (*in[0]);
13525                 const fp16type  y                       (*in[1]);
13526                 const double    xd                      (x.asDouble());
13527                 const double    yd                      (y.asDouble());
13528                 const double    unspecUlp       (16.0);
13529                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13530                 double                  result          (0.0);
13531
13532                 if (y.isZero())
13533                         return false;
13534
13535                 if (getFlavor() == 0)
13536                 {
13537                         result = (xd / yd);
13538                 }
13539                 else if (getFlavor() == 1)
13540                 {
13541                         const double    invyd   (1.0 / yd);
13542                         const fp16type  invy    (invyd);
13543
13544                         result = (xd * invy.asDouble());
13545                 }
13546                 else
13547                 {
13548                         TCU_THROW(InternalError, "Unknown flavor");
13549                 }
13550
13551                 out[0] = fp16type(result).bits();
13552                 min[0] = getMin(result, ulpCnt);
13553                 max[0] = getMax(result, ulpCnt);
13554
13555                 return true;
13556         }
13557 };
13558
13559 struct fp16Atan2 : public fp16PerComponent
13560 {
13561         fp16Atan2() : fp16PerComponent()
13562         {
13563                 flavorNames.push_back("DoubleCalc");
13564                 flavorNames.push_back("DoubleCalc_PI");
13565         }
13566
13567         virtual double getULPs(vector<const deFloat16*>& in)
13568         {
13569                 DE_UNREF(in);
13570
13571                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13572         }
13573
13574         template<class fp16type>
13575         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13576         {
13577                 const fp16type  x               (*in[0]);
13578                 const fp16type  y               (*in[1]);
13579                 const double    xd              (x.asDouble());
13580                 const double    yd              (y.asDouble());
13581                 double                  result  (0.0);
13582
13583                 if (x.isZero() && y.isZero())
13584                         return false;
13585
13586                 if (getFlavor() == 0)
13587                 {
13588                         result  = deAtan2(xd, yd);
13589                 }
13590                 else if (getFlavor() == 1)
13591                 {
13592                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13593                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13594
13595                         result  = deAtan2(xd, yd);
13596
13597                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13598                                 result  = -result;
13599                 }
13600                 else
13601                 {
13602                         TCU_THROW(InternalError, "Unknown flavor");
13603                 }
13604
13605                 out[0] = fp16type(result).bits();
13606                 min[0] = getMin(result, getULPs(in));
13607                 max[0] = getMax(result, getULPs(in));
13608
13609                 return true;
13610         }
13611 };
13612
13613 struct fp16Pow : public fp16PerComponent
13614 {
13615         fp16Pow() : fp16PerComponent()
13616         {
13617                 flavorNames.push_back("Pow");
13618                 flavorNames.push_back("PowLog2");
13619                 flavorNames.push_back("PowLog2FP16");
13620         }
13621
13622         template<class fp16type>
13623         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13624         {
13625                 const fp16type  x               (*in[0]);
13626                 const fp16type  y               (*in[1]);
13627                 const double    xd              (x.asDouble());
13628                 const double    yd              (y.asDouble());
13629                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13630                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13631                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13632                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13633                 double                  result  (0.0);
13634
13635                 if (xd < 0.0)
13636                         return false;
13637
13638                 if (x.isZero() && yd <= 0.0)
13639                         return false;
13640
13641                 if (getFlavor() == 0)
13642                 {
13643                         result = dePow(xd, yd);
13644                 }
13645                 else if (getFlavor() == 1)
13646                 {
13647                         const double    l2d     (deLog2(xd));
13648                         const double    e2d     (deExp2(yd * l2d));
13649
13650                         result = e2d;
13651                 }
13652                 else if (getFlavor() == 2)
13653                 {
13654                         const double    l2d     (deLog2(xd));
13655                         const fp16type  l2      (l2d);
13656                         const double    e2d     (deExp2(yd * l2.asDouble()));
13657                         const fp16type  e2      (e2d);
13658
13659                         result = e2.asDouble();
13660                 }
13661                 else
13662                 {
13663                         TCU_THROW(InternalError, "Unknown flavor");
13664                 }
13665
13666                 out[0] = fp16type(result).bits();
13667                 min[0] = getMin(result, ulps);
13668                 max[0] = getMax(result, ulps);
13669
13670                 return true;
13671         }
13672 };
13673
13674 struct fp16FMin : public fp16PerComponent
13675 {
13676         template<class fp16type>
13677         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13678         {
13679                 const fp16type  x               (*in[0]);
13680                 const fp16type  y               (*in[1]);
13681                 const double    xd              (x.asDouble());
13682                 const double    yd              (y.asDouble());
13683                 const double    result  (deMin(xd, yd));
13684
13685                 if (x.isNaN() || y.isNaN())
13686                         return false;
13687
13688                 out[0] = fp16type(result).bits();
13689                 min[0] = getMin(result, getULPs(in));
13690                 max[0] = getMax(result, getULPs(in));
13691
13692                 return true;
13693         }
13694 };
13695
13696 struct fp16FMax : public fp16PerComponent
13697 {
13698         template<class fp16type>
13699         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13700         {
13701                 const fp16type  x               (*in[0]);
13702                 const fp16type  y               (*in[1]);
13703                 const double    xd              (x.asDouble());
13704                 const double    yd              (y.asDouble());
13705                 const double    result  (deMax(xd, yd));
13706
13707                 if (x.isNaN() || y.isNaN())
13708                         return false;
13709
13710                 out[0] = fp16type(result).bits();
13711                 min[0] = getMin(result, getULPs(in));
13712                 max[0] = getMax(result, getULPs(in));
13713
13714                 return true;
13715         }
13716 };
13717
13718 struct fp16Step : public fp16PerComponent
13719 {
13720         template<class fp16type>
13721         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13722         {
13723                 const fp16type  edge    (*in[0]);
13724                 const fp16type  x               (*in[1]);
13725                 const double    edged   (edge.asDouble());
13726                 const double    xd              (x.asDouble());
13727                 const double    result  (deStep(edged, xd));
13728
13729                 out[0] = fp16type(result).bits();
13730                 min[0] = getMin(result, getULPs(in));
13731                 max[0] = getMax(result, getULPs(in));
13732
13733                 return true;
13734         }
13735 };
13736
13737 struct fp16Ldexp : public fp16PerComponent
13738 {
13739         template<class fp16type>
13740         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13741         {
13742                 const fp16type  x               (*in[0]);
13743                 const fp16type  y               (*in[1]);
13744                 const double    xd              (x.asDouble());
13745                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13746                 const double    result  (deLdExp(xd, yd));
13747
13748                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13749                         return false;
13750
13751                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13752                 if (fp16type(result).isInf())
13753                         return false;
13754
13755                 out[0] = fp16type(result).bits();
13756                 min[0] = getMin(result, getULPs(in));
13757                 max[0] = getMax(result, getULPs(in));
13758
13759                 return true;
13760         }
13761 };
13762
13763 struct fp16FClamp : public fp16PerComponent
13764 {
13765         template<class fp16type>
13766         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13767         {
13768                 const fp16type  x               (*in[0]);
13769                 const fp16type  minVal  (*in[1]);
13770                 const fp16type  maxVal  (*in[2]);
13771                 const double    xd              (x.asDouble());
13772                 const double    minVald (minVal.asDouble());
13773                 const double    maxVald (maxVal.asDouble());
13774                 const double    result  (deClamp(xd, minVald, maxVald));
13775
13776                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13777                         return false;
13778
13779                 out[0] = fp16type(result).bits();
13780                 min[0] = getMin(result, getULPs(in));
13781                 max[0] = getMax(result, getULPs(in));
13782
13783                 return true;
13784         }
13785 };
13786
13787 struct fp16FMix : public fp16PerComponent
13788 {
13789         fp16FMix() : fp16PerComponent()
13790         {
13791                 flavorNames.push_back("DoubleCalc");
13792                 flavorNames.push_back("EmulatingFP16");
13793                 flavorNames.push_back("EmulatingFP16YminusX");
13794         }
13795
13796         template<class fp16type>
13797         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13798         {
13799                 const fp16type  x               (*in[0]);
13800                 const fp16type  y               (*in[1]);
13801                 const fp16type  a               (*in[2]);
13802                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13803                 double                  result  (0.0);
13804
13805                 if (getFlavor() == 0)
13806                 {
13807                         const double    xd              (x.asDouble());
13808                         const double    yd              (y.asDouble());
13809                         const double    ad              (a.asDouble());
13810                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13811                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13812                         const double    eps             (xeps + yeps);
13813
13814                         result = deMix(xd, yd, ad);
13815                         min[0] = result - eps;
13816                         max[0] = result + eps;
13817                 }
13818                 else if (getFlavor() == 1)
13819                 {
13820                         const double    xd              (x.asDouble());
13821                         const double    yd              (y.asDouble());
13822                         const double    ad              (a.asDouble());
13823                         const fp16type  am              (1.0 - ad);
13824                         const double    amd             (am.asDouble());
13825                         const fp16type  xam             (xd * amd);
13826                         const double    xamd    (xam.asDouble());
13827                         const fp16type  ya              (yd * ad);
13828                         const double    yad             (ya.asDouble());
13829                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13830                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13831                         const double    eps             (xeps + yeps);
13832
13833                         result = xamd + yad;
13834                         min[0] = result - eps;
13835                         max[0] = result + eps;
13836                 }
13837                 else if (getFlavor() == 2)
13838                 {
13839                         const double    xd              (x.asDouble());
13840                         const double    yd              (y.asDouble());
13841                         const double    ad              (a.asDouble());
13842                         const fp16type  ymx             (yd - xd);
13843                         const double    ymxd    (ymx.asDouble());
13844                         const fp16type  ymxa    (ymxd * ad);
13845                         const double    ymxad   (ymxa.asDouble());
13846                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13847                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13848                         const double    eps             (xeps + yeps);
13849
13850                         result = xd + ymxad;
13851                         min[0] = result - eps;
13852                         max[0] = result + eps;
13853                 }
13854                 else
13855                 {
13856                         TCU_THROW(InternalError, "Unknown flavor");
13857                 }
13858
13859                 out[0] = fp16type(result).bits();
13860
13861                 return true;
13862         }
13863 };
13864
13865 struct fp16SmoothStep : public fp16PerComponent
13866 {
13867         fp16SmoothStep() : fp16PerComponent()
13868         {
13869                 flavorNames.push_back("FloatCalc");
13870                 flavorNames.push_back("EmulatingFP16");
13871                 flavorNames.push_back("EmulatingFP16WClamp");
13872         }
13873
13874         virtual double getULPs(vector<const deFloat16*>& in)
13875         {
13876                 DE_UNREF(in);
13877
13878                 return 4.0; // This is not a precision test. Value is not from spec
13879         }
13880
13881         template<class fp16type>
13882         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13883         {
13884                 const fp16type  edge0   (*in[0]);
13885                 const fp16type  edge1   (*in[1]);
13886                 const fp16type  x               (*in[2]);
13887                 double                  result  (0.0);
13888
13889                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13890                         return false;
13891
13892                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13893                         return false;
13894
13895                 if (getFlavor() == 0)
13896                 {
13897                         const float     edge0d  (edge0.asFloat());
13898                         const float     edge1d  (edge1.asFloat());
13899                         const float     xd              (x.asFloat());
13900                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13901
13902                         result = sstep;
13903                 }
13904                 else if (getFlavor() == 1)
13905                 {
13906                         const double    edge0d  (edge0.asDouble());
13907                         const double    edge1d  (edge1.asDouble());
13908                         const double    xd              (x.asDouble());
13909
13910                         if (xd <= edge0d)
13911                                 result = 0.0;
13912                         else if (xd >= edge1d)
13913                                 result = 1.0;
13914                         else
13915                         {
13916                                 const fp16type  a       (xd - edge0d);
13917                                 const fp16type  b       (edge1d - edge0d);
13918                                 const fp16type  t       (a.asDouble() / b.asDouble());
13919                                 const fp16type  t2      (2.0 * t.asDouble());
13920                                 const fp16type  t3      (3.0 - t2.asDouble());
13921                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13922                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13923
13924                                 result = t5.asDouble();
13925                         }
13926                 }
13927                 else if (getFlavor() == 2)
13928                 {
13929                         const double    edge0d  (edge0.asDouble());
13930                         const double    edge1d  (edge1.asDouble());
13931                         const double    xd              (x.asDouble());
13932                         const fp16type  a       (xd - edge0d);
13933                         const fp16type  b       (edge1d - edge0d);
13934                         const fp16type  bi      (1.0 / b.asDouble());
13935                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13936                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13937                         const fp16type  t       (tc);
13938                         const fp16type  t2      (2.0 * t.asDouble());
13939                         const fp16type  t3      (3.0 - t2.asDouble());
13940                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13941                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13942
13943                         result = t5.asDouble();
13944                 }
13945                 else
13946                 {
13947                         TCU_THROW(InternalError, "Unknown flavor");
13948                 }
13949
13950                 out[0] = fp16type(result).bits();
13951                 min[0] = getMin(result, getULPs(in));
13952                 max[0] = getMax(result, getULPs(in));
13953
13954                 return true;
13955         }
13956 };
13957
13958 struct fp16Fma : public fp16PerComponent
13959 {
13960         fp16Fma()
13961         {
13962                 flavorNames.push_back("DoubleCalc");
13963                 flavorNames.push_back("EmulatingFP16");
13964         }
13965
13966         virtual double getULPs(vector<const deFloat16*>& in)
13967         {
13968                 DE_UNREF(in);
13969
13970                 return 16.0;
13971         }
13972
13973         template<class fp16type>
13974         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13975         {
13976                 DE_ASSERT(in.size() == 3);
13977                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13978                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13979                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13980                 DE_ASSERT(getOutCompCount() > 0);
13981
13982                 const fp16type  a               (*in[0]);
13983                 const fp16type  b               (*in[1]);
13984                 const fp16type  c               (*in[2]);
13985                 double                  result  (0.0);
13986
13987                 if (getFlavor() == 0)
13988                 {
13989                         const double    ad      (a.asDouble());
13990                         const double    bd      (b.asDouble());
13991                         const double    cd      (c.asDouble());
13992
13993                         result  = deMadd(ad, bd, cd);
13994                 }
13995                 else if (getFlavor() == 1)
13996                 {
13997                         const double    ad      (a.asDouble());
13998                         const double    bd      (b.asDouble());
13999                         const double    cd      (c.asDouble());
14000                         const fp16type  ab      (ad * bd);
14001                         const fp16type  r       (ab.asDouble() + cd);
14002
14003                         result  = r.asDouble();
14004                 }
14005                 else
14006                 {
14007                         TCU_THROW(InternalError, "Unknown flavor");
14008                 }
14009
14010                 out[0] = fp16type(result).bits();
14011                 min[0] = getMin(result, getULPs(in));
14012                 max[0] = getMax(result, getULPs(in));
14013
14014                 return true;
14015         }
14016 };
14017
14018
14019 struct fp16AllComponents : public fp16PerComponent
14020 {
14021         bool            callOncePerComponent    ()      { return false; }
14022 };
14023
14024 struct fp16Length : public fp16AllComponents
14025 {
14026         fp16Length() : fp16AllComponents()
14027         {
14028                 flavorNames.push_back("EmulatingFP16");
14029                 flavorNames.push_back("DoubleCalc");
14030         }
14031
14032         virtual double getULPs(vector<const deFloat16*>& in)
14033         {
14034                 DE_UNREF(in);
14035
14036                 return 4.0;
14037         }
14038
14039         template<class fp16type>
14040         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14041         {
14042                 DE_ASSERT(getOutCompCount() == 1);
14043                 DE_ASSERT(in.size() == 1);
14044
14045                 double  result  (0.0);
14046
14047                 if (getFlavor() == 0)
14048                 {
14049                         fp16type        r       (0.0);
14050
14051                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14052                         {
14053                                 const fp16type  x       (in[0][componentNdx]);
14054                                 const fp16type  q       (x.asDouble() * x.asDouble());
14055
14056                                 r = fp16type(r.asDouble() + q.asDouble());
14057                         }
14058
14059                         result = deSqrt(r.asDouble());
14060
14061                         out[0] = fp16type(result).bits();
14062                 }
14063                 else if (getFlavor() == 1)
14064                 {
14065                         double  r       (0.0);
14066
14067                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14068                         {
14069                                 const fp16type  x       (in[0][componentNdx]);
14070                                 const double    q       (x.asDouble() * x.asDouble());
14071
14072                                 r += q;
14073                         }
14074
14075                         result = deSqrt(r);
14076
14077                         out[0] = fp16type(result).bits();
14078                 }
14079                 else
14080                 {
14081                         TCU_THROW(InternalError, "Unknown flavor");
14082                 }
14083
14084                 min[0] = getMin(result, getULPs(in));
14085                 max[0] = getMax(result, getULPs(in));
14086
14087                 return true;
14088         }
14089 };
14090
14091 struct fp16Distance : public fp16AllComponents
14092 {
14093         fp16Distance() : fp16AllComponents()
14094         {
14095                 flavorNames.push_back("EmulatingFP16");
14096                 flavorNames.push_back("DoubleCalc");
14097         }
14098
14099         virtual double getULPs(vector<const deFloat16*>& in)
14100         {
14101                 DE_UNREF(in);
14102
14103                 return 4.0;
14104         }
14105
14106         template<class fp16type>
14107         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14108         {
14109                 DE_ASSERT(getOutCompCount() == 1);
14110                 DE_ASSERT(in.size() == 2);
14111                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14112
14113                 double  result  (0.0);
14114
14115                 if (getFlavor() == 0)
14116                 {
14117                         fp16type        r       (0.0);
14118
14119                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14120                         {
14121                                 const fp16type  x       (in[0][componentNdx]);
14122                                 const fp16type  y       (in[1][componentNdx]);
14123                                 const fp16type  d       (x.asDouble() - y.asDouble());
14124                                 const fp16type  q       (d.asDouble() * d.asDouble());
14125
14126                                 r = fp16type(r.asDouble() + q.asDouble());
14127                         }
14128
14129                         result = deSqrt(r.asDouble());
14130                 }
14131                 else if (getFlavor() == 1)
14132                 {
14133                         double  r       (0.0);
14134
14135                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14136                         {
14137                                 const fp16type  x       (in[0][componentNdx]);
14138                                 const fp16type  y       (in[1][componentNdx]);
14139                                 const double    d       (x.asDouble() - y.asDouble());
14140                                 const double    q       (d * d);
14141
14142                                 r += q;
14143                         }
14144
14145                         result = deSqrt(r);
14146                 }
14147                 else
14148                 {
14149                         TCU_THROW(InternalError, "Unknown flavor");
14150                 }
14151
14152                 out[0] = fp16type(result).bits();
14153                 min[0] = getMin(result, getULPs(in));
14154                 max[0] = getMax(result, getULPs(in));
14155
14156                 return true;
14157         }
14158 };
14159
14160 struct fp16Cross : public fp16AllComponents
14161 {
14162         fp16Cross() : fp16AllComponents()
14163         {
14164                 flavorNames.push_back("EmulatingFP16");
14165                 flavorNames.push_back("DoubleCalc");
14166         }
14167
14168         virtual double getULPs(vector<const deFloat16*>& in)
14169         {
14170                 DE_UNREF(in);
14171
14172                 return 4.0;
14173         }
14174
14175         template<class fp16type>
14176         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14177         {
14178                 DE_ASSERT(getOutCompCount() == 3);
14179                 DE_ASSERT(in.size() == 2);
14180                 DE_ASSERT(getArgCompCount(0) == 3);
14181                 DE_ASSERT(getArgCompCount(1) == 3);
14182
14183                 if (getFlavor() == 0)
14184                 {
14185                         const fp16type  x0              (in[0][0]);
14186                         const fp16type  x1              (in[0][1]);
14187                         const fp16type  x2              (in[0][2]);
14188                         const fp16type  y0              (in[1][0]);
14189                         const fp16type  y1              (in[1][1]);
14190                         const fp16type  y2              (in[1][2]);
14191                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
14192                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
14193                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
14194                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
14195                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
14196                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
14197
14198                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
14199                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
14200                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
14201                 }
14202                 else if (getFlavor() == 1)
14203                 {
14204                         const fp16type  x0              (in[0][0]);
14205                         const fp16type  x1              (in[0][1]);
14206                         const fp16type  x2              (in[0][2]);
14207                         const fp16type  y0              (in[1][0]);
14208                         const fp16type  y1              (in[1][1]);
14209                         const fp16type  y2              (in[1][2]);
14210                         const double    x1y2    (x1.asDouble() * y2.asDouble());
14211                         const double    y1x2    (y1.asDouble() * x2.asDouble());
14212                         const double    x2y0    (x2.asDouble() * y0.asDouble());
14213                         const double    y2x0    (y2.asDouble() * x0.asDouble());
14214                         const double    x0y1    (x0.asDouble() * y1.asDouble());
14215                         const double    y0x1    (y0.asDouble() * x1.asDouble());
14216
14217                         out[0] = fp16type(x1y2 - y1x2).bits();
14218                         out[1] = fp16type(x2y0 - y2x0).bits();
14219                         out[2] = fp16type(x0y1 - y0x1).bits();
14220                 }
14221                 else
14222                 {
14223                         TCU_THROW(InternalError, "Unknown flavor");
14224                 }
14225
14226                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14227                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14228                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14229                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14230
14231                 return true;
14232         }
14233 };
14234
14235 struct fp16Normalize : public fp16AllComponents
14236 {
14237         fp16Normalize() : fp16AllComponents()
14238         {
14239                 flavorNames.push_back("EmulatingFP16");
14240                 flavorNames.push_back("DoubleCalc");
14241
14242                 // flavorNames will be extended later
14243         }
14244
14245         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14246         {
14247                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14248
14249                 if (argNo == 0 && argCompCount[argNo] == 0)
14250                 {
14251                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14252                         std::vector<int>        indices;
14253
14254                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14255                                 indices.push_back(static_cast<int>(componentNdx));
14256
14257                         m_permutations.reserve(maxPermutationsCount);
14258
14259                         permutationsFlavorStart = flavorNames.size();
14260
14261                         do
14262                         {
14263                                 tcu::UVec4      permutation;
14264                                 std::string     name            = "Permutted_";
14265
14266                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14267                                 {
14268                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14269                                         name += de::toString(indices[componentNdx]);
14270                                 }
14271
14272                                 m_permutations.push_back(permutation);
14273                                 flavorNames.push_back(name);
14274
14275                         } while(std::next_permutation(indices.begin(), indices.end()));
14276
14277                         permutationsFlavorEnd = flavorNames.size();
14278                 }
14279
14280                 fp16AllComponents::setArgCompCount(argNo, compCount);
14281         }
14282         virtual double getULPs(vector<const deFloat16*>& in)
14283         {
14284                 DE_UNREF(in);
14285
14286                 return 8.0;
14287         }
14288
14289         template<class fp16type>
14290         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14291         {
14292                 DE_ASSERT(in.size() == 1);
14293                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14294
14295                 if (getFlavor() == 0)
14296                 {
14297                         fp16type        r(0.0);
14298
14299                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14300                         {
14301                                 const fp16type  x       (in[0][componentNdx]);
14302                                 const fp16type  q       (x.asDouble() * x.asDouble());
14303
14304                                 r = fp16type(r.asDouble() + q.asDouble());
14305                         }
14306
14307                         r = fp16type(deSqrt(r.asDouble()));
14308
14309                         if (r.isZero())
14310                                 return false;
14311
14312                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14313                         {
14314                                 const fp16type  x       (in[0][componentNdx]);
14315
14316                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14317                         }
14318                 }
14319                 else if (getFlavor() == 1)
14320                 {
14321                         double  r(0.0);
14322
14323                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14324                         {
14325                                 const fp16type  x       (in[0][componentNdx]);
14326                                 const double    q       (x.asDouble() * x.asDouble());
14327
14328                                 r += q;
14329                         }
14330
14331                         r = deSqrt(r);
14332
14333                         if (r == 0)
14334                                 return false;
14335
14336                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14337                         {
14338                                 const fp16type  x       (in[0][componentNdx]);
14339
14340                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14341                         }
14342                 }
14343                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14344                 {
14345                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14346                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14347                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14348                         fp16type                        r                               (0.0);
14349
14350                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14351                         {
14352                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14353                                 const fp16type  x                               (in[0][componentNdx]);
14354                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14355
14356                                 r = fp16type(r.asDouble() + q.asDouble());
14357                         }
14358
14359                         r = fp16type(deSqrt(r.asDouble()));
14360
14361                         if (r.isZero())
14362                                 return false;
14363
14364                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14365                         {
14366                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14367                                 const fp16type  x                               (in[0][componentNdx]);
14368
14369                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14370                         }
14371                 }
14372                 else
14373                 {
14374                         TCU_THROW(InternalError, "Unknown flavor");
14375                 }
14376
14377                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14378                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14379                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14380                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14381
14382                 return true;
14383         }
14384
14385 private:
14386         std::vector<tcu::UVec4> m_permutations;
14387         size_t                                  permutationsFlavorStart;
14388         size_t                                  permutationsFlavorEnd;
14389 };
14390
14391 struct fp16FaceForward : public fp16AllComponents
14392 {
14393         virtual double getULPs(vector<const deFloat16*>& in)
14394         {
14395                 DE_UNREF(in);
14396
14397                 return 4.0;
14398         }
14399
14400         template<class fp16type>
14401         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14402         {
14403                 DE_ASSERT(in.size() == 3);
14404                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14405                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14406                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14407
14408                 fp16type        dp(0.0);
14409
14410                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14411                 {
14412                         const fp16type  x       (in[1][componentNdx]);
14413                         const fp16type  y       (in[2][componentNdx]);
14414                         const double    xd      (x.asDouble());
14415                         const double    yd      (y.asDouble());
14416                         const fp16type  q       (xd * yd);
14417
14418                         dp = fp16type(dp.asDouble() + q.asDouble());
14419                 }
14420
14421                 if (dp.isNaN() || dp.isZero())
14422                         return false;
14423
14424                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14425                 {
14426                         const fp16type  n       (in[0][componentNdx]);
14427
14428                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14429                 }
14430
14431                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14432                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14433                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14434                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14435
14436                 return true;
14437         }
14438 };
14439
14440 struct fp16Reflect : public fp16AllComponents
14441 {
14442         fp16Reflect() : fp16AllComponents()
14443         {
14444                 flavorNames.push_back("EmulatingFP16");
14445                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14446                 flavorNames.push_back("FloatCalc");
14447                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14448                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14449                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14450         }
14451
14452         virtual double getULPs(vector<const deFloat16*>& in)
14453         {
14454                 DE_UNREF(in);
14455
14456                 return 256.0; // This is not a precision test. Value is not from spec
14457         }
14458
14459         template<class fp16type>
14460         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14461         {
14462                 DE_ASSERT(in.size() == 2);
14463                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14464                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14465
14466                 if (getFlavor() < 4)
14467                 {
14468                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14469                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14470
14471                         if (floatCalc)
14472                         {
14473                                 float   dp(0.0f);
14474
14475                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14476                                 {
14477                                         const fp16type  i       (in[0][componentNdx]);
14478                                         const fp16type  n       (in[1][componentNdx]);
14479                                         const float             id      (i.asFloat());
14480                                         const float             nd      (n.asFloat());
14481                                         const float             qd      (id * nd);
14482
14483                                         if (keepZeroSign)
14484                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14485                                         else
14486                                                 dp = dp + qd;
14487                                 }
14488
14489                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14490                                 {
14491                                         const fp16type  i               (in[0][componentNdx]);
14492                                         const fp16type  n               (in[1][componentNdx]);
14493                                         const float             dpnd    (dp * n.asFloat());
14494                                         const float             dpn2d   (2.0f * dpnd);
14495                                         const float             idpn2d  (i.asFloat() - dpn2d);
14496                                         const fp16type  result  (idpn2d);
14497
14498                                         out[componentNdx] = result.bits();
14499                                 }
14500                         }
14501                         else
14502                         {
14503                                 fp16type        dp(0.0);
14504
14505                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14506                                 {
14507                                         const fp16type  i       (in[0][componentNdx]);
14508                                         const fp16type  n       (in[1][componentNdx]);
14509                                         const double    id      (i.asDouble());
14510                                         const double    nd      (n.asDouble());
14511                                         const fp16type  q       (id * nd);
14512
14513                                         if (keepZeroSign)
14514                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14515                                         else
14516                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14517                                 }
14518
14519                                 if (dp.isNaN())
14520                                         return false;
14521
14522                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14523                                 {
14524                                         const fp16type  i               (in[0][componentNdx]);
14525                                         const fp16type  n               (in[1][componentNdx]);
14526                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14527                                         const fp16type  dpn2    (2 * dpn.asDouble());
14528                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14529
14530                                         out[componentNdx] = idpn2.bits();
14531                                 }
14532                         }
14533                 }
14534                 else if (getFlavor() == 4)
14535                 {
14536                         fp16type        dp(0.0);
14537
14538                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14539                         {
14540                                 const fp16type  i       (in[0][componentNdx]);
14541                                 const fp16type  n       (in[1][componentNdx]);
14542                                 const double    id      (i.asDouble());
14543                                 const double    nd      (n.asDouble());
14544                                 const fp16type  q       (id * nd);
14545
14546                                 dp = fp16type(dp.asDouble() + q.asDouble());
14547                         }
14548
14549                         if (dp.isNaN())
14550                                 return false;
14551
14552                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14553                         {
14554                                 const fp16type  i               (in[0][componentNdx]);
14555                                 const fp16type  n               (in[1][componentNdx]);
14556                                 const fp16type  n2              (2 * n.asDouble());
14557                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14558                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14559
14560                                 out[componentNdx] = idpn2.bits();
14561                         }
14562                 }
14563                 else if (getFlavor() == 5)
14564                 {
14565                         fp16type        dp2(0.0);
14566
14567                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14568                         {
14569                                 const fp16type  i       (in[0][componentNdx]);
14570                                 const fp16type  n       (in[1][componentNdx]);
14571                                 const fp16type  i2      (2.0 * i.asDouble());
14572                                 const double    i2d     (i2.asDouble());
14573                                 const double    nd      (n.asDouble());
14574                                 const fp16type  q       (i2d * nd);
14575
14576                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14577                         }
14578
14579                         if (dp2.isNaN())
14580                                 return false;
14581
14582                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14583                         {
14584                                 const fp16type  i               (in[0][componentNdx]);
14585                                 const fp16type  n               (in[1][componentNdx]);
14586                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14587                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14588
14589                                 out[componentNdx] = idpn2.bits();
14590                         }
14591                 }
14592                 else
14593                 {
14594                         TCU_THROW(InternalError, "Unknown flavor");
14595                 }
14596
14597                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14598                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14599                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14600                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14601
14602                 return true;
14603         }
14604 };
14605
14606 struct fp16Refract : public fp16AllComponents
14607 {
14608         fp16Refract() : fp16AllComponents()
14609         {
14610                 flavorNames.push_back("EmulatingFP16");
14611                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14612                 flavorNames.push_back("FloatCalc");
14613                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14614         }
14615
14616         virtual double getULPs(vector<const deFloat16*>& in)
14617         {
14618                 DE_UNREF(in);
14619
14620                 return 8192.0; // This is not a precision test. Value is not from spec
14621         }
14622
14623         template<class fp16type>
14624         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14625         {
14626                 DE_ASSERT(in.size() == 3);
14627                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14628                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14629                 DE_ASSERT(getArgCompCount(2) == 1);
14630
14631                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14632                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14633                 const fp16type  eta                             (*in[2]);
14634
14635                 if (doubleCalc)
14636                 {
14637                         double  dp      (0.0);
14638
14639                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14640                         {
14641                                 const fp16type  i       (in[0][componentNdx]);
14642                                 const fp16type  n       (in[1][componentNdx]);
14643                                 const double    id      (i.asDouble());
14644                                 const double    nd      (n.asDouble());
14645                                 const double    qd      (id * nd);
14646
14647                                 if (keepZeroSign)
14648                                         dp = (componentNdx == 0) ? qd : dp + qd;
14649                                 else
14650                                         dp = dp + qd;
14651                         }
14652
14653                         const double    eta2    (eta.asDouble() * eta.asDouble());
14654                         const double    dp2             (dp * dp);
14655                         const double    dp1             (1.0 - dp2);
14656                         const double    dpe             (eta2 * dp1);
14657                         const double    k               (1.0 - dpe);
14658
14659                         if (k < 0.0)
14660                         {
14661                                 const fp16type  zero    (0.0);
14662
14663                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14664                                         out[componentNdx] = zero.bits();
14665                         }
14666                         else
14667                         {
14668                                 const double    sk      (deSqrt(k));
14669
14670                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14671                                 {
14672                                         const fp16type  i               (in[0][componentNdx]);
14673                                         const fp16type  n               (in[1][componentNdx]);
14674                                         const double    etai    (i.asDouble() * eta.asDouble());
14675                                         const double    etadp   (eta.asDouble() * dp);
14676                                         const double    etadpk  (etadp + sk);
14677                                         const double    etadpkn (etadpk * n.asDouble());
14678                                         const double    full    (etai - etadpkn);
14679                                         const fp16type  result  (full);
14680
14681                                         if (result.isInf())
14682                                                 return false;
14683
14684                                         out[componentNdx] = result.bits();
14685                                 }
14686                         }
14687                 }
14688                 else
14689                 {
14690                         fp16type        dp      (0.0);
14691
14692                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14693                         {
14694                                 const fp16type  i       (in[0][componentNdx]);
14695                                 const fp16type  n       (in[1][componentNdx]);
14696                                 const double    id      (i.asDouble());
14697                                 const double    nd      (n.asDouble());
14698                                 const fp16type  q       (id * nd);
14699
14700                                 if (keepZeroSign)
14701                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14702                                 else
14703                                         dp = fp16type(dp.asDouble() + q.asDouble());
14704                         }
14705
14706                         if (dp.isNaN())
14707                                 return false;
14708
14709                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14710                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14711                         const fp16type  dp1     (1.0 - dp2.asDouble());
14712                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14713                         const fp16type  k       (1.0 - dpe.asDouble());
14714
14715                         if (k.asDouble() < 0.0)
14716                         {
14717                                 const fp16type  zero    (0.0);
14718
14719                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14720                                         out[componentNdx] = zero.bits();
14721                         }
14722                         else
14723                         {
14724                                 const fp16type  sk      (deSqrt(k.asDouble()));
14725
14726                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14727                                 {
14728                                         const fp16type  i               (in[0][componentNdx]);
14729                                         const fp16type  n               (in[1][componentNdx]);
14730                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14731                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14732                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14733                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14734                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14735
14736                                         if (full.isNaN() || full.isInf())
14737                                                 return false;
14738
14739                                         out[componentNdx] = full.bits();
14740                                 }
14741                         }
14742                 }
14743
14744                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14745                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14746                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14747                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14748
14749                 return true;
14750         }
14751 };
14752
14753 struct fp16Dot : public fp16AllComponents
14754 {
14755         fp16Dot() : fp16AllComponents()
14756         {
14757                 flavorNames.push_back("EmulatingFP16");
14758                 flavorNames.push_back("FloatCalc");
14759                 flavorNames.push_back("DoubleCalc");
14760
14761                 // flavorNames will be extended later
14762         }
14763
14764         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14765         {
14766                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14767
14768                 if (argNo == 0 && argCompCount[argNo] == 0)
14769                 {
14770                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14771                         std::vector<int>        indices;
14772
14773                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14774                                 indices.push_back(static_cast<int>(componentNdx));
14775
14776                         m_permutations.reserve(maxPermutationsCount);
14777
14778                         permutationsFlavorStart = flavorNames.size();
14779
14780                         do
14781                         {
14782                                 tcu::UVec4      permutation;
14783                                 std::string     name            = "Permutted_";
14784
14785                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14786                                 {
14787                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14788                                         name += de::toString(indices[componentNdx]);
14789                                 }
14790
14791                                 m_permutations.push_back(permutation);
14792                                 flavorNames.push_back(name);
14793
14794                         } while(std::next_permutation(indices.begin(), indices.end()));
14795
14796                         permutationsFlavorEnd = flavorNames.size();
14797                 }
14798
14799                 fp16AllComponents::setArgCompCount(argNo, compCount);
14800         }
14801
14802         virtual double  getULPs(vector<const deFloat16*>& in)
14803         {
14804                 DE_UNREF(in);
14805
14806                 return 16.0; // This is not a precision test. Value is not from spec
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                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14814                 DE_ASSERT(getOutCompCount() == 1);
14815
14816                 double  result  (0.0);
14817                 double  eps             (0.0);
14818
14819                 if (getFlavor() == 0)
14820                 {
14821                         fp16type        dp      (0.0);
14822
14823                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14824                         {
14825                                 const fp16type  x       (in[0][componentNdx]);
14826                                 const fp16type  y       (in[1][componentNdx]);
14827                                 const fp16type  q       (x.asDouble() * y.asDouble());
14828
14829                                 dp = fp16type(dp.asDouble() + q.asDouble());
14830                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14831                         }
14832
14833                         result = dp.asDouble();
14834                 }
14835                 else if (getFlavor() == 1)
14836                 {
14837                         float   dp      (0.0);
14838
14839                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14840                         {
14841                                 const fp16type  x       (in[0][componentNdx]);
14842                                 const fp16type  y       (in[1][componentNdx]);
14843                                 const float             q       (x.asFloat() * y.asFloat());
14844
14845                                 dp += q;
14846                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14847                         }
14848
14849                         result = dp;
14850                 }
14851                 else if (getFlavor() == 2)
14852                 {
14853                         double  dp      (0.0);
14854
14855                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14856                         {
14857                                 const fp16type  x       (in[0][componentNdx]);
14858                                 const fp16type  y       (in[1][componentNdx]);
14859                                 const double    q       (x.asDouble() * y.asDouble());
14860
14861                                 dp += q;
14862                                 eps += floatFormat16.ulp(q, 2.0);
14863                         }
14864
14865                         result = dp;
14866                 }
14867                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14868                 {
14869                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14870                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14871                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14872                         fp16type                        dp                              (0.0);
14873
14874                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14875                         {
14876                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14877                                 const fp16type          x                               (in[0][componentNdx]);
14878                                 const fp16type          y                               (in[1][componentNdx]);
14879                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14880
14881                                 dp = fp16type(dp.asDouble() + q.asDouble());
14882                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14883                         }
14884
14885                         result = dp.asDouble();
14886                 }
14887                 else
14888                 {
14889                         TCU_THROW(InternalError, "Unknown flavor");
14890                 }
14891
14892                 out[0] = fp16type(result).bits();
14893                 min[0] = result - eps;
14894                 max[0] = result + eps;
14895
14896                 return true;
14897         }
14898
14899 private:
14900         std::vector<tcu::UVec4> m_permutations;
14901         size_t                                  permutationsFlavorStart;
14902         size_t                                  permutationsFlavorEnd;
14903 };
14904
14905 struct fp16VectorTimesScalar : public fp16AllComponents
14906 {
14907         virtual double getULPs(vector<const deFloat16*>& in)
14908         {
14909                 DE_UNREF(in);
14910
14911                 return 2.0;
14912         }
14913
14914         template<class fp16type>
14915         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14916         {
14917                 DE_ASSERT(in.size() == 2);
14918                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14919                 DE_ASSERT(getArgCompCount(1) == 1);
14920
14921                 fp16type        s       (*in[1]);
14922
14923                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14924                 {
14925                         const fp16type  x          (in[0][componentNdx]);
14926                         const double    result (s.asDouble() * x.asDouble());
14927                         const fp16type  m          (result);
14928
14929                         out[componentNdx] = m.bits();
14930                         min[componentNdx] = getMin(result, getULPs(in));
14931                         max[componentNdx] = getMax(result, getULPs(in));
14932                 }
14933
14934                 return true;
14935         }
14936 };
14937
14938 struct fp16MatrixBase : public fp16AllComponents
14939 {
14940         deUint32                getComponentValidity                    ()
14941         {
14942                 return static_cast<deUint32>(-1);
14943         }
14944
14945         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14946         {
14947                 const size_t minComponentCount  = 0;
14948                 const size_t maxComponentCount  = 3;
14949                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14950
14951                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14952                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14953                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14954                 DE_UNREF(minComponentCount);
14955                 DE_UNREF(maxComponentCount);
14956
14957                 return col * alignedRowsCount + row;
14958         }
14959
14960         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14961         {
14962                 deUint32        result  = 0u;
14963
14964                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14965                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14966                         {
14967                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14968
14969                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14970
14971                                 result |= (1<<bitNdx);
14972                         }
14973
14974                 return result;
14975         }
14976 };
14977
14978 template<size_t cols, size_t rows>
14979 struct fp16Transpose : public fp16MatrixBase
14980 {
14981         virtual double getULPs(vector<const deFloat16*>& in)
14982         {
14983                 DE_UNREF(in);
14984
14985                 return 1.0;
14986         }
14987
14988         deUint32        getComponentValidity    ()
14989         {
14990                 return getComponentMatrixValidityMask(rows, cols);
14991         }
14992
14993         template<class fp16type>
14994         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14995         {
14996                 DE_ASSERT(in.size() == 1);
14997
14998                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14999                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
15000                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
15001
15002                 DE_ASSERT(output.size() == alignedCols * alignedRows);
15003
15004                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15005                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15006                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
15007
15008                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
15009                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
15010                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
15011
15012                 return true;
15013         }
15014 };
15015
15016 template<size_t cols, size_t rows>
15017 struct fp16MatrixTimesScalar : public fp16MatrixBase
15018 {
15019         virtual double getULPs(vector<const deFloat16*>& in)
15020         {
15021                 DE_UNREF(in);
15022
15023                 return 4.0;
15024         }
15025
15026         deUint32        getComponentValidity    ()
15027         {
15028                 return getComponentMatrixValidityMask(cols, rows);
15029         }
15030
15031         template<class fp16type>
15032         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15033         {
15034                 DE_ASSERT(in.size() == 2);
15035                 DE_ASSERT(getArgCompCount(1) == 1);
15036
15037                 const fp16type  y                       (in[1][0]);
15038                 const float             scalar          (y.asFloat());
15039                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15040                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15041
15042                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
15043                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15044                 DE_UNREF(alignedCols);
15045
15046                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15047                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15048                         {
15049                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15050                                 const fp16type  x       (in[0][ndx]);
15051                                 const double    result  (scalar * x.asFloat());
15052
15053                                 out[ndx] = fp16type(result).bits();
15054                                 min[ndx] = getMin(result, getULPs(in));
15055                                 max[ndx] = getMax(result, getULPs(in));
15056                         }
15057
15058                 return true;
15059         }
15060 };
15061
15062 template<size_t cols, size_t rows>
15063 struct fp16VectorTimesMatrix : public fp16MatrixBase
15064 {
15065         fp16VectorTimesMatrix() : fp16MatrixBase()
15066         {
15067                 flavorNames.push_back("EmulatingFP16");
15068                 flavorNames.push_back("FloatCalc");
15069         }
15070
15071         virtual double getULPs (vector<const deFloat16*>& in)
15072         {
15073                 DE_UNREF(in);
15074
15075                 return (8.0 * cols);
15076         }
15077
15078         deUint32 getComponentValidity ()
15079         {
15080                 return getComponentMatrixValidityMask(cols, 1);
15081         }
15082
15083         template<class fp16type>
15084         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15085         {
15086                 DE_ASSERT(in.size() == 2);
15087
15088                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15089                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15090
15091                 DE_ASSERT(getOutCompCount() == cols);
15092                 DE_ASSERT(getArgCompCount(0) == rows);
15093                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
15094                 DE_UNREF(alignedCols);
15095
15096                 if (getFlavor() == 0)
15097                 {
15098                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15099                         {
15100                                 fp16type        s       (fp16type::zero(1));
15101
15102                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15103                                 {
15104                                         const fp16type  v       (in[0][rowNdx]);
15105                                         const float             vf      (v.asFloat());
15106                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15107                                         const fp16type  x       (in[1][ndx]);
15108                                         const float             xf      (x.asFloat());
15109                                         const fp16type  m       (vf * xf);
15110
15111                                         s = fp16type(s.asFloat() + m.asFloat());
15112                                 }
15113
15114                                 out[colNdx] = s.bits();
15115                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
15116                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
15117                         }
15118                 }
15119                 else if (getFlavor() == 1)
15120                 {
15121                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15122                         {
15123                                 float   s       (0.0f);
15124
15125                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15126                                 {
15127                                         const fp16type  v       (in[0][rowNdx]);
15128                                         const float             vf      (v.asFloat());
15129                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15130                                         const fp16type  x       (in[1][ndx]);
15131                                         const float             xf      (x.asFloat());
15132                                         const float             m       (vf * xf);
15133
15134                                         s += m;
15135                                 }
15136
15137                                 out[colNdx] = fp16type(s).bits();
15138                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
15139                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
15140                         }
15141                 }
15142                 else
15143                 {
15144                         TCU_THROW(InternalError, "Unknown flavor");
15145                 }
15146
15147                 return true;
15148         }
15149 };
15150
15151 template<size_t cols, size_t rows>
15152 struct fp16MatrixTimesVector : public fp16MatrixBase
15153 {
15154         fp16MatrixTimesVector() : fp16MatrixBase()
15155         {
15156                 flavorNames.push_back("EmulatingFP16");
15157                 flavorNames.push_back("FloatCalc");
15158         }
15159
15160         virtual double getULPs (vector<const deFloat16*>& in)
15161         {
15162                 DE_UNREF(in);
15163
15164                 return (8.0 * rows);
15165         }
15166
15167         deUint32 getComponentValidity ()
15168         {
15169                 return getComponentMatrixValidityMask(rows, 1);
15170         }
15171
15172         template<class fp16type>
15173         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15174         {
15175                 DE_ASSERT(in.size() == 2);
15176
15177                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15178                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15179
15180                 DE_ASSERT(getOutCompCount() == rows);
15181                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
15182                 DE_ASSERT(getArgCompCount(1) == cols);
15183                 DE_UNREF(alignedCols);
15184
15185                 if (getFlavor() == 0)
15186                 {
15187                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15188                         {
15189                                 fp16type        s       (fp16type::zero(1));
15190
15191                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15192                                 {
15193                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15194                                         const fp16type  x       (in[0][ndx]);
15195                                         const float             xf      (x.asFloat());
15196                                         const fp16type  v       (in[1][colNdx]);
15197                                         const float             vf      (v.asFloat());
15198                                         const fp16type  m       (vf * xf);
15199
15200                                         s = fp16type(s.asFloat() + m.asFloat());
15201                                 }
15202
15203                                 out[rowNdx] = s.bits();
15204                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
15205                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
15206                         }
15207                 }
15208                 else if (getFlavor() == 1)
15209                 {
15210                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15211                         {
15212                                 float   s       (0.0f);
15213
15214                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15215                                 {
15216                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15217                                         const fp16type  x       (in[0][ndx]);
15218                                         const float             xf      (x.asFloat());
15219                                         const fp16type  v       (in[1][colNdx]);
15220                                         const float             vf      (v.asFloat());
15221                                         const float             m       (vf * xf);
15222
15223                                         s += m;
15224                                 }
15225
15226                                 out[rowNdx] = fp16type(s).bits();
15227                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
15228                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
15229                         }
15230                 }
15231                 else
15232                 {
15233                         TCU_THROW(InternalError, "Unknown flavor");
15234                 }
15235
15236                 return true;
15237         }
15238 };
15239
15240 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15241 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15242 {
15243         fp16MatrixTimesMatrix() : fp16MatrixBase()
15244         {
15245                 flavorNames.push_back("EmulatingFP16");
15246                 flavorNames.push_back("FloatCalc");
15247         }
15248
15249         virtual double getULPs (vector<const deFloat16*>& in)
15250         {
15251                 DE_UNREF(in);
15252
15253                 return 32.0;
15254         }
15255
15256         deUint32 getComponentValidity ()
15257         {
15258                 return getComponentMatrixValidityMask(colsR, rowsL);
15259         }
15260
15261         template<class fp16type>
15262         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15263         {
15264                 DE_STATIC_ASSERT(colsL == rowsR);
15265
15266                 DE_ASSERT(in.size() == 2);
15267
15268                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15269                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15270                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15271                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15272
15273                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15274                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15275                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15276                 DE_UNREF(alignedColsL);
15277                 DE_UNREF(alignedColsR);
15278
15279                 if (getFlavor() == 0)
15280                 {
15281                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15282                         {
15283                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15284                                 {
15285                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15286                                         fp16type                s       (fp16type::zero(1));
15287
15288                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15289                                         {
15290                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15291                                                 const fp16type  l               (in[0][ndxl]);
15292                                                 const float             lf              (l.asFloat());
15293                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15294                                                 const fp16type  r               (in[1][ndxr]);
15295                                                 const float             rf              (r.asFloat());
15296                                                 const fp16type  m               (lf * rf);
15297
15298                                                 s = fp16type(s.asFloat() + m.asFloat());
15299                                         }
15300
15301                                         out[ndx] = s.bits();
15302                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15303                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15304                                 }
15305                         }
15306                 }
15307                 else if (getFlavor() == 1)
15308                 {
15309                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15310                         {
15311                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15312                                 {
15313                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15314                                         float                   s       (0.0f);
15315
15316                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15317                                         {
15318                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15319                                                 const fp16type  l               (in[0][ndxl]);
15320                                                 const float             lf              (l.asFloat());
15321                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15322                                                 const fp16type  r               (in[1][ndxr]);
15323                                                 const float             rf              (r.asFloat());
15324                                                 const float             m               (lf * rf);
15325
15326                                                 s += m;
15327                                         }
15328
15329                                         out[ndx] = fp16type(s).bits();
15330                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15331                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15332                                 }
15333                         }
15334                 }
15335                 else
15336                 {
15337                         TCU_THROW(InternalError, "Unknown flavor");
15338                 }
15339
15340                 return true;
15341         }
15342 };
15343
15344 template<size_t cols, size_t rows>
15345 struct fp16OuterProduct : public fp16MatrixBase
15346 {
15347         virtual double getULPs (vector<const deFloat16*>& in)
15348         {
15349                 DE_UNREF(in);
15350
15351                 return 2.0;
15352         }
15353
15354         deUint32 getComponentValidity ()
15355         {
15356                 return getComponentMatrixValidityMask(cols, rows);
15357         }
15358
15359         template<class fp16type>
15360         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15361         {
15362                 DE_ASSERT(in.size() == 2);
15363
15364                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15365                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15366
15367                 DE_ASSERT(getArgCompCount(0) == rows);
15368                 DE_ASSERT(getArgCompCount(1) == cols);
15369                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15370                 DE_UNREF(alignedCols);
15371
15372                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15373                 {
15374                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15375                         {
15376                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15377                                 const fp16type  x       (in[0][rowNdx]);
15378                                 const float             xf      (x.asFloat());
15379                                 const fp16type  y       (in[1][colNdx]);
15380                                 const float             yf      (y.asFloat());
15381                                 const fp16type  m       (xf * yf);
15382
15383                                 out[ndx] = m.bits();
15384                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15385                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15386                         }
15387                 }
15388
15389                 return true;
15390         }
15391 };
15392
15393 template<size_t size>
15394 struct fp16Determinant;
15395
15396 template<>
15397 struct fp16Determinant<2> : public fp16MatrixBase
15398 {
15399         virtual double getULPs (vector<const deFloat16*>& in)
15400         {
15401                 DE_UNREF(in);
15402
15403                 return 128.0; // This is not a precision test. Value is not from spec
15404         }
15405
15406         deUint32 getComponentValidity ()
15407         {
15408                 return 1;
15409         }
15410
15411         template<class fp16type>
15412         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15413         {
15414                 const size_t    cols            = 2;
15415                 const size_t    rows            = 2;
15416                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15417                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15418
15419                 DE_ASSERT(in.size() == 1);
15420                 DE_ASSERT(getOutCompCount() == 1);
15421                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15422                 DE_UNREF(alignedCols);
15423                 DE_UNREF(alignedRows);
15424
15425                 // [ a b ]
15426                 // [ c d ]
15427                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15428                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15429                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15430                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15431                 const float             ad              (a * d);
15432                 const fp16type  adf16   (ad);
15433                 const float             bc              (b * c);
15434                 const fp16type  bcf16   (bc);
15435                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15436                 const fp16type  rf16    (r);
15437
15438                 out[0] = rf16.bits();
15439                 min[0] = getMin(r, getULPs(in));
15440                 max[0] = getMax(r, getULPs(in));
15441
15442                 return true;
15443         }
15444 };
15445
15446 template<>
15447 struct fp16Determinant<3> : public fp16MatrixBase
15448 {
15449         virtual double getULPs (vector<const deFloat16*>& in)
15450         {
15451                 DE_UNREF(in);
15452
15453                 return 128.0; // This is not a precision test. Value is not from spec
15454         }
15455
15456         deUint32 getComponentValidity ()
15457         {
15458                 return 1;
15459         }
15460
15461         template<class fp16type>
15462         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15463         {
15464                 const size_t    cols            = 3;
15465                 const size_t    rows            = 3;
15466                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15467                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15468
15469                 DE_ASSERT(in.size() == 1);
15470                 DE_ASSERT(getOutCompCount() == 1);
15471                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15472                 DE_UNREF(alignedCols);
15473                 DE_UNREF(alignedRows);
15474
15475                 // [ a b c ]
15476                 // [ d e f ]
15477                 // [ g h i ]
15478                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15479                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15480                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15481                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15482                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15483                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15484                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15485                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15486                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15487                 const fp16type  aei             (a * e * i);
15488                 const fp16type  bfg             (b * f * g);
15489                 const fp16type  cdh             (c * d * h);
15490                 const fp16type  ceg             (c * e * g);
15491                 const fp16type  bdi             (b * d * i);
15492                 const fp16type  afh             (a * f * h);
15493                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15494                 const fp16type  rf16    (r);
15495
15496                 out[0] = rf16.bits();
15497                 min[0] = getMin(r, getULPs(in));
15498                 max[0] = getMax(r, getULPs(in));
15499
15500                 return true;
15501         }
15502 };
15503
15504 template<>
15505 struct fp16Determinant<4> : public fp16MatrixBase
15506 {
15507         virtual double getULPs (vector<const deFloat16*>& in)
15508         {
15509                 DE_UNREF(in);
15510
15511                 return 128.0; // This is not a precision test. Value is not from spec
15512         }
15513
15514         deUint32 getComponentValidity ()
15515         {
15516                 return 1;
15517         }
15518
15519         template<class fp16type>
15520         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15521         {
15522                 const size_t    rows            = 4;
15523                 const size_t    cols            = 4;
15524                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15525                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15526
15527                 DE_ASSERT(in.size() == 1);
15528                 DE_ASSERT(getOutCompCount() == 1);
15529                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15530                 DE_UNREF(alignedCols);
15531                 DE_UNREF(alignedRows);
15532
15533                 // [ a b c d ]
15534                 // [ e f g h ]
15535                 // [ i j k l ]
15536                 // [ m n o p ]
15537                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15538                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15539                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15540                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15541                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15542                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15543                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15544                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15545                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15546                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15547                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15548                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15549                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15550                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15551                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15552                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15553
15554                 // [ f g h ]
15555                 // [ j k l ]
15556                 // [ n o p ]
15557                 const fp16type  fkp             (f * k * p);
15558                 const fp16type  gln             (g * l * n);
15559                 const fp16type  hjo             (h * j * o);
15560                 const fp16type  hkn             (h * k * n);
15561                 const fp16type  gjp             (g * j * p);
15562                 const fp16type  flo             (f * l * o);
15563                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15564
15565                 // [ e g h ]
15566                 // [ i k l ]
15567                 // [ m o p ]
15568                 const fp16type  ekp             (e * k * p);
15569                 const fp16type  glm             (g * l * m);
15570                 const fp16type  hio             (h * i * o);
15571                 const fp16type  hkm             (h * k * m);
15572                 const fp16type  gip             (g * i * p);
15573                 const fp16type  elo             (e * l * o);
15574                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15575
15576                 // [ e f h ]
15577                 // [ i j l ]
15578                 // [ m n p ]
15579                 const fp16type  ejp             (e * j * p);
15580                 const fp16type  flm             (f * l * m);
15581                 const fp16type  hin             (h * i * n);
15582                 const fp16type  hjm             (h * j * m);
15583                 const fp16type  fip             (f * i * p);
15584                 const fp16type  eln             (e * l * n);
15585                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15586
15587                 // [ e f g ]
15588                 // [ i j k ]
15589                 // [ m n o ]
15590                 const fp16type  ejo             (e * j * o);
15591                 const fp16type  fkm             (f * k * m);
15592                 const fp16type  gin             (g * i * n);
15593                 const fp16type  gjm             (g * j * m);
15594                 const fp16type  fio             (f * i * o);
15595                 const fp16type  ekn             (e * k * n);
15596                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15597
15598                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15599                 const fp16type  rf16    (r);
15600
15601                 out[0] = rf16.bits();
15602                 min[0] = getMin(r, getULPs(in));
15603                 max[0] = getMax(r, getULPs(in));
15604
15605                 return true;
15606         }
15607 };
15608
15609 template<size_t size>
15610 struct fp16Inverse;
15611
15612 template<>
15613 struct fp16Inverse<2> : public fp16MatrixBase
15614 {
15615         virtual double getULPs (vector<const deFloat16*>& in)
15616         {
15617                 DE_UNREF(in);
15618
15619                 return 128.0; // This is not a precision test. Value is not from spec
15620         }
15621
15622         deUint32 getComponentValidity ()
15623         {
15624                 return getComponentMatrixValidityMask(2, 2);
15625         }
15626
15627         template<class fp16type>
15628         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15629         {
15630                 const size_t    cols            = 2;
15631                 const size_t    rows            = 2;
15632                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15633                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15634
15635                 DE_ASSERT(in.size() == 1);
15636                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15637                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15638                 DE_UNREF(alignedCols);
15639
15640                 // [ a b ]
15641                 // [ c d ]
15642                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15643                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15644                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15645                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15646                 const float             ad              (a * d);
15647                 const fp16type  adf16   (ad);
15648                 const float             bc              (b * c);
15649                 const fp16type  bcf16   (bc);
15650                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15651                 const fp16type  det16   (det);
15652
15653                 out[0] = fp16type( d / det16.asFloat()).bits();
15654                 out[1] = fp16type(-c / det16.asFloat()).bits();
15655                 out[2] = fp16type(-b / det16.asFloat()).bits();
15656                 out[3] = fp16type( a / det16.asFloat()).bits();
15657
15658                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15659                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15660                         {
15661                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15662                                 const fp16type  s       (out[ndx]);
15663
15664                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15665                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15666                         }
15667
15668                 return true;
15669         }
15670 };
15671
15672 inline std::string fp16ToString(deFloat16 val)
15673 {
15674         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15675 }
15676
15677 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15678 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15679 {
15680         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15681                 return false;
15682
15683         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15684         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15685         const size_t    inputsSteps[3]          =
15686         {
15687                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15688                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15689                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15690         };
15691
15692         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15693         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15694
15695         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15696         {
15697                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15698                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15699         }
15700
15701         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15702         TestedArithmeticFunction        func;
15703
15704         func.setOutCompCount(RES_COMPONENTS);
15705         func.setArgCompCount(0, ARG0_COMPONENTS);
15706         func.setArgCompCount(1, ARG1_COMPONENTS);
15707         func.setArgCompCount(2, ARG2_COMPONENTS);
15708
15709         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15710         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15711         const size_t                            denormModesCount                                = 2;
15712         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15713         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15714         bool                                            success                                                 = true;
15715         size_t                                          validatedCount                                  = 0;
15716
15717         vector<deUint8> inputBytes[3];
15718
15719         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15720                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15721
15722         const deFloat16* const                  inputsAsFP16[3]                 =
15723         {
15724                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15725                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15726                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15727         };
15728
15729         for (size_t idx = 0; idx < iterationsCount; ++idx)
15730         {
15731                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15732                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15733                 bool                                            iterationValidated      (true);
15734
15735                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15736                 {
15737                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15738                         {
15739                                 func.setFlavor(flavorNdx);
15740
15741                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15742                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15743                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15744                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15745                                 vector<const deFloat16*>        arguments;
15746
15747                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15748                                 {
15749                                         std::string     error;
15750                                         bool            reportError = false;
15751
15752                                         if (callOncePerComponent || componentNdx == 0)
15753                                         {
15754                                                 bool funcCallResult;
15755
15756                                                 arguments.clear();
15757
15758                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15759                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15760
15761                                                 if (denormNdx == 0)
15762                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15763                                                 else
15764                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15765
15766                                                 if (!funcCallResult)
15767                                                 {
15768                                                         iterationValidated = false;
15769
15770                                                         if (callOncePerComponent)
15771                                                                 continue;
15772                                                         else
15773                                                                 break;
15774                                                 }
15775                                         }
15776
15777                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15778                                                 continue;
15779
15780                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15781
15782                                         if (reportError)
15783                                         {
15784                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15785                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15786
15787                                                 if (reportError && expected.isNaN())
15788                                                         reportError = false;
15789
15790                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15791                                                 {
15792                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15793                                                         {
15794                                                                 // Ignore rounding
15795                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15796                                                                         reportError = false;
15797                                                         }
15798
15799                                                         if (reportError && expected.isInf())
15800                                                         {
15801                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15802                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15803                                                                         reportError = false;
15804                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15805                                                                         reportError = false;
15806                                                         }
15807
15808                                                         if (reportError)
15809                                                         {
15810                                                                 const double    outputtedDouble = outputted.asDouble();
15811
15812                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15813
15814                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15815                                                                         reportError = false;
15816                                                         }
15817                                                 }
15818
15819                                                 if (reportError)
15820                                                 {
15821                                                         const size_t            inputsComps[3]  =
15822                                                         {
15823                                                                 ARG0_COMPONENTS,
15824                                                                 ARG1_COMPONENTS,
15825                                                                 ARG2_COMPONENTS,
15826                                                         };
15827                                                         string                          inputsValues    ("Inputs:");
15828                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15829                                                         std::stringstream       errStream;
15830
15831                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15832                                                         {
15833                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15834
15835                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15836
15837                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15838                                                                 {
15839                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15840
15841                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15842                                                                 }
15843                                                         }
15844
15845                                                         errStream       << "At"
15846                                                                                 << " iteration " << de::toString(idx)
15847                                                                                 << " component " << de::toString(componentNdx)
15848                                                                                 << " denormMode " << de::toString(denormNdx)
15849                                                                                 << " (" << denormModes[denormNdx] << ")"
15850                                                                                 << " " << flavorName
15851                                                                                 << " " << inputsValues
15852                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15853                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15854                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15855                                                                                 << " " << error << "."
15856                                                                                 << std::endl;
15857
15858                                                         errors[componentNdx] += errStream.str();
15859
15860                                                         successfulRuns[componentNdx]--;
15861                                                 }
15862                                         }
15863                                 }
15864                         }
15865                 }
15866
15867                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15868                 {
15869                         // Check if any component has total failure
15870                         if (successfulRuns[componentNdx] == 0)
15871                         {
15872                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15873                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15874
15875                                 success = false;
15876                         }
15877                 }
15878
15879                 if (iterationValidated)
15880                         validatedCount++;
15881         }
15882
15883         if (validatedCount < 16)
15884                 TCU_THROW(InternalError, "Too few samples has been validated.");
15885
15886         return success;
15887 }
15888
15889 // IEEE-754 floating point numbers:
15890 // +--------+------+----------+-------------+
15891 // | binary | sign | exponent | significand |
15892 // +--------+------+----------+-------------+
15893 // | 16-bit |  1   |    5     |     10      |
15894 // +--------+------+----------+-------------+
15895 // | 32-bit |  1   |    8     |     23      |
15896 // +--------+------+----------+-------------+
15897 //
15898 // 16-bit floats:
15899 //
15900 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15901 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15902 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15903 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15904 //
15905 // 0   000 00   00 0000 0000 (0x0000: +0)
15906 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15907 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15908 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15909 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15910 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15911 // Generate and return 16-bit floats and their corresponding 32-bit values.
15912 //
15913 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15914 // Expected count to be at least 14 (numPicks).
15915 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15916 {
15917         vector<deFloat16>       float16;
15918
15919         float16.reserve(count);
15920
15921         // Zero
15922         float16.push_back(deUint16(0x0000));
15923         float16.push_back(deUint16(0x8000));
15924         // Infinity
15925         float16.push_back(deUint16(0x7c00));
15926         float16.push_back(deUint16(0xfc00));
15927         // Normalized
15928         float16.push_back(deUint16(0x0401));
15929         float16.push_back(deUint16(0x8401));
15930         // Some normal number
15931         float16.push_back(deUint16(0x14cb));
15932         float16.push_back(deUint16(0x94cb));
15933         // Min/max positive normal
15934         float16.push_back(deUint16(0x0400));
15935         float16.push_back(deUint16(0x7bff));
15936         // Min/max negative normal
15937         float16.push_back(deUint16(0x8400));
15938         float16.push_back(deUint16(0xfbff));
15939         // PI
15940         float16.push_back(deUint16(0x4248)); // 3.140625
15941         float16.push_back(deUint16(0xb248)); // -3.140625
15942         // PI/2
15943         float16.push_back(deUint16(0x3e48)); // 1.5703125
15944         float16.push_back(deUint16(0xbe48)); // -1.5703125
15945         float16.push_back(deUint16(0x3c00)); // 1.0
15946         float16.push_back(deUint16(0x3800)); // 0.5
15947         // Some useful constants
15948         float16.push_back(tcu::Float16(-2.5f).bits());
15949         float16.push_back(tcu::Float16(-1.0f).bits());
15950         float16.push_back(tcu::Float16( 0.4f).bits());
15951         float16.push_back(tcu::Float16( 2.5f).bits());
15952
15953         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15954
15955         DE_ASSERT(count >= numPicks);
15956         count -= numPicks;
15957
15958         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15959         {
15960                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15961                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15962                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15963
15964                 // Exclude power of -14 to avoid denorms
15965                 DE_ASSERT(de::inRange(exponent, -13, 15));
15966
15967                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15968         }
15969
15970         return float16;
15971 }
15972
15973 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15974 {
15975         DE_UNREF(argNo);
15976
15977         de::Random      rnd(seed);
15978
15979         return getFloat16a(rnd, static_cast<deUint32>(count));
15980 }
15981
15982 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15983 {
15984         de::Random      rnd             (seed);
15985         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15986
15987         DE_ASSERT(newCount * newCount == count);
15988
15989         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15990
15991         return squarize(float16, static_cast<deUint32>(argNo));
15992 }
15993
15994 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15995 {
15996         if (argNo == 0 || argNo == 1)
15997                 return getInputData2(seed, count, argNo);
15998         else
15999                 return getInputData1(seed<<argNo, count, argNo);
16000 }
16001
16002 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16003 {
16004         DE_UNREF(stride);
16005
16006         vector<deFloat16>       result;
16007
16008         switch (argCount)
16009         {
16010                 case 1:result = getInputData1(seed, count, argNo); break;
16011                 case 2:result = getInputData2(seed, count, argNo); break;
16012                 case 3:result = getInputData3(seed, count, argNo); break;
16013                 default: TCU_THROW(InternalError, "Invalid argument count specified");
16014         }
16015
16016         if (compCount == 3)
16017         {
16018                 const size_t            newCount = (3 * count) / 4;
16019                 vector<deFloat16>       newResult;
16020
16021                 newResult.reserve(result.size());
16022
16023                 for (size_t ndx = 0; ndx < newCount; ++ndx)
16024                 {
16025                         newResult.push_back(result[ndx]);
16026
16027                         if (ndx % 3 == 2)
16028                                 newResult.push_back(0);
16029                 }
16030
16031                 result = newResult;
16032         }
16033
16034         DE_ASSERT(result.size() == count);
16035
16036         return result;
16037 }
16038
16039 // Generator for functions requiring data in range [1, inf]
16040 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16041 {
16042         vector<deFloat16>       result;
16043
16044         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16045
16046         // Filter out values below 1.0 from upper half of numbers
16047         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16048         {
16049                 const float f = tcu::Float16(result[idx]).asFloat();
16050
16051                 if (f < 1.0f)
16052                         result[idx] = tcu::Float16(1.0f - f).bits();
16053         }
16054
16055         return result;
16056 }
16057
16058 // Generator for functions requiring data in range [-1, 1]
16059 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16060 {
16061         vector<deFloat16>       result;
16062
16063         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16064
16065         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16066         {
16067                 const float f = tcu::Float16(result[idx]).asFloat();
16068
16069                 if (!de::inRange(f, -1.0f, 1.0f))
16070                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
16071         }
16072
16073         return result;
16074 }
16075
16076 // Generator for functions requiring data in range [-pi, pi]
16077 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16078 {
16079         vector<deFloat16>       result;
16080
16081         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16082
16083         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16084         {
16085                 const float f = tcu::Float16(result[idx]).asFloat();
16086
16087                 if (!de::inRange(f, -DE_PI, DE_PI))
16088                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
16089         }
16090
16091         return result;
16092 }
16093
16094 // Generator for functions requiring data in range [0, inf]
16095 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16096 {
16097         vector<deFloat16>       result;
16098
16099         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16100
16101         if (argNo == 0)
16102         {
16103                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16104                         result[idx] &= static_cast<deFloat16>(~0x8000);
16105         }
16106
16107         return result;
16108 }
16109
16110 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16111 {
16112         DE_UNREF(stride);
16113         DE_UNREF(argCount);
16114
16115         vector<deFloat16>       result;
16116
16117         if (argNo == 0)
16118                 result = getInputData2(seed, count, argNo);
16119         else
16120         {
16121                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
16122                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
16123                 const size_t            newCountY               = count / newCountX;
16124                 de::Random                      rnd                             (seed);
16125                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
16126
16127                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
16128
16129                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
16130                 {
16131                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
16132
16133                         result.insert(result.end(), tmp.begin(), tmp.end());
16134                 }
16135         }
16136
16137         DE_ASSERT(result.size() == count);
16138
16139         return result;
16140 }
16141
16142 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16143 {
16144         DE_UNREF(compCount);
16145         DE_UNREF(stride);
16146         DE_UNREF(argCount);
16147
16148         de::Random                      rnd             (seed << argNo);
16149         vector<deFloat16>       result;
16150
16151         result = getFloat16a(rnd, static_cast<deUint32>(count));
16152
16153         DE_ASSERT(result.size() == count);
16154
16155         return result;
16156 }
16157
16158 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16159 {
16160         DE_UNREF(compCount);
16161         DE_UNREF(argCount);
16162
16163         de::Random                      rnd             (seed << argNo);
16164         vector<deFloat16>       result;
16165
16166         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16167         {
16168                 int num = (rnd.getUint16() % 16) - 8;
16169
16170                 result.push_back(tcu::Float16(float(num)).bits());
16171         }
16172
16173         result[0 * stride] = deUint16(0x7c00); // +Inf
16174         result[1 * stride] = deUint16(0xfc00); // -Inf
16175
16176         DE_ASSERT(result.size() == count);
16177
16178         return result;
16179 }
16180
16181 // Generator for smoothstep function
16182 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16183 {
16184         vector<deFloat16>       result;
16185
16186         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
16187
16188         if (argNo == 0)
16189         {
16190                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16191                 {
16192                         const float f = tcu::Float16(result[idx]).asFloat();
16193
16194                         if (f > 4.0f)
16195                                 result[idx] = tcu::Float16(-f).bits();
16196                 }
16197         }
16198
16199         if (argNo == 1)
16200         {
16201                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16202                 {
16203                         const float f = tcu::Float16(result[idx]).asFloat();
16204
16205                         if (f < 4.0f)
16206                                 result[idx] = tcu::Float16(-f).bits();
16207                 }
16208         }
16209
16210         return result;
16211 }
16212
16213 // Generates normalized vectors for arguments 0 and 1
16214 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16215 {
16216         DE_UNREF(compCount);
16217         DE_UNREF(argCount);
16218
16219         de::Random                      rnd             (seed << argNo);
16220         vector<deFloat16>       result;
16221
16222         if (argNo == 0 || argNo == 1)
16223         {
16224                 // The input parameters for the incident vector I and the surface normal N must already be normalized
16225                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
16226                 {
16227                         vector <float>  unnormolized;
16228                         float                   sum                             = 0;
16229
16230                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16231                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
16232
16233                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16234                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
16235
16236                         sum = deFloatSqrt(sum);
16237                         if (sum == 0.0f)
16238                                 unnormolized[0] = sum = 1.0f;
16239
16240                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16241                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16242
16243                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16244                                 result.push_back(0);
16245                 }
16246         }
16247         else
16248         {
16249                 // Input parameter eta
16250                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16251                 {
16252                         int num = (rnd.getUint16() % 16) - 8;
16253
16254                         result.push_back(tcu::Float16(float(num)).bits());
16255                 }
16256         }
16257
16258         DE_ASSERT(result.size() == count);
16259
16260         return result;
16261 }
16262
16263 // Data generator for complex matrix functions like determinant and inverse
16264 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16265 {
16266         DE_UNREF(compCount);
16267         DE_UNREF(stride);
16268         DE_UNREF(argCount);
16269
16270         de::Random                      rnd             (seed << argNo);
16271         vector<deFloat16>       result;
16272
16273         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16274         {
16275                 int num = (rnd.getUint16() % 16) - 8;
16276
16277                 result.push_back(tcu::Float16(float(num)).bits());
16278         }
16279
16280         DE_ASSERT(result.size() == count);
16281
16282         return result;
16283 }
16284
16285 struct Math16TestType
16286 {
16287         const char*             typePrefix;
16288         const size_t    typeComponents;
16289         const size_t    typeArrayStride;
16290         const size_t    typeStructStride;
16291 };
16292
16293 enum Math16DataTypes
16294 {
16295         NONE    = 0,
16296         SCALAR  = 1,
16297         VEC2    = 2,
16298         VEC3    = 3,
16299         VEC4    = 4,
16300         MAT2X2,
16301         MAT2X3,
16302         MAT2X4,
16303         MAT3X2,
16304         MAT3X3,
16305         MAT3X4,
16306         MAT4X2,
16307         MAT4X3,
16308         MAT4X4,
16309         MATH16_TYPE_LAST
16310 };
16311
16312 struct Math16ArgFragments
16313 {
16314         const char*     bodies;
16315         const char*     variables;
16316         const char*     decorations;
16317         const char*     funcVariables;
16318 };
16319
16320 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16321
16322 struct Math16TestFunc
16323 {
16324         const char*                                     funcName;
16325         const char*                                     funcSuffix;
16326         size_t                                          funcArgsCount;
16327         size_t                                          typeResult;
16328         size_t                                          typeArg0;
16329         size_t                                          typeArg1;
16330         size_t                                          typeArg2;
16331         Math16GetInputData*                     getInputDataFunc;
16332         VerifyIOFunc                            verifyFunc;
16333 };
16334
16335 template<class SpecResource>
16336 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16337 {
16338         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16339         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16340         const size_t                            numDataPointsByAxis                     = 32;
16341         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16342         const char*                                     componentType                           = "f16";
16343         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16344         {
16345                 { "",           0,       0,                                              0,                                             },
16346                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16347                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16348                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16349                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16350                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16351                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16352                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16353                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16354                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16355                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16356                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16357                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16358                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16359         };
16360
16361         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16362
16363
16364         const StringTemplate preMain
16365         (
16366                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16367
16368                 "        %f16     = OpTypeFloat 16\n"
16369                 "        %v2f16   = OpTypeVector %f16 2\n"
16370                 "        %v3f16   = OpTypeVector %f16 3\n"
16371                 "        %v4f16   = OpTypeVector %f16 4\n"
16372                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16373                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16374                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16375                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16376                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16377                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16378                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16379                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16380                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16381
16382                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16383                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16384                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16385                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16386                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16387                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16388                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16389                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16390                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16391                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16392                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16393                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16394                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16395
16396                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16397                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16398                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16399                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16400                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16401                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16402                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16403                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16404                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16405                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16406                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16407                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16408                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16409
16410                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16411                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16412                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16413                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16414                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16415                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16416                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16417                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16418                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16419                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16420                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16421                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16422                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16423
16424                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16425                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16426                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16427                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16428                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16429                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16430                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16431                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16432                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16433                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16434                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16435                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16436                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16437
16438                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16439                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16440                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16441                 "${arg_vars}"
16442         );
16443
16444         const StringTemplate decoration
16445         (
16446                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16447                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16448                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16449                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16450                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16451                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16452                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16453                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16454                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16455                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16456                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16457                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16458                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16459
16460                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16461                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16462                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16463                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16464                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16465                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16466                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16467                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16468                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16469                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16470                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16471                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16472                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16473
16474                 "OpDecorate %SSBO_f16     BufferBlock\n"
16475                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16476                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16477                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16478                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16479                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16480                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16481                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16482                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16483                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16484                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16485                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16486                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16487
16488                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16489                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16490                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16491                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16492                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16493                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16494                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16495                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16496                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16497
16498                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16499                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16500                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16501                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16502                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16503                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16504                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16505                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16506                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16507
16508                 "${arg_decorations}"
16509         );
16510
16511         const StringTemplate testFun
16512         (
16513                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16514                 "    %param = OpFunctionParameter %v4f32\n"
16515                 "    %entry = OpLabel\n"
16516
16517                 "        %i = OpVariable %fp_i32 Function\n"
16518                 "${arg_infunc_vars}"
16519                 "             OpStore %i %c_i32_0\n"
16520                 "             OpBranch %loop\n"
16521
16522                 "     %loop = OpLabel\n"
16523                 "    %i_cmp = OpLoad %i32 %i\n"
16524                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16525                 "             OpLoopMerge %merge %next None\n"
16526                 "             OpBranchConditional %lt %write %merge\n"
16527
16528                 "    %write = OpLabel\n"
16529                 "      %ndx = OpLoad %i32 %i\n"
16530
16531                 "${arg_func_call}"
16532
16533                 "             OpBranch %next\n"
16534
16535                 "     %next = OpLabel\n"
16536                 "    %i_cur = OpLoad %i32 %i\n"
16537                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16538                 "             OpStore %i %i_new\n"
16539                 "             OpBranch %loop\n"
16540
16541                 "    %merge = OpLabel\n"
16542                 "             OpReturnValue %param\n"
16543                 "             OpFunctionEnd\n"
16544         );
16545
16546         const Math16ArgFragments        argFragment1    =
16547         {
16548                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16549                 " %val_src0 = OpLoad %${t0} %src0\n"
16550                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16551                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16552                 "             OpStore %dst %val_dst\n",
16553                 "",
16554                 "",
16555                 "",
16556         };
16557
16558         const Math16ArgFragments        argFragment2    =
16559         {
16560                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16561                 " %val_src0 = OpLoad %${t0} %src0\n"
16562                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16563                 " %val_src1 = OpLoad %${t1} %src1\n"
16564                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16565                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16566                 "             OpStore %dst %val_dst\n",
16567                 "",
16568                 "",
16569                 "",
16570         };
16571
16572         const Math16ArgFragments        argFragment3    =
16573         {
16574                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16575                 " %val_src0 = OpLoad %${t0} %src0\n"
16576                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16577                 " %val_src1 = OpLoad %${t1} %src1\n"
16578                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16579                 " %val_src2 = OpLoad %${t2} %src2\n"
16580                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16581                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16582                 "             OpStore %dst %val_dst\n",
16583                 "",
16584                 "",
16585                 "",
16586         };
16587
16588         const Math16ArgFragments        argFragmentLdExp        =
16589         {
16590                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16591                 " %val_src0 = OpLoad %${t0} %src0\n"
16592                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16593                 " %val_src1 = OpLoad %${t1} %src1\n"
16594                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16595                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16596                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16597                 "             OpStore %dst %val_dst\n",
16598
16599                 "",
16600
16601                 "",
16602
16603                 "",
16604         };
16605
16606         const Math16ArgFragments        argFragmentModfFrac     =
16607         {
16608                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16609                 " %val_src0 = OpLoad %${t0} %src0\n"
16610                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16611                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16612                 "             OpStore %dst %val_dst\n",
16613
16614                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16615
16616                 "",
16617
16618                 "      %tmp = OpVariable %fp_tmp Function\n",
16619         };
16620
16621         const Math16ArgFragments        argFragmentModfInt      =
16622         {
16623                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16624                 " %val_src0 = OpLoad %${t0} %src0\n"
16625                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16626                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16627                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16628                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16629                 "             OpStore %dst %val_dst\n",
16630
16631                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16632
16633                 "",
16634
16635                 "      %tmp = OpVariable %fp_tmp Function\n",
16636         };
16637
16638         const Math16ArgFragments        argFragmentModfStruct   =
16639         {
16640                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16641                 " %val_src0 = OpLoad %${t0} %src0\n"
16642                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16643                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16644                 "             OpStore %tmp_ptr_s %val_tmp\n"
16645                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16646                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16647                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16648                 "             OpStore %dst %val_dst\n",
16649
16650                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16651                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16652                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16653                 "   %c_frac = OpConstant %i32 0\n"
16654                 "    %c_int = OpConstant %i32 1\n",
16655
16656                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16657                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16658
16659                 "      %tmp = OpVariable %fp_tmp Function\n",
16660         };
16661
16662         const Math16ArgFragments        argFragmentFrexpStructS =
16663         {
16664                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16665                 " %val_src0 = OpLoad %${t0} %src0\n"
16666                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16667                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16668                 "             OpStore %tmp_ptr_s %val_tmp\n"
16669                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16670                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16671                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16672                 "             OpStore %dst %val_dst\n",
16673
16674                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16675                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16676                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16677
16678                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16679                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16680
16681                 "      %tmp = OpVariable %fp_tmp Function\n",
16682         };
16683
16684         const Math16ArgFragments        argFragmentFrexpStructE =
16685         {
16686                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16687                 " %val_src0 = OpLoad %${t0} %src0\n"
16688                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16689                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16690                 "             OpStore %tmp_ptr_s %val_tmp\n"
16691                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16692                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16693                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16694                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16695                 "             OpStore %dst %val_dst\n",
16696
16697                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16698                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16699
16700                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16701                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16702
16703                 "      %tmp = OpVariable %fp_tmp Function\n",
16704         };
16705
16706         const Math16ArgFragments        argFragmentFrexpS               =
16707         {
16708                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16709                 " %val_src0 = OpLoad %${t0} %src0\n"
16710                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16711                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16712                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16713                 "             OpStore %dst %val_dst\n",
16714
16715                 "",
16716
16717                 "",
16718
16719                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16720         };
16721
16722         const Math16ArgFragments        argFragmentFrexpE               =
16723         {
16724                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16725                 " %val_src0 = OpLoad %${t0} %src0\n"
16726                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16727                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16728                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16729                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16730                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16731                 "             OpStore %dst %val_dst\n",
16732
16733                 "",
16734
16735                 "",
16736
16737                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16738         };
16739
16740         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16741         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16742         const string                            testName                                = de::toLower(funcNameString);
16743         const Math16ArgFragments*       argFragments                    = DE_NULL;
16744         const size_t                            typeStructStride                = testType.typeStructStride;
16745         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16746         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16747         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16748         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16749         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16750         VulkanFeatures                          features;
16751         SpecResource                            specResource;
16752         map<string, string>                     specs;
16753         map<string, string>                     fragments;
16754         vector<string>                          extensions;
16755         string                                          funcCall;
16756         string                                          funcVariables;
16757         string                                          variables;
16758         string                                          declarations;
16759         string                                          decorations;
16760
16761         switch (testFunc.funcArgsCount)
16762         {
16763                 case 1:
16764                 {
16765                         argFragments = &argFragment1;
16766
16767                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16768                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16769                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16770                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16771                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16772                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16773                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16774                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16775
16776                         break;
16777                 }
16778                 case 2:
16779                 {
16780                         argFragments = &argFragment2;
16781
16782                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16783
16784                         break;
16785                 }
16786                 case 3:
16787                 {
16788                         argFragments = &argFragment3;
16789
16790                         break;
16791                 }
16792                 default:
16793                 {
16794                         TCU_THROW(InternalError, "Invalid number of arguments");
16795                 }
16796         }
16797
16798         if (testFunc.funcArgsCount == 1)
16799         {
16800                 variables +=
16801                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16802                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16803
16804                 decorations +=
16805                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16806                         "OpDecorate %ssbo_src0 Binding 0\n"
16807                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16808                         "OpDecorate %ssbo_dst Binding 1\n";
16809         }
16810         else if (testFunc.funcArgsCount == 2)
16811         {
16812                 variables +=
16813                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16814                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16815                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16816
16817                 decorations +=
16818                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16819                         "OpDecorate %ssbo_src0 Binding 0\n"
16820                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16821                         "OpDecorate %ssbo_src1 Binding 1\n"
16822                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16823                         "OpDecorate %ssbo_dst Binding 2\n";
16824         }
16825         else if (testFunc.funcArgsCount == 3)
16826         {
16827                 variables +=
16828                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16829                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16830                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16831                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16832
16833                 decorations +=
16834                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16835                         "OpDecorate %ssbo_src0 Binding 0\n"
16836                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16837                         "OpDecorate %ssbo_src1 Binding 1\n"
16838                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16839                         "OpDecorate %ssbo_src2 Binding 2\n"
16840                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16841                         "OpDecorate %ssbo_dst Binding 3\n";
16842         }
16843         else
16844         {
16845                 TCU_THROW(InternalError, "Invalid number of function arguments");
16846         }
16847
16848         variables       += argFragments->variables;
16849         decorations     += argFragments->decorations;
16850
16851         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16852         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16853         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16854         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16855         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16856         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16857         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16858         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16859         specs["struct_stride"]          = de::toString(typeStructStride);
16860         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16861         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16862         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16863
16864         variables                                       = StringTemplate(variables).specialize(specs);
16865         decorations                                     = StringTemplate(decorations).specialize(specs);
16866         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16867         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16868
16869         specs["num_data_points"]        = de::toString(iterations);
16870         specs["arg_vars"]                       = variables;
16871         specs["arg_decorations"]        = decorations;
16872         specs["arg_infunc_vars"]        = funcVariables;
16873         specs["arg_func_call"]          = funcCall;
16874
16875         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16876         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16877         fragments["decoration"]         = decoration.specialize(specs);
16878         fragments["pre_main"]           = preMain.specialize(specs);
16879         fragments["testfun"]            = testFun.specialize(specs);
16880
16881         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16882         {
16883                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16884                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16885                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16886                                                                                                         : -1;
16887                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16888
16889                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16890         }
16891
16892         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16893         specResource.verifyIO = testFunc.verifyFunc;
16894
16895         extensions.push_back("VK_KHR_16bit_storage");
16896         extensions.push_back("VK_KHR_shader_float16_int8");
16897
16898         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16899         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16900
16901         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16902 }
16903
16904 template<size_t C, class SpecResource>
16905 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16906 {
16907         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16908
16909         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16910         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16911         const Math16TestFunc                    testFuncs[]             =
16912         {
16913                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16914                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16915                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16916                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16917                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16918                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16919                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16920                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16921                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16922                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16923                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16924                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16925                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16926                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16927                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16928                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16929                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16930                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16931                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16932                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16933                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16934                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16935                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16936                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16937                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16938                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16939                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16940                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16941                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16942                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16943                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16944                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16945                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16946                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16947                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16948                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16949                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16950                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16951                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16952                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16953                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16954                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16955                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16956                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16957                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16958                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16959                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16960                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16961                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16962                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16963                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16964                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16965                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16966                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16967                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16968                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16969                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16970                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16971                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16972                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16973         };
16974
16975         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16976         {
16977                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16978                 const string                    funcNameString  = testFunc.funcName;
16979
16980                 if ((C != 3) && funcNameString == "Cross")
16981                         continue;
16982
16983                 if ((C < 2) && funcNameString == "OpDot")
16984                         continue;
16985
16986                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16987                         continue;
16988
16989                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16990         }
16991
16992         return testGroup.release();
16993 }
16994
16995 template<class SpecResource>
16996 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16997 {
16998         const std::string                               testGroupName   ("arithmetic");
16999         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
17000         const Math16TestFunc                    testFuncs[]             =
17001         {
17002                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
17003                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
17004                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
17005                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
17006                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
17007                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
17008                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
17009                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
17010                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
17011                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
17012                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
17013                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
17014                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
17015                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
17016                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
17017                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
17018                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
17019                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
17020                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
17021                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
17022                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
17023                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
17024                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
17025                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
17026                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
17027                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
17028                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
17029                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
17030                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
17031                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
17032                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
17033                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
17034                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
17035                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
17036                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
17037                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
17038                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
17039                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
17040                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
17041                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
17042                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
17043                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
17044                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
17045                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
17046                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
17047                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
17048                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
17049                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
17050                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
17051                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
17052                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
17053                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
17054                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
17055                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
17056                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
17057                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
17058                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
17059                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
17060                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
17061                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
17062                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
17063                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
17064                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
17065                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
17066                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
17067                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
17068                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
17069                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
17070                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
17071                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
17072                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
17073                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
17074                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
17075                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
17076                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
17077                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
17078         };
17079
17080         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
17081         {
17082                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
17083
17084                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
17085         }
17086
17087         return testGroup.release();
17088 }
17089
17090 const string getNumberTypeName (const NumberType type)
17091 {
17092         if (type == NUMBERTYPE_INT32)
17093         {
17094                 return "int";
17095         }
17096         else if (type == NUMBERTYPE_UINT32)
17097         {
17098                 return "uint";
17099         }
17100         else if (type == NUMBERTYPE_FLOAT32)
17101         {
17102                 return "float";
17103         }
17104         else
17105         {
17106                 DE_ASSERT(false);
17107                 return "";
17108         }
17109 }
17110
17111 deInt32 getInt(de::Random& rnd)
17112 {
17113         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
17114 }
17115
17116 const string repeatString (const string& str, int times)
17117 {
17118         string filler;
17119         for (int i = 0; i < times; ++i)
17120         {
17121                 filler += str;
17122         }
17123         return filler;
17124 }
17125
17126 const string getRandomConstantString (const NumberType type, de::Random& rnd)
17127 {
17128         if (type == NUMBERTYPE_INT32)
17129         {
17130                 return numberToString<deInt32>(getInt(rnd));
17131         }
17132         else if (type == NUMBERTYPE_UINT32)
17133         {
17134                 return numberToString<deUint32>(rnd.getUint32());
17135         }
17136         else if (type == NUMBERTYPE_FLOAT32)
17137         {
17138                 return numberToString<float>(rnd.getFloat());
17139         }
17140         else
17141         {
17142                 DE_ASSERT(false);
17143                 return "";
17144         }
17145 }
17146
17147 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17148 {
17149         map<string, string> params;
17150
17151         // Vec2 to Vec4
17152         for (int width = 2; width <= 4; ++width)
17153         {
17154                 const string randomConst = numberToString(getInt(rnd));
17155                 const string widthStr = numberToString(width);
17156                 const string composite_type = "${customType}vec" + widthStr;
17157                 const int index = rnd.getInt(0, width-1);
17158
17159                 params["type"]                  = "vec";
17160                 params["name"]                  = params["type"] + "_" + widthStr;
17161                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
17162                 params["compositeType"]         = composite_type;
17163                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17164                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
17165                 params["indexes"]               = numberToString(index);
17166                 testCases.push_back(params);
17167         }
17168 }
17169
17170 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17171 {
17172         const int limit = 10;
17173         map<string, string> params;
17174
17175         for (int width = 2; width <= limit; ++width)
17176         {
17177                 string randomConst = numberToString(getInt(rnd));
17178                 string widthStr = numberToString(width);
17179                 int index = rnd.getInt(0, width-1);
17180
17181                 params["type"]                  = "array";
17182                 params["name"]                  = params["type"] + "_" + widthStr;
17183                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
17184                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
17185                 params["compositeType"]         = "%composite";
17186                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17187                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17188                 params["indexes"]               = numberToString(index);
17189                 testCases.push_back(params);
17190         }
17191 }
17192
17193 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17194 {
17195         const int limit = 10;
17196         map<string, string> params;
17197
17198         for (int width = 2; width <= limit; ++width)
17199         {
17200                 string randomConst = numberToString(getInt(rnd));
17201                 int index = rnd.getInt(0, width-1);
17202
17203                 params["type"]                  = "struct";
17204                 params["name"]                  = params["type"] + "_" + numberToString(width);
17205                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
17206                 params["compositeType"]         = "%composite";
17207                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17208                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17209                 params["indexes"]               = numberToString(index);
17210                 testCases.push_back(params);
17211         }
17212 }
17213
17214 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17215 {
17216         map<string, string> params;
17217
17218         // Vec2 to Vec4
17219         for (int width = 2; width <= 4; ++width)
17220         {
17221                 string widthStr = numberToString(width);
17222
17223                 for (int column = 2 ; column <= 4; ++column)
17224                 {
17225                         int index_0 = rnd.getInt(0, column-1);
17226                         int index_1 = rnd.getInt(0, width-1);
17227                         string columnStr = numberToString(column);
17228
17229                         params["type"]          = "matrix";
17230                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
17231                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
17232                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
17233                         params["compositeType"] = "%composite";
17234
17235                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
17236                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
17237
17238                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17239                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17240                         testCases.push_back(params);
17241                 }
17242         }
17243 }
17244
17245 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17246 {
17247         createVectorCompositeCases(testCases, rnd, type);
17248         createArrayCompositeCases(testCases, rnd, type);
17249         createStructCompositeCases(testCases, rnd, type);
17250         // Matrix only supports float types
17251         if (type == NUMBERTYPE_FLOAT32)
17252         {
17253                 createMatrixCompositeCases(testCases, rnd, type);
17254         }
17255 }
17256
17257 const string getAssemblyTypeDeclaration (const NumberType type)
17258 {
17259         switch (type)
17260         {
17261                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17262                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17263                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17264                 default:                        DE_ASSERT(false); return "";
17265         }
17266 }
17267
17268 const string getAssemblyTypeName (const NumberType type)
17269 {
17270         switch (type)
17271         {
17272                 case NUMBERTYPE_INT32:          return "%i32";
17273                 case NUMBERTYPE_UINT32:         return "%u32";
17274                 case NUMBERTYPE_FLOAT32:        return "%f32";
17275                 default:                        DE_ASSERT(false); return "";
17276         }
17277 }
17278
17279 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17280 {
17281         map<string, string>     parameters(params);
17282
17283         const string customType = getAssemblyTypeName(type);
17284         map<string, string> substCustomType;
17285         substCustomType["customType"] = customType;
17286         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17287         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17288         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17289         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17290         parameters["customType"] = customType;
17291         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17292
17293         if (parameters.at("compositeType") != "%u32vec3")
17294         {
17295                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17296         }
17297
17298         return StringTemplate(
17299                 "OpCapability Shader\n"
17300                 "OpCapability Matrix\n"
17301                 "OpMemoryModel Logical GLSL450\n"
17302                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17303                 "OpExecutionMode %main LocalSize 1 1 1\n"
17304
17305                 "OpSource GLSL 430\n"
17306                 "OpName %main           \"main\"\n"
17307                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17308
17309                 // Decorators
17310                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17311                 "OpDecorate %buf BufferBlock\n"
17312                 "OpDecorate %indata DescriptorSet 0\n"
17313                 "OpDecorate %indata Binding 0\n"
17314                 "OpDecorate %outdata DescriptorSet 0\n"
17315                 "OpDecorate %outdata Binding 1\n"
17316                 "OpDecorate %customarr ArrayStride 4\n"
17317                 "${compositeDecorator}"
17318                 "OpMemberDecorate %buf 0 Offset 0\n"
17319
17320                 // General types
17321                 "%void      = OpTypeVoid\n"
17322                 "%voidf     = OpTypeFunction %void\n"
17323                 "%u32       = OpTypeInt 32 0\n"
17324                 "%i32       = OpTypeInt 32 1\n"
17325                 "%f32       = OpTypeFloat 32\n"
17326
17327                 // Composite declaration
17328                 "${compositeDecl}"
17329
17330                 // Constants
17331                 "${filler}"
17332
17333                 "${u32vec3Decl:opt}"
17334                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17335
17336                 // Inherited from custom
17337                 "%customptr = OpTypePointer Uniform ${customType}\n"
17338                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17339                 "%buf       = OpTypeStruct %customarr\n"
17340                 "%bufptr    = OpTypePointer Uniform %buf\n"
17341
17342                 "%indata    = OpVariable %bufptr Uniform\n"
17343                 "%outdata   = OpVariable %bufptr Uniform\n"
17344
17345                 "%id        = OpVariable %uvec3ptr Input\n"
17346                 "%zero      = OpConstant %i32 0\n"
17347
17348                 "%main      = OpFunction %void None %voidf\n"
17349                 "%label     = OpLabel\n"
17350                 "%idval     = OpLoad %u32vec3 %id\n"
17351                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17352
17353                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17354                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17355                 // Read the input value
17356                 "%inval     = OpLoad ${customType} %inloc\n"
17357                 // Create the composite and fill it
17358                 "${compositeConstruct}"
17359                 // Insert the input value to a place
17360                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17361                 // Read back the value from the position
17362                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17363                 // Store it in the output position
17364                 "             OpStore %outloc %out_val\n"
17365                 "             OpReturn\n"
17366                 "             OpFunctionEnd\n"
17367         ).specialize(parameters);
17368 }
17369
17370 template<typename T>
17371 BufferSp createCompositeBuffer(T number)
17372 {
17373         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17374 }
17375
17376 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17377 {
17378         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17379         de::Random                                              rnd             (deStringHash(group->getName()));
17380
17381         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17382         {
17383                 NumberType                                              numberType              = NumberType(type);
17384                 const string                                    typeName                = getNumberTypeName(numberType);
17385                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17386                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17387                 vector<map<string, string> >    testCases;
17388
17389                 createCompositeCases(testCases, rnd, numberType);
17390
17391                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17392                 {
17393                         ComputeShaderSpec       spec;
17394
17395                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17396
17397                         switch (numberType)
17398                         {
17399                                 case NUMBERTYPE_INT32:
17400                                 {
17401                                         deInt32 number = getInt(rnd);
17402                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17403                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17404                                         break;
17405                                 }
17406                                 case NUMBERTYPE_UINT32:
17407                                 {
17408                                         deUint32 number = rnd.getUint32();
17409                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17410                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17411                                         break;
17412                                 }
17413                                 case NUMBERTYPE_FLOAT32:
17414                                 {
17415                                         float number = rnd.getFloat();
17416                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17417                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17418                                         break;
17419                                 }
17420                                 default:
17421                                         DE_ASSERT(false);
17422                         }
17423
17424                         spec.numWorkGroups = IVec3(1, 1, 1);
17425                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17426                 }
17427                 group->addChild(subGroup.release());
17428         }
17429         return group.release();
17430 }
17431
17432 struct AssemblyStructInfo
17433 {
17434         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17435         : components    (comp)
17436         , index                 (idx)
17437         {}
17438
17439         deUint32 components;
17440         deUint32 index;
17441 };
17442
17443 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17444 {
17445         // Create the full index string
17446         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17447         // Convert it to list of indexes
17448         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17449
17450         map<string, string>     parameters      (params);
17451         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17452         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17453         parameters["insertIndexes"]     = fullIndex;
17454
17455         // In matrix cases the last two index is the CompositeExtract indexes
17456         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17457
17458         // Construct the extractIndex
17459         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17460         {
17461                 parameters["extractIndexes"] += " " + *index;
17462         }
17463
17464         // Remove the last 1 or 2 element depends on matrix case or not
17465         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17466
17467         deUint32 id = 0;
17468         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17469         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17470         {
17471                 string indexId = "%index_" + numberToString(id++);
17472                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17473                 parameters["accessChainIndexes"] += " " + indexId;
17474         }
17475
17476         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17477
17478         const string customType = getAssemblyTypeName(type);
17479         map<string, string> substCustomType;
17480         substCustomType["customType"] = customType;
17481         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17482         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17483         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17484         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17485         parameters["customType"] = customType;
17486
17487         const string compositeType = parameters.at("compositeType");
17488         map<string, string> substCompositeType;
17489         substCompositeType["compositeType"] = compositeType;
17490         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17491         if (compositeType != "%u32vec3")
17492         {
17493                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17494         }
17495
17496         return StringTemplate(
17497                 "OpCapability Shader\n"
17498                 "OpCapability Matrix\n"
17499                 "OpMemoryModel Logical GLSL450\n"
17500                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17501                 "OpExecutionMode %main LocalSize 1 1 1\n"
17502
17503                 "OpSource GLSL 430\n"
17504                 "OpName %main           \"main\"\n"
17505                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17506                 // Decorators
17507                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17508                 "OpDecorate %buf BufferBlock\n"
17509                 "OpDecorate %indata DescriptorSet 0\n"
17510                 "OpDecorate %indata Binding 0\n"
17511                 "OpDecorate %outdata DescriptorSet 0\n"
17512                 "OpDecorate %outdata Binding 1\n"
17513                 "OpDecorate %customarr ArrayStride 4\n"
17514                 "${compositeDecorator}"
17515                 "OpMemberDecorate %buf 0 Offset 0\n"
17516                 // General types
17517                 "%void      = OpTypeVoid\n"
17518                 "%voidf     = OpTypeFunction %void\n"
17519                 "%i32       = OpTypeInt 32 1\n"
17520                 "%u32       = OpTypeInt 32 0\n"
17521                 "%f32       = OpTypeFloat 32\n"
17522                 // Custom types
17523                 "${compositeDecl}"
17524                 // %u32vec3 if not already declared in ${compositeDecl}
17525                 "${u32vec3Decl:opt}"
17526                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17527                 // Inherited from composite
17528                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17529                 "%struct_t  = OpTypeStruct${structType}\n"
17530                 "%struct_p  = OpTypePointer Function %struct_t\n"
17531                 // Constants
17532                 "${filler}"
17533                 "${accessChainConstDeclaration}"
17534                 // Inherited from custom
17535                 "%customptr = OpTypePointer Uniform ${customType}\n"
17536                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17537                 "%buf       = OpTypeStruct %customarr\n"
17538                 "%bufptr    = OpTypePointer Uniform %buf\n"
17539                 "%indata    = OpVariable %bufptr Uniform\n"
17540                 "%outdata   = OpVariable %bufptr Uniform\n"
17541
17542                 "%id        = OpVariable %uvec3ptr Input\n"
17543                 "%zero      = OpConstant %u32 0\n"
17544                 "%main      = OpFunction %void None %voidf\n"
17545                 "%label     = OpLabel\n"
17546                 "%struct_v  = OpVariable %struct_p Function\n"
17547                 "%idval     = OpLoad %u32vec3 %id\n"
17548                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17549                 // Create the input/output type
17550                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17551                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17552                 // Read the input value
17553                 "%inval     = OpLoad ${customType} %inloc\n"
17554                 // Create the composite and fill it
17555                 "${compositeConstruct}"
17556                 // Create the struct and fill it with the composite
17557                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17558                 // Insert the value
17559                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17560                 // Store the object
17561                 "             OpStore %struct_v %comp_obj\n"
17562                 // Get deepest possible composite pointer
17563                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17564                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17565                 // Read back the stored value
17566                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17567                 "             OpStore %outloc %read_val\n"
17568                 "             OpReturn\n"
17569                 "             OpFunctionEnd\n"
17570         ).specialize(parameters);
17571 }
17572
17573 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17574 {
17575         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17576         de::Random                                              rnd                             (deStringHash(group->getName()));
17577
17578         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17579         {
17580                 NumberType                                              numberType      = NumberType(type);
17581                 const string                                    typeName        = getNumberTypeName(numberType);
17582                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17583                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17584
17585                 vector<map<string, string> >    testCases;
17586                 createCompositeCases(testCases, rnd, numberType);
17587
17588                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17589                 {
17590                         ComputeShaderSpec       spec;
17591
17592                         // Number of components inside of a struct
17593                         deUint32 structComponents = rnd.getInt(2, 8);
17594                         // Component index value
17595                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17596                         AssemblyStructInfo structInfo(structComponents, structIndex);
17597
17598                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17599
17600                         switch (numberType)
17601                         {
17602                                 case NUMBERTYPE_INT32:
17603                                 {
17604                                         deInt32 number = getInt(rnd);
17605                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17606                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17607                                         break;
17608                                 }
17609                                 case NUMBERTYPE_UINT32:
17610                                 {
17611                                         deUint32 number = rnd.getUint32();
17612                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17613                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17614                                         break;
17615                                 }
17616                                 case NUMBERTYPE_FLOAT32:
17617                                 {
17618                                         float number = rnd.getFloat();
17619                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17620                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17621                                         break;
17622                                 }
17623                                 default:
17624                                         DE_ASSERT(false);
17625                         }
17626                         spec.numWorkGroups = IVec3(1, 1, 1);
17627                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17628                 }
17629                 group->addChild(subGroup.release());
17630         }
17631         return group.release();
17632 }
17633
17634 // If the params missing, uninitialized case
17635 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17636 {
17637         map<string, string> parameters(params);
17638
17639         parameters["customType"]        = getAssemblyTypeName(type);
17640
17641         // Declare the const value, and use it in the initializer
17642         if (params.find("constValue") != params.end())
17643         {
17644                 parameters["variableInitializer"]       = " %const";
17645         }
17646         // Uninitialized case
17647         else
17648         {
17649                 parameters["commentDecl"]       = ";";
17650         }
17651
17652         return StringTemplate(
17653                 "OpCapability Shader\n"
17654                 "OpMemoryModel Logical GLSL450\n"
17655                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17656                 "OpExecutionMode %main LocalSize 1 1 1\n"
17657                 "OpSource GLSL 430\n"
17658                 "OpName %main           \"main\"\n"
17659                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17660                 // Decorators
17661                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17662                 "OpDecorate %indata DescriptorSet 0\n"
17663                 "OpDecorate %indata Binding 0\n"
17664                 "OpDecorate %outdata DescriptorSet 0\n"
17665                 "OpDecorate %outdata Binding 1\n"
17666                 "OpDecorate %in_arr ArrayStride 4\n"
17667                 "OpDecorate %in_buf BufferBlock\n"
17668                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17669                 // Base types
17670                 "%void       = OpTypeVoid\n"
17671                 "%voidf      = OpTypeFunction %void\n"
17672                 "%u32        = OpTypeInt 32 0\n"
17673                 "%i32        = OpTypeInt 32 1\n"
17674                 "%f32        = OpTypeFloat 32\n"
17675                 "%uvec3      = OpTypeVector %u32 3\n"
17676                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17677                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17678                 // Derived types
17679                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17680                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17681                 "%in_buf     = OpTypeStruct %in_arr\n"
17682                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17683                 "%indata     = OpVariable %in_bufptr Uniform\n"
17684                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17685                 "%id         = OpVariable %uvec3ptr Input\n"
17686                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17687                 // Constants
17688                 "%zero       = OpConstant %i32 0\n"
17689                 // Main function
17690                 "%main       = OpFunction %void None %voidf\n"
17691                 "%label      = OpLabel\n"
17692                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17693                 "%idval      = OpLoad %uvec3 %id\n"
17694                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17695                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17696                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17697
17698                 "%outval     = OpLoad ${customType} %out_var\n"
17699                 "              OpStore %outloc %outval\n"
17700                 "              OpReturn\n"
17701                 "              OpFunctionEnd\n"
17702         ).specialize(parameters);
17703 }
17704
17705 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17706 {
17707         DE_ASSERT(outputAllocs.size() != 0);
17708         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17709
17710         // Use custom epsilon because of the float->string conversion
17711         const float     epsilon = 0.00001f;
17712
17713         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17714         {
17715                 vector<deUint8> expectedBytes;
17716                 float                   expected;
17717                 float                   actual;
17718
17719                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17720                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17721                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17722
17723                 // Test with epsilon
17724                 if (fabs(expected - actual) > epsilon)
17725                 {
17726                         log << TestLog::Message << "Error: The actual and expected values not matching."
17727                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17728                         return false;
17729                 }
17730         }
17731         return true;
17732 }
17733
17734 // Checks if the driver crash with uninitialized cases
17735 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17736 {
17737         DE_ASSERT(outputAllocs.size() != 0);
17738         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17739
17740         // Copy and discard the result.
17741         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17742         {
17743                 vector<deUint8> expectedBytes;
17744                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17745
17746                 const size_t    width                   = expectedBytes.size();
17747                 vector<char>    data                    (width);
17748
17749                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17750         }
17751         return true;
17752 }
17753
17754 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17755 {
17756         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17757         de::Random                                              rnd             (deStringHash(group->getName()));
17758
17759         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17760         {
17761                 NumberType                                              numberType      = NumberType(type);
17762                 const string                                    typeName        = getNumberTypeName(numberType);
17763                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17764                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17765
17766                 // 2 similar subcases (initialized and uninitialized)
17767                 for (int subCase = 0; subCase < 2; ++subCase)
17768                 {
17769                         ComputeShaderSpec spec;
17770                         spec.numWorkGroups = IVec3(1, 1, 1);
17771
17772                         map<string, string>                             params;
17773
17774                         switch (numberType)
17775                         {
17776                                 case NUMBERTYPE_INT32:
17777                                 {
17778                                         deInt32 number = getInt(rnd);
17779                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17780                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17781                                         params["constValue"] = numberToString(number);
17782                                         break;
17783                                 }
17784                                 case NUMBERTYPE_UINT32:
17785                                 {
17786                                         deUint32 number = rnd.getUint32();
17787                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17788                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17789                                         params["constValue"] = numberToString(number);
17790                                         break;
17791                                 }
17792                                 case NUMBERTYPE_FLOAT32:
17793                                 {
17794                                         float number = rnd.getFloat();
17795                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17796                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17797                                         spec.verifyIO = &compareFloats;
17798                                         params["constValue"] = numberToString(number);
17799                                         break;
17800                                 }
17801                                 default:
17802                                         DE_ASSERT(false);
17803                         }
17804
17805                         // Initialized subcase
17806                         if (!subCase)
17807                         {
17808                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17809                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17810                         }
17811                         // Uninitialized subcase
17812                         else
17813                         {
17814                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17815                                 spec.verifyIO = &passthruVerify;
17816                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17817                         }
17818                 }
17819                 group->addChild(subGroup.release());
17820         }
17821         return group.release();
17822 }
17823
17824 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17825 {
17826         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17827         RGBA                                                    defaultColors[4];
17828         map<string, string>                             opNopFragments;
17829
17830         getDefaultColors(defaultColors);
17831
17832         opNopFragments["testfun"]               =
17833                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17834                 "%param1 = OpFunctionParameter %v4f32\n"
17835                 "%label_testfun = OpLabel\n"
17836                 "OpNop\n"
17837                 "OpNop\n"
17838                 "OpNop\n"
17839                 "OpNop\n"
17840                 "OpNop\n"
17841                 "OpNop\n"
17842                 "OpNop\n"
17843                 "OpNop\n"
17844                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17845                 "%b = OpFAdd %f32 %a %a\n"
17846                 "OpNop\n"
17847                 "%c = OpFSub %f32 %b %a\n"
17848                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17849                 "OpNop\n"
17850                 "OpNop\n"
17851                 "OpReturnValue %ret\n"
17852                 "OpFunctionEnd\n";
17853
17854         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17855
17856         return testGroup.release();
17857 }
17858
17859 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17860 {
17861         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17862         RGBA                                                    defaultColors[4];
17863         map<string, string>                             opNameFragments;
17864
17865         getDefaultColors(defaultColors);
17866
17867         opNameFragments["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                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17875                 "OpReturnValue %ret\n"
17876                 "OpFunctionEnd\n";
17877
17878         opNameFragments["debug"] =
17879                 "OpName %BP_main \"not_main\"";
17880
17881         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17882
17883         return testGroup.release();
17884 }
17885
17886 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17887 {
17888         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17889
17890         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17891         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17892         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17893         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17894         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17895         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17896         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17897         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17898         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17899         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17900         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17901         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17902         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17903         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17904         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17905         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17906         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17907         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17908
17909         return testGroup.release();
17910 }
17911
17912 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17913 {
17914         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17915
17916         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17917         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17918         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17919         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17920         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17921         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17922         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17923         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17924         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17925         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17926         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17927         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17928         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17929         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17930         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17931
17932         return testGroup.release();
17933 }
17934
17935 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17936 {
17937         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17938
17939         de::Random                                              rnd                             (deStringHash(group->getName()));
17940         const int               numElements             = 100;
17941         vector<float>   inputData               (numElements, 0);
17942         vector<float>   outputData              (numElements, 0);
17943         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17944
17945         const StringTemplate                    shaderTemplate  (
17946                 "${CAPS}\n"
17947                 "OpMemoryModel Logical GLSL450\n"
17948                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17949                 "OpExecutionMode %main LocalSize 1 1 1\n"
17950                 "OpSource GLSL 430\n"
17951                 "OpName %main           \"main\"\n"
17952                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17953
17954                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17955
17956                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17957
17958                 "%id        = OpVariable %uvec3ptr Input\n"
17959                 "${CONST}\n"
17960                 "%main      = OpFunction %void None %voidf\n"
17961                 "%label     = OpLabel\n"
17962                 "%idval     = OpLoad %uvec3 %id\n"
17963                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17964                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17965
17966                 "${TEST}\n"
17967
17968                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17969                 "             OpStore %outloc %res\n"
17970                 "             OpReturn\n"
17971                 "             OpFunctionEnd\n"
17972         );
17973
17974         // Each test case produces 4 boolean values, and we want each of these values
17975         // to come froma different combination of the available bit-sizes, so compute
17976         // all possible combinations here.
17977         vector<deUint32>        widths;
17978         widths.push_back(32);
17979         widths.push_back(16);
17980         widths.push_back(8);
17981
17982         vector<IVec4>   cases;
17983         for (size_t width0 = 0; width0 < widths.size(); width0++)
17984         {
17985                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17986                 {
17987                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17988                         {
17989                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17990                                 {
17991                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17992                                 }
17993                         }
17994                 }
17995         }
17996
17997         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17998         {
17999                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
18000                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
18001                         continue;
18002
18003                 map<string, string>     specializations;
18004                 ComputeShaderSpec       spec;
18005
18006                 // Inject appropriate capabilities and reference constants depending
18007                 // on the bit-sizes required by this test case
18008                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
18009                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
18010                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
18011
18012                 string capsStr  = "OpCapability Shader\n";
18013                 string constStr =
18014                         "%c0i32     = OpConstant %i32 0\n"
18015                         "%c1f32     = OpConstant %f32 1.0\n"
18016                         "%c0f32     = OpConstant %f32 0.0\n";
18017
18018                 if (hasFloat32)
18019                 {
18020                         constStr        +=
18021                                 "%c10f32    = OpConstant %f32 10.0\n"
18022                                 "%c25f32    = OpConstant %f32 25.0\n"
18023                                 "%c50f32    = OpConstant %f32 50.0\n"
18024                                 "%c90f32    = OpConstant %f32 90.0\n";
18025                 }
18026
18027                 if (hasFloat16)
18028                 {
18029                         capsStr         += "OpCapability Float16\n";
18030                         constStr        +=
18031                                 "%f16       = OpTypeFloat 16\n"
18032                                 "%c10f16    = OpConstant %f16 10.0\n"
18033                                 "%c25f16    = OpConstant %f16 25.0\n"
18034                                 "%c50f16    = OpConstant %f16 50.0\n"
18035                                 "%c90f16    = OpConstant %f16 90.0\n";
18036                 }
18037
18038                 if (hasInt8)
18039                 {
18040                         capsStr         += "OpCapability Int8\n";
18041                         constStr        +=
18042                                 "%i8        = OpTypeInt 8 1\n"
18043                                 "%c10i8     = OpConstant %i8 10\n"
18044                                 "%c25i8     = OpConstant %i8 25\n"
18045                                 "%c50i8     = OpConstant %i8 50\n"
18046                                 "%c90i8     = OpConstant %i8 90\n";
18047                 }
18048
18049                 // Each invocation reads a different float32 value as input. Depending on
18050                 // the bit-sizes required by the particular test case, we also produce
18051                 // float16 and/or and int8 values by converting from the 32-bit float.
18052                 string testStr  = "";
18053                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
18054                 if (hasFloat16)
18055                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
18056                 if (hasInt8)
18057                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
18058
18059                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
18060                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
18061                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
18062                 // other way around, so in this case we want < instead of <=.
18063                 if (cases[caseNdx][0] == 32)
18064                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
18065                 else if (cases[caseNdx][0] == 16)
18066                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
18067                 else
18068                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
18069
18070                 if (cases[caseNdx][1] == 32)
18071                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
18072                 else if (cases[caseNdx][1] == 16)
18073                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
18074                 else
18075                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
18076
18077                 if (cases[caseNdx][2] == 32)
18078                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
18079                 else if (cases[caseNdx][2] == 16)
18080                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
18081                 else
18082                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
18083
18084                 if (cases[caseNdx][3] == 32)
18085                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
18086                 else if (cases[caseNdx][3] == 16)
18087                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
18088                 else
18089                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
18090
18091                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
18092                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
18093                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
18094                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
18095                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
18096
18097                 specializations["CAPS"]         = capsStr;
18098                 specializations["CONST"]        = constStr;
18099                 specializations["TEST"]         = testStr;
18100
18101                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
18102                 for (size_t ndx = 0; ndx < numElements; ++ndx)
18103                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
18104
18105                 spec.assembly = shaderTemplate.specialize(specializations);
18106                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
18107                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
18108                 spec.numWorkGroups = IVec3(numElements, 1, 1);
18109                 if (hasFloat16)
18110                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
18111                 if (hasInt8)
18112                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
18113                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
18114
18115                 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]);
18116                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
18117         }
18118
18119         return group.release();
18120 }
18121
18122 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
18123 {
18124         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
18125
18126         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
18127
18128         return testGroup.release();
18129 }
18130
18131 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
18132 {
18133         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
18134         vector<CaseParameter>                   abuseCases;
18135         RGBA                                                    defaultColors[4];
18136         map<string, string>                             opNameFragments;
18137
18138         getOpNameAbuseCases(abuseCases);
18139         getDefaultColors(defaultColors);
18140
18141         opNameFragments["testfun"] =
18142                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18143                 "%param1     = OpFunctionParameter %v4f32\n"
18144                 "%label_func = OpLabel\n"
18145                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18146                 "%b          = OpFAdd %f32 %a %a\n"
18147                 "%c          = OpFSub %f32 %b %a\n"
18148                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
18149                 "OpReturnValue %ret\n"
18150                 "OpFunctionEnd\n";
18151
18152         for (unsigned int i = 0; i < abuseCases.size(); i++)
18153         {
18154                 string casename;
18155                 casename = string("main") + abuseCases[i].name;
18156
18157                 opNameFragments["debug"] =
18158                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
18159
18160                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18161         }
18162
18163         for (unsigned int i = 0; i < abuseCases.size(); i++)
18164         {
18165                 string casename;
18166                 casename = string("b") + abuseCases[i].name;
18167
18168                 opNameFragments["debug"] =
18169                         "OpName %b \"" + abuseCases[i].param + "\"";
18170
18171                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18172         }
18173
18174         {
18175                 opNameFragments["debug"] =
18176                         "OpName %test_code \"name1\"\n"
18177                         "OpName %param1    \"name2\"\n"
18178                         "OpName %a         \"name3\"\n"
18179                         "OpName %b         \"name4\"\n"
18180                         "OpName %c         \"name5\"\n"
18181                         "OpName %ret       \"name6\"\n";
18182
18183                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18184         }
18185
18186         {
18187                 opNameFragments["debug"] =
18188                         "OpName %test_code \"the_same\"\n"
18189                         "OpName %param1    \"the_same\"\n"
18190                         "OpName %a         \"the_same\"\n"
18191                         "OpName %b         \"the_same\"\n"
18192                         "OpName %c         \"the_same\"\n"
18193                         "OpName %ret       \"the_same\"\n";
18194
18195                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18196         }
18197
18198         {
18199                 opNameFragments["debug"] =
18200                         "OpName %BP_main \"to_be\"\n"
18201                         "OpName %BP_main \"or_not\"\n"
18202                         "OpName %BP_main \"to_be\"\n";
18203
18204                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18205         }
18206
18207         {
18208                 opNameFragments["debug"] =
18209                         "OpName %b \"to_be\"\n"
18210                         "OpName %b \"or_not\"\n"
18211                         "OpName %b \"to_be\"\n";
18212
18213                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18214         }
18215
18216         return abuseGroup.release();
18217 }
18218
18219
18220 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
18221 {
18222         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
18223         vector<CaseParameter>                   abuseCases;
18224         RGBA                                                    defaultColors[4];
18225         map<string, string>                             opMemberNameFragments;
18226
18227         getOpNameAbuseCases(abuseCases);
18228         getDefaultColors(defaultColors);
18229
18230         opMemberNameFragments["pre_main"] =
18231                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
18232
18233         opMemberNameFragments["testfun"] =
18234                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18235                 "%param1     = OpFunctionParameter %v4f32\n"
18236                 "%label_func = OpLabel\n"
18237                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18238                 "%b          = OpFAdd %f32 %a %a\n"
18239                 "%c          = OpFSub %f32 %b %a\n"
18240                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18241                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18242                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18243                 "OpReturnValue %ret\n"
18244                 "OpFunctionEnd\n";
18245
18246         for (unsigned int i = 0; i < abuseCases.size(); i++)
18247         {
18248                 string casename;
18249                 casename = string("f3str_x") + abuseCases[i].name;
18250
18251                 opMemberNameFragments["debug"] =
18252                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18253
18254                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18255         }
18256
18257         {
18258                 opMemberNameFragments["debug"] =
18259                         "OpMemberName %f3str 0 \"name1\"\n"
18260                         "OpMemberName %f3str 1 \"name2\"\n"
18261                         "OpMemberName %f3str 2 \"name3\"\n";
18262
18263                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18264         }
18265
18266         {
18267                 opMemberNameFragments["debug"] =
18268                         "OpMemberName %f3str 0 \"the_same\"\n"
18269                         "OpMemberName %f3str 1 \"the_same\"\n"
18270                         "OpMemberName %f3str 2 \"the_same\"\n";
18271
18272                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18273         }
18274
18275         {
18276                 opMemberNameFragments["debug"] =
18277                         "OpMemberName %f3str 0 \"to_be\"\n"
18278                         "OpMemberName %f3str 1 \"or_not\"\n"
18279                         "OpMemberName %f3str 0 \"to_be\"\n"
18280                         "OpMemberName %f3str 2 \"makes_no\"\n"
18281                         "OpMemberName %f3str 0 \"difference\"\n"
18282                         "OpMemberName %f3str 0 \"to_me\"\n";
18283
18284
18285                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18286         }
18287
18288         return abuseGroup.release();
18289 }
18290
18291 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18292 {
18293         vector<deUint32>        result;
18294         de::Random                      rnd             (seed);
18295
18296         result.reserve(numDataPoints);
18297
18298         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18299                 result.push_back(rnd.getUint32());
18300
18301         return result;
18302 }
18303
18304 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18305 {
18306         vector<deUint32>        result;
18307
18308         result.reserve(inData1.size());
18309
18310         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18311                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18312
18313         return result;
18314 }
18315
18316 template<class SpecResource>
18317 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18318 {
18319         const deUint32                  numDataPoints   = 16;
18320         const std::string               testName                ("sparse_ids");
18321         const deUint32                  seed                    (deStringHash(testName.c_str()));
18322         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18323         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18324         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18325         const StringTemplate    preMain
18326         (
18327                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18328                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18329                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18330                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18331                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18332                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18333                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18334                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18335         );
18336         const StringTemplate    decoration
18337         (
18338                 "OpDecorate %ra_u32 ArrayStride 4\n"
18339                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18340                 "OpDecorate %SSBO32 BufferBlock\n"
18341                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18342                 "OpDecorate %ssbo_src0 Binding 0\n"
18343                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18344                 "OpDecorate %ssbo_src1 Binding 1\n"
18345                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18346                 "OpDecorate %ssbo_dst Binding 2\n"
18347         );
18348         const StringTemplate    testFun
18349         (
18350                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18351                 "    %param = OpFunctionParameter %v4f32\n"
18352
18353                 "    %entry = OpLabel\n"
18354                 "        %i = OpVariable %fp_i32 Function\n"
18355                 "             OpStore %i %c_i32_0\n"
18356                 "             OpBranch %loop\n"
18357
18358                 "     %loop = OpLabel\n"
18359                 "    %i_cmp = OpLoad %i32 %i\n"
18360                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18361                 "             OpLoopMerge %merge %next None\n"
18362                 "             OpBranchConditional %lt %write %merge\n"
18363
18364                 "    %write = OpLabel\n"
18365                 "      %ndx = OpLoad %i32 %i\n"
18366
18367                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18368                 "      %128 = OpLoad %u32 %127\n"
18369
18370                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18371                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18372                 "  %4194001 = OpLoad %u32 %4194000\n"
18373
18374                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18375                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18376                 "             OpStore %2097152 %2097151\n"
18377                 "             OpBranch %next\n"
18378
18379                 "     %next = OpLabel\n"
18380                 "    %i_cur = OpLoad %i32 %i\n"
18381                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18382                 "             OpStore %i %i_new\n"
18383                 "             OpBranch %loop\n"
18384
18385                 "    %merge = OpLabel\n"
18386                 "             OpReturnValue %param\n"
18387
18388                 "             OpFunctionEnd\n"
18389         );
18390         SpecResource                    specResource;
18391         map<string, string>             specs;
18392         VulkanFeatures                  features;
18393         map<string, string>             fragments;
18394         vector<string>                  extensions;
18395
18396         specs["num_data_points"]        = de::toString(numDataPoints);
18397
18398         fragments["decoration"]         = decoration.specialize(specs);
18399         fragments["pre_main"]           = preMain.specialize(specs);
18400         fragments["testfun"]            = testFun.specialize(specs);
18401
18402         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18403         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18404         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18405
18406         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18407         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18408
18409         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18410 }
18411
18412 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18413 {
18414         vector<deUint32>        result;
18415         de::Random                      rnd             (seed);
18416
18417         result.reserve(numDataPoints);
18418
18419         // Fixed value
18420         result.push_back(1u);
18421
18422         // Random values
18423         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18424                 result.push_back(rnd.getUint8());
18425
18426         return result;
18427 }
18428
18429 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18430 {
18431         vector<deUint32>        result;
18432
18433         result.reserve(inData1.size());
18434
18435         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18436                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18437
18438         return result;
18439 }
18440
18441 template<class SpecResource>
18442 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18443 {
18444         const deUint32                  numDataPoints   = 16;
18445         const deUint32                  firstNdx                = 100u;
18446         const deUint32                  sequenceCount   = 10000u;
18447         const std::string               testName                ("lots_ids");
18448         const deUint32                  seed                    (deStringHash(testName.c_str()));
18449         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18450         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18451         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18452         const StringTemplate preMain
18453         (
18454                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18455                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18456                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18457                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18458                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18459                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18460                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18461                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18462         );
18463         const StringTemplate decoration
18464         (
18465                 "OpDecorate %ra_u32 ArrayStride 4\n"
18466                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18467                 "OpDecorate %SSBO32 BufferBlock\n"
18468                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18469                 "OpDecorate %ssbo_src0 Binding 0\n"
18470                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18471                 "OpDecorate %ssbo_src1 Binding 1\n"
18472                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18473                 "OpDecorate %ssbo_dst Binding 2\n"
18474         );
18475         const StringTemplate testFun
18476         (
18477                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18478                 "    %param = OpFunctionParameter %v4f32\n"
18479
18480                 "    %entry = OpLabel\n"
18481                 "        %i = OpVariable %fp_i32 Function\n"
18482                 "             OpStore %i %c_i32_0\n"
18483                 "             OpBranch %loop\n"
18484
18485                 "     %loop = OpLabel\n"
18486                 "    %i_cmp = OpLoad %i32 %i\n"
18487                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18488                 "             OpLoopMerge %merge %next None\n"
18489                 "             OpBranchConditional %lt %write %merge\n"
18490
18491                 "    %write = OpLabel\n"
18492                 "      %ndx = OpLoad %i32 %i\n"
18493
18494                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18495                 "       %91 = OpLoad %u32 %90\n"
18496
18497                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18498                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18499
18500                 "${seq}\n"
18501
18502                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18503                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18504                 "             OpStore %dst %${last_id}\n"
18505                 "             OpBranch %next\n"
18506
18507                 "     %next = OpLabel\n"
18508                 "    %i_cur = OpLoad %i32 %i\n"
18509                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18510                 "             OpStore %i %i_new\n"
18511                 "             OpBranch %loop\n"
18512
18513                 "    %merge = OpLabel\n"
18514                 "             OpReturnValue %param\n"
18515
18516                 "             OpFunctionEnd\n"
18517         );
18518         deUint32                                lastId                  = firstNdx;
18519         SpecResource                    specResource;
18520         map<string, string>             specs;
18521         VulkanFeatures                  features;
18522         map<string, string>             fragments;
18523         vector<string>                  extensions;
18524         std::string                             sequence;
18525
18526         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18527         {
18528                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18529                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18530
18531                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18532                 lastId = sequenceId;
18533
18534                 if (sequenceNdx == 0)
18535                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18536         }
18537
18538         specs["num_data_points"]        = de::toString(numDataPoints);
18539         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18540         specs["last_id"]                        = de::toString(lastId);
18541         specs["seq"]                            = sequence;
18542
18543         fragments["decoration"]         = decoration.specialize(specs);
18544         fragments["pre_main"]           = preMain.specialize(specs);
18545         fragments["testfun"]            = testFun.specialize(specs);
18546
18547         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18548         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18549         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18550
18551         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18552         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18553
18554         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18555 }
18556
18557 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18558 {
18559         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18560
18561         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18562         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18563
18564         return testGroup.release();
18565 }
18566
18567 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18568 {
18569         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18570
18571         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18572         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18573
18574         return testGroup.release();
18575 }
18576
18577 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18578 {
18579         const bool testComputePipeline = true;
18580
18581         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18582         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18583         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18584
18585         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18586         computeTests->addChild(createLocalSizeGroup(testCtx));
18587         computeTests->addChild(createOpNopGroup(testCtx));
18588         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18589         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18590         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18591         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18592         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18593         computeTests->addChild(createOpLineGroup(testCtx));
18594         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18595         computeTests->addChild(createOpNoLineGroup(testCtx));
18596         computeTests->addChild(createOpConstantNullGroup(testCtx));
18597         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18598         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18599         computeTests->addChild(createSpecConstantGroup(testCtx));
18600         computeTests->addChild(createOpSourceGroup(testCtx));
18601         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18602         computeTests->addChild(createDecorationGroupGroup(testCtx));
18603         computeTests->addChild(createOpPhiGroup(testCtx));
18604         computeTests->addChild(createLoopControlGroup(testCtx));
18605         computeTests->addChild(createFunctionControlGroup(testCtx));
18606         computeTests->addChild(createSelectionControlGroup(testCtx));
18607         computeTests->addChild(createBlockOrderGroup(testCtx));
18608         computeTests->addChild(createMultipleShaderGroup(testCtx));
18609         computeTests->addChild(createMemoryAccessGroup(testCtx));
18610         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18611         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18612         computeTests->addChild(createNoContractionGroup(testCtx));
18613         computeTests->addChild(createOpUndefGroup(testCtx));
18614         computeTests->addChild(createOpUnreachableGroup(testCtx));
18615         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18616         computeTests->addChild(createOpFRemGroup(testCtx));
18617         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18618         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18619         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18620         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18621         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18622         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18623         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18624         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18625         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18626         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18627         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18628         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18629         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18630         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18631         computeTests->addChild(createOpNMinGroup(testCtx));
18632         computeTests->addChild(createOpNMaxGroup(testCtx));
18633         computeTests->addChild(createOpNClampGroup(testCtx));
18634         {
18635                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18636
18637                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18638                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18639
18640                 computeTests->addChild(computeAndroidTests.release());
18641         }
18642
18643         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18644         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18645         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18646         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18647         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18648         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18649         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18650         computeTests->addChild(createIndexingComputeGroup(testCtx));
18651         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18652         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18653         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18654         computeTests->addChild(createOpNameGroup(testCtx));
18655         computeTests->addChild(createOpMemberNameGroup(testCtx));
18656         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18657         computeTests->addChild(createFloat16Group(testCtx));
18658         computeTests->addChild(createBoolGroup(testCtx));
18659         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18660         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18661         computeTests->addChild(createSignedIntCompareGroup(testCtx));
18662         computeTests->addChild(createUnusedVariableComputeTests(testCtx));
18663         computeTests->addChild(createPtrAccessChainGroup(testCtx));
18664
18665         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18666         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18667         graphicsTests->addChild(createOpNopTests(testCtx));
18668         graphicsTests->addChild(createOpSourceTests(testCtx));
18669         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18670         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18671         graphicsTests->addChild(createOpLineTests(testCtx));
18672         graphicsTests->addChild(createOpNoLineTests(testCtx));
18673         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18674         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18675         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18676         graphicsTests->addChild(createOpUndefTests(testCtx));
18677         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18678         graphicsTests->addChild(createModuleTests(testCtx));
18679         graphicsTests->addChild(createUnusedVariableTests(testCtx));
18680         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18681         graphicsTests->addChild(createOpPhiTests(testCtx));
18682         graphicsTests->addChild(createNoContractionTests(testCtx));
18683         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18684         graphicsTests->addChild(createLoopTests(testCtx));
18685         graphicsTests->addChild(createSpecConstantTests(testCtx));
18686         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18687         graphicsTests->addChild(createBarrierTests(testCtx));
18688         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18689         graphicsTests->addChild(createFRemTests(testCtx));
18690         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18691         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18692
18693         {
18694                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18695
18696                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18697                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18698
18699                 graphicsTests->addChild(graphicsAndroidTests.release());
18700         }
18701         graphicsTests->addChild(createOpNameTests(testCtx));
18702         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18703         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18704
18705         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18706         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18707         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18708         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18709         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18710         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18711         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18712         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18713         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18714         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18715         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18716         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18717         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18718         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18719         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18720         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18721         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18722         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18723         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18724         graphicsTests->addChild(createFloat16Tests(testCtx));
18725         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18726
18727         instructionTests->addChild(computeTests.release());
18728         instructionTests->addChild(graphicsTests.release());
18729
18730         return instructionTests.release();
18731 }
18732
18733 } // SpirVAssembly
18734 } // vkt