Reduce long execution time in spirv_asm float16
[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
76 #include <cmath>
77 #include <limits>
78 #include <map>
79 #include <string>
80 #include <sstream>
81 #include <utility>
82 #include <stack>
83
84 namespace vkt
85 {
86 namespace SpirVAssembly
87 {
88
89 namespace
90 {
91
92 using namespace vk;
93 using std::map;
94 using std::string;
95 using std::vector;
96 using tcu::IVec3;
97 using tcu::IVec4;
98 using tcu::RGBA;
99 using tcu::TestLog;
100 using tcu::TestStatus;
101 using tcu::Vec4;
102 using de::UniquePtr;
103 using tcu::StringTemplate;
104 using tcu::Vec4;
105
106 const bool TEST_WITH_NAN        = true;
107 const bool TEST_WITHOUT_NAN     = false;
108
109 template<typename T>
110 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
111 {
112         T* const typedPtr = (T*)dst;
113         for (int ndx = 0; ndx < numValues; ndx++)
114                 typedPtr[offset + ndx] = de::randomScalar<T>(rnd, minValue, maxValue);
115 }
116
117 // Filter is a function that returns true if a value should pass, false otherwise.
118 template<typename T, typename FilterT>
119 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
120 {
121         T* const typedPtr = (T*)dst;
122         T value;
123         for (int ndx = 0; ndx < numValues; ndx++)
124         {
125                 do
126                         value = de::randomScalar<T>(rnd, minValue, maxValue);
127                 while (!filter(value));
128
129                 typedPtr[offset + ndx] = value;
130         }
131 }
132
133 // Gets a 64-bit integer with a more logarithmic distribution
134 deInt64 randomInt64LogDistributed (de::Random& rnd)
135 {
136         deInt64 val = rnd.getUint64();
137         val &= (1ull << rnd.getInt(1, 63)) - 1;
138         if (rnd.getBool())
139                 val = -val;
140         return val;
141 }
142
143 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
144 {
145         for (int ndx = 0; ndx < numValues; ndx++)
146                 dst[ndx] = randomInt64LogDistributed(rnd);
147 }
148
149 template<typename FilterT>
150 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
151 {
152         for (int ndx = 0; ndx < numValues; ndx++)
153         {
154                 deInt64 value;
155                 do {
156                         value = randomInt64LogDistributed(rnd);
157                 } while (!filter(value));
158                 dst[ndx] = value;
159         }
160 }
161
162 inline bool filterNonNegative (const deInt64 value)
163 {
164         return value >= 0;
165 }
166
167 inline bool filterPositive (const deInt64 value)
168 {
169         return value > 0;
170 }
171
172 inline bool filterNotZero (const deInt64 value)
173 {
174         return value != 0;
175 }
176
177 static void floorAll (vector<float>& values)
178 {
179         for (size_t i = 0; i < values.size(); i++)
180                 values[i] = deFloatFloor(values[i]);
181 }
182
183 static void floorAll (vector<Vec4>& values)
184 {
185         for (size_t i = 0; i < values.size(); i++)
186                 values[i] = floor(values[i]);
187 }
188
189 struct CaseParameter
190 {
191         const char*             name;
192         string                  param;
193
194         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
195 };
196
197 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
198 //
199 // #version 430
200 //
201 // layout(std140, set = 0, binding = 0) readonly buffer Input {
202 //   float elements[];
203 // } input_data;
204 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
205 //   float elements[];
206 // } output_data;
207 //
208 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
209 //
210 // void main() {
211 //   uint x = gl_GlobalInvocationID.x;
212 //   output_data.elements[x] = -input_data.elements[x];
213 // }
214
215 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
216 {
217         std::ostringstream out;
218         out << getComputeAsmShaderPreambleWithoutLocalSize();
219
220         if (useLiteralLocalSize)
221         {
222                 out << "OpExecutionMode %main LocalSize "
223                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
224         }
225
226         out << "OpSource GLSL 430\n"
227                 "OpName %main           \"main\"\n"
228                 "OpName %id             \"gl_GlobalInvocationID\"\n"
229                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
230
231         if (useSpecConstantWorkgroupSize)
232         {
233                 out << "OpDecorate %spec_0 SpecId 100\n"
234                         << "OpDecorate %spec_1 SpecId 101\n"
235                         << "OpDecorate %spec_2 SpecId 102\n"
236                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
237         }
238
239         out << getComputeAsmInputOutputBufferTraits()
240                 << getComputeAsmCommonTypes()
241                 << getComputeAsmInputOutputBuffer()
242                 << "%id        = OpVariable %uvec3ptr Input\n"
243                 << "%zero      = OpConstant %i32 0 \n";
244
245         if (useSpecConstantWorkgroupSize)
246         {
247                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
248                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
249                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
250                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
251         }
252
253         out << "%main      = OpFunction %void None %voidf\n"
254                 << "%label     = OpLabel\n"
255                 << "%idval     = OpLoad %uvec3 %id\n"
256                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
257
258                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
259                         "%inval     = OpLoad %f32 %inloc\n"
260                         "%neg       = OpFNegate %f32 %inval\n"
261                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
262                         "             OpStore %outloc %neg\n"
263                         "             OpReturn\n"
264                         "             OpFunctionEnd\n";
265         return out.str();
266 }
267
268 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
269 {
270         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
271         ComputeShaderSpec                               spec;
272         de::Random                                              rnd                             (deStringHash(group->getName()));
273         const deUint32                                  numElements             = 64u;
274         vector<float>                                   positiveFloats  (numElements, 0);
275         vector<float>                                   negativeFloats  (numElements, 0);
276
277         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
278
279         for (size_t ndx = 0; ndx < numElements; ++ndx)
280                 negativeFloats[ndx] = -positiveFloats[ndx];
281
282         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
283         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
284
285         spec.numWorkGroups = IVec3(numElements, 1, 1);
286
287         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
288         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
289
290         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
291         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
292
293         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
294         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
295
296         spec.numWorkGroups = IVec3(1, 1, 1);
297
298         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
299         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
300
301         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
303
304         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
305         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
306
307         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
308         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
309
310         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
311         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
312
313         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
314         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
315
316         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
317         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
318
319         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
320         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
321
322         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
323         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
324
325         return group.release();
326 }
327
328 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
329 {
330         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
331         ComputeShaderSpec                               spec;
332         de::Random                                              rnd                             (deStringHash(group->getName()));
333         const int                                               numElements             = 100;
334         vector<float>                                   positiveFloats  (numElements, 0);
335         vector<float>                                   negativeFloats  (numElements, 0);
336
337         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
338
339         for (size_t ndx = 0; ndx < numElements; ++ndx)
340                 negativeFloats[ndx] = -positiveFloats[ndx];
341
342         spec.assembly =
343                 string(getComputeAsmShaderPreamble()) +
344
345                 "OpSource GLSL 430\n"
346                 "OpName %main           \"main\"\n"
347                 "OpName %id             \"gl_GlobalInvocationID\"\n"
348
349                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
350
351                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
352
353                 + string(getComputeAsmInputOutputBuffer()) +
354
355                 "%id        = OpVariable %uvec3ptr Input\n"
356                 "%zero      = OpConstant %i32 0\n"
357
358                 "%main      = OpFunction %void None %voidf\n"
359                 "%label     = OpLabel\n"
360                 "%idval     = OpLoad %uvec3 %id\n"
361                 "%x         = OpCompositeExtract %u32 %idval 0\n"
362
363                 "             OpNop\n" // Inside a function body
364
365                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
366                 "%inval     = OpLoad %f32 %inloc\n"
367                 "%neg       = OpFNegate %f32 %inval\n"
368                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
369                 "             OpStore %outloc %neg\n"
370                 "             OpReturn\n"
371                 "             OpFunctionEnd\n";
372         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
373         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
374         spec.numWorkGroups = IVec3(numElements, 1, 1);
375
376         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
377
378         return group.release();
379 }
380
381 template<bool nanSupported>
382 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
383 {
384         if (outputAllocs.size() != 1)
385                 return false;
386
387         vector<deUint8> input1Bytes;
388         vector<deUint8> input2Bytes;
389         vector<deUint8> expectedBytes;
390
391         inputs[0].getBytes(input1Bytes);
392         inputs[1].getBytes(input2Bytes);
393         expectedOutputs[0].getBytes(expectedBytes);
394
395         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
396         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
397         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
398         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
399         bool returnValue                                                                = true;
400
401         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
402         {
403                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
404                         continue;
405
406                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
407                 {
408                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
409                         returnValue = false;
410                 }
411         }
412         return returnValue;
413 }
414
415 typedef VkBool32 (*compareFuncType) (float, float);
416
417 struct OpFUnordCase
418 {
419         const char*             name;
420         const char*             opCode;
421         compareFuncType compareFunc;
422
423                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
424                                                 : name                          (_name)
425                                                 , opCode                        (_opCode)
426                                                 , compareFunc           (_compareFunc) {}
427 };
428
429 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
430 do { \
431         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
432         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
433 } while (deGetFalse())
434
435 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool nanSupported)
436 {
437         const string                                    nan                             = nanSupported ? "_nan" : "";
438         const string                                    groupName               = "opfunord" + nan;
439         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
440         de::Random                                              rnd                             (deStringHash(group->getName()));
441         const int                                               numElements             = 100;
442         vector<OpFUnordCase>                    cases;
443         string                                                  extensions              = nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
444         string                                                  capabilities    = nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "";
445         string                          exeModes        = nanSupported ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
446         const StringTemplate                    shaderTemplate  (
447                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
448                 "OpSource GLSL 430\n"
449                 "OpName %main           \"main\"\n"
450                 "OpName %id             \"gl_GlobalInvocationID\"\n"
451
452                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
453
454                 "OpDecorate %buf BufferBlock\n"
455                 "OpDecorate %buf2 BufferBlock\n"
456                 "OpDecorate %indata1 DescriptorSet 0\n"
457                 "OpDecorate %indata1 Binding 0\n"
458                 "OpDecorate %indata2 DescriptorSet 0\n"
459                 "OpDecorate %indata2 Binding 1\n"
460                 "OpDecorate %outdata DescriptorSet 0\n"
461                 "OpDecorate %outdata Binding 2\n"
462                 "OpDecorate %f32arr ArrayStride 4\n"
463                 "OpDecorate %i32arr ArrayStride 4\n"
464                 "OpMemberDecorate %buf 0 Offset 0\n"
465                 "OpMemberDecorate %buf2 0 Offset 0\n"
466
467                 + string(getComputeAsmCommonTypes()) +
468
469                 "%buf        = OpTypeStruct %f32arr\n"
470                 "%bufptr     = OpTypePointer Uniform %buf\n"
471                 "%indata1    = OpVariable %bufptr Uniform\n"
472                 "%indata2    = OpVariable %bufptr Uniform\n"
473
474                 "%buf2       = OpTypeStruct %i32arr\n"
475                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
476                 "%outdata    = OpVariable %buf2ptr Uniform\n"
477
478                 "%id        = OpVariable %uvec3ptr Input\n"
479                 "%zero      = OpConstant %i32 0\n"
480                 "%consti1   = OpConstant %i32 1\n"
481                 "%constf1   = OpConstant %f32 1.0\n"
482
483                 "%main      = OpFunction %void None %voidf\n"
484                 "%label     = OpLabel\n"
485                 "%idval     = OpLoad %uvec3 %id\n"
486                 "%x         = OpCompositeExtract %u32 %idval 0\n"
487
488                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
489                 "%inval1    = OpLoad %f32 %inloc1\n"
490                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
491                 "%inval2    = OpLoad %f32 %inloc2\n"
492                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
493
494                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
495                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
496                 "             OpStore %outloc %int_res\n"
497
498                 "             OpReturn\n"
499                 "             OpFunctionEnd\n");
500
501         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
502         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
503         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
504         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
505         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
506         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
507
508         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
509         {
510                 map<string, string>                     specializations;
511                 ComputeShaderSpec                       spec;
512                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
513                 vector<float>                           inputFloats1    (numElements, 0);
514                 vector<float>                           inputFloats2    (numElements, 0);
515                 vector<deInt32>                         expectedInts    (numElements, 0);
516
517                 specializations["OPCODE"]       = cases[caseNdx].opCode;
518                 spec.assembly                           = shaderTemplate.specialize(specializations);
519
520                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
521                 for (size_t ndx = 0; ndx < numElements; ++ndx)
522                 {
523                         switch (ndx % 6)
524                         {
525                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
526                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
527                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
528                                 case 3:         inputFloats2[ndx] = NaN; break;
529                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
530                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
531                         }
532                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
533                 }
534
535                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
536                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
537                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
538                 spec.numWorkGroups = IVec3(numElements, 1, 1);
539                 spec.verifyIO = nanSupported ? &compareFUnord<true> : &compareFUnord<false>;
540                 if (nanSupported)
541                 {
542                         spec.extensions.push_back("VK_KHR_shader_float_controls");
543                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
544                 }
545                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
546         }
547
548         return group.release();
549 }
550
551 struct OpAtomicCase
552 {
553         const char*             name;
554         const char*             assembly;
555         const char*             retValAssembly;
556         OpAtomicType    opAtomic;
557         deInt32                 numOutputElements;
558
559                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
560                                                 : name                          (_name)
561                                                 , assembly                      (_assembly)
562                                                 , retValAssembly        (_retValAssembly)
563                                                 , opAtomic                      (_opAtomic)
564                                                 , numOutputElements     (_numOutputElements) {}
565 };
566
567 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
568 {
569         std::string                                             groupName                       ("opatomic");
570         if (useStorageBuffer)
571                 groupName += "_storage_buffer";
572         if (verifyReturnValues)
573                 groupName += "_return_values";
574         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
575         vector<OpAtomicCase>                    cases;
576
577         const StringTemplate                    shaderTemplate  (
578
579                 string("OpCapability Shader\n") +
580                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
581                 "OpMemoryModel Logical GLSL450\n"
582                 "OpEntryPoint GLCompute %main \"main\" %id\n"
583                 "OpExecutionMode %main LocalSize 1 1 1\n" +
584
585                 "OpSource GLSL 430\n"
586                 "OpName %main           \"main\"\n"
587                 "OpName %id             \"gl_GlobalInvocationID\"\n"
588
589                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
590
591                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
592                 "OpDecorate %indata DescriptorSet 0\n"
593                 "OpDecorate %indata Binding 0\n"
594                 "OpDecorate %i32arr ArrayStride 4\n"
595                 "OpMemberDecorate %buf 0 Offset 0\n"
596
597                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
598                 "OpDecorate %sum DescriptorSet 0\n"
599                 "OpDecorate %sum Binding 1\n"
600                 "OpMemberDecorate %sumbuf 0 Coherent\n"
601                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
602
603                 "${RETVAL_BUF_DECORATE}"
604
605                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
606
607                 "%buf       = OpTypeStruct %i32arr\n"
608                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
609                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
610
611                 "%sumbuf    = OpTypeStruct %i32arr\n"
612                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
613                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
614
615                 "${RETVAL_BUF_DECL}"
616
617                 "%id        = OpVariable %uvec3ptr Input\n"
618                 "%minusone  = OpConstant %i32 -1\n"
619                 "%zero      = OpConstant %i32 0\n"
620                 "%one       = OpConstant %u32 1\n"
621                 "%two       = OpConstant %i32 2\n"
622
623                 "%main      = OpFunction %void None %voidf\n"
624                 "%label     = OpLabel\n"
625                 "%idval     = OpLoad %uvec3 %id\n"
626                 "%x         = OpCompositeExtract %u32 %idval 0\n"
627
628                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
629                 "%inval     = OpLoad %i32 %inloc\n"
630
631                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
632                 "${INSTRUCTION}"
633                 "${RETVAL_ASSEMBLY}"
634
635                 "             OpReturn\n"
636                 "             OpFunctionEnd\n");
637
638         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
639         do { \
640                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
641                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
642         } while (deGetFalse())
643         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
644         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
645
646         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
647                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
648         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
649                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
650         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
651                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
652         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
653                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
654         if (!verifyReturnValues)
655         {
656                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
657                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
658                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
659         }
660
661         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
662                                                                 "             OpStore %outloc %even\n"
663                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
664                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
665
666
667         #undef ADD_OPATOMIC_CASE
668         #undef ADD_OPATOMIC_CASE_1
669         #undef ADD_OPATOMIC_CASE_N
670
671         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
672         {
673                 map<string, string>                     specializations;
674                 ComputeShaderSpec                       spec;
675                 vector<deInt32>                         inputInts               (numElements, 0);
676                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
677
678                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
679                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
680                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
681                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
682
683                 if (verifyReturnValues)
684                 {
685                         const StringTemplate blockDecoration    (
686                                 "\n"
687                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
688                                 "OpDecorate %ret DescriptorSet 0\n"
689                                 "OpDecorate %ret Binding 2\n"
690                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
691
692                         const StringTemplate blockDeclaration   (
693                                 "\n"
694                                 "%retbuf    = OpTypeStruct %i32arr\n"
695                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
696                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
697
698                         specializations["RETVAL_ASSEMBLY"] =
699                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
700                                 + std::string(cases[caseNdx].retValAssembly);
701
702                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
703                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
704                 }
705                 else
706                 {
707                         specializations["RETVAL_ASSEMBLY"]              = "";
708                         specializations["RETVAL_BUF_DECORATE"]  = "";
709                         specializations["RETVAL_BUF_DECL"]              = "";
710                 }
711
712                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
713
714                 if (useStorageBuffer)
715                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
716
717                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
718                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
719                 if (verifyReturnValues)
720                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
721                 spec.numWorkGroups = IVec3(numElements, 1, 1);
722
723                 if (verifyReturnValues)
724                 {
725                         switch (cases[caseNdx].opAtomic)
726                         {
727                                 case OPATOMIC_IADD:
728                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
729                                         break;
730                                 case OPATOMIC_ISUB:
731                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
732                                         break;
733                                 case OPATOMIC_IINC:
734                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
735                                         break;
736                                 case OPATOMIC_IDEC:
737                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
738                                         break;
739                                 case OPATOMIC_COMPEX:
740                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
741                                         break;
742                                 default:
743                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
744                         }
745                 }
746                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
747         }
748
749         return group.release();
750 }
751
752 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
753 {
754         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
755         ComputeShaderSpec                               spec;
756         de::Random                                              rnd                             (deStringHash(group->getName()));
757         const int                                               numElements             = 100;
758         vector<float>                                   positiveFloats  (numElements, 0);
759         vector<float>                                   negativeFloats  (numElements, 0);
760
761         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
762
763         for (size_t ndx = 0; ndx < numElements; ++ndx)
764                 negativeFloats[ndx] = -positiveFloats[ndx];
765
766         spec.assembly =
767                 string(getComputeAsmShaderPreamble()) +
768
769                 "%fname1 = OpString \"negateInputs.comp\"\n"
770                 "%fname2 = OpString \"negateInputs\"\n"
771
772                 "OpSource GLSL 430\n"
773                 "OpName %main           \"main\"\n"
774                 "OpName %id             \"gl_GlobalInvocationID\"\n"
775
776                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
777
778                 + string(getComputeAsmInputOutputBufferTraits()) +
779
780                 "OpLine %fname1 0 0\n" // At the earliest possible position
781
782                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
783
784                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
785                 "OpLine %fname2 1 0\n" // Different filenames
786                 "OpLine %fname1 1000 100000\n"
787
788                 "%id        = OpVariable %uvec3ptr Input\n"
789                 "%zero      = OpConstant %i32 0\n"
790
791                 "OpLine %fname1 1 1\n" // Before a function
792
793                 "%main      = OpFunction %void None %voidf\n"
794                 "%label     = OpLabel\n"
795
796                 "OpLine %fname1 1 1\n" // In a function
797
798                 "%idval     = OpLoad %uvec3 %id\n"
799                 "%x         = OpCompositeExtract %u32 %idval 0\n"
800                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
801                 "%inval     = OpLoad %f32 %inloc\n"
802                 "%neg       = OpFNegate %f32 %inval\n"
803                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
804                 "             OpStore %outloc %neg\n"
805                 "             OpReturn\n"
806                 "             OpFunctionEnd\n";
807         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
808         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
809         spec.numWorkGroups = IVec3(numElements, 1, 1);
810
811         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
812
813         return group.release();
814 }
815
816 bool veryfiBinaryShader (const ProgramBinary& binary)
817 {
818         const size_t    paternCount                     = 3u;
819         bool paternsCheck[paternCount]          =
820         {
821                 false, false, false
822         };
823         const string patersns[paternCount]      =
824         {
825                 "VULKAN CTS",
826                 "Negative values",
827                 "Date: 2017/09/21"
828         };
829         size_t                  paternNdx               = 0u;
830
831         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
832         {
833                 if (false == paternsCheck[paternNdx] &&
834                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
835                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
836                 {
837                         paternsCheck[paternNdx]= true;
838                         paternNdx++;
839                         if (paternNdx == paternCount)
840                                 break;
841                 }
842         }
843
844         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
845         {
846                 if (!paternsCheck[ndx])
847                         return false;
848         }
849
850         return true;
851 }
852
853 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
854 {
855         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
856         ComputeShaderSpec                               spec;
857         de::Random                                              rnd                             (deStringHash(group->getName()));
858         const int                                               numElements             = 10;
859         vector<float>                                   positiveFloats  (numElements, 0);
860         vector<float>                                   negativeFloats  (numElements, 0);
861
862         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
863
864         for (size_t ndx = 0; ndx < numElements; ++ndx)
865                 negativeFloats[ndx] = -positiveFloats[ndx];
866
867         spec.assembly =
868                 string(getComputeAsmShaderPreamble()) +
869                 "%fname = OpString \"negateInputs.comp\"\n"
870
871                 "OpSource GLSL 430\n"
872                 "OpName %main           \"main\"\n"
873                 "OpName %id             \"gl_GlobalInvocationID\"\n"
874                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
875                 "OpModuleProcessed \"Negative values\"\n"
876                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
877                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
878
879                 + string(getComputeAsmInputOutputBufferTraits())
880
881                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
882
883                 "OpLine %fname 0 1\n"
884
885                 "OpLine %fname 1000 1\n"
886
887                 "%id        = OpVariable %uvec3ptr Input\n"
888                 "%zero      = OpConstant %i32 0\n"
889                 "%main      = OpFunction %void None %voidf\n"
890
891                 "%label     = OpLabel\n"
892                 "%idval     = OpLoad %uvec3 %id\n"
893                 "%x         = OpCompositeExtract %u32 %idval 0\n"
894
895                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
896                 "%inval     = OpLoad %f32 %inloc\n"
897                 "%neg       = OpFNegate %f32 %inval\n"
898                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
899                 "             OpStore %outloc %neg\n"
900                 "             OpReturn\n"
901                 "             OpFunctionEnd\n";
902         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
903         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
904         spec.numWorkGroups = IVec3(numElements, 1, 1);
905         spec.verifyBinary = veryfiBinaryShader;
906         spec.spirvVersion = SPIRV_VERSION_1_3;
907
908         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
909
910         return group.release();
911 }
912
913 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
914 {
915         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
916         ComputeShaderSpec                               spec;
917         de::Random                                              rnd                             (deStringHash(group->getName()));
918         const int                                               numElements             = 100;
919         vector<float>                                   positiveFloats  (numElements, 0);
920         vector<float>                                   negativeFloats  (numElements, 0);
921
922         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
923
924         for (size_t ndx = 0; ndx < numElements; ++ndx)
925                 negativeFloats[ndx] = -positiveFloats[ndx];
926
927         spec.assembly =
928                 string(getComputeAsmShaderPreamble()) +
929
930                 "%fname = OpString \"negateInputs.comp\"\n"
931
932                 "OpSource GLSL 430\n"
933                 "OpName %main           \"main\"\n"
934                 "OpName %id             \"gl_GlobalInvocationID\"\n"
935
936                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
937
938                 + string(getComputeAsmInputOutputBufferTraits()) +
939
940                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
941
942                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
943
944                 "OpLine %fname 0 1\n"
945                 "OpNoLine\n" // Immediately following a preceding OpLine
946
947                 "OpLine %fname 1000 1\n"
948
949                 "%id        = OpVariable %uvec3ptr Input\n"
950                 "%zero      = OpConstant %i32 0\n"
951
952                 "OpNoLine\n" // Contents after the previous OpLine
953
954                 "%main      = OpFunction %void None %voidf\n"
955                 "%label     = OpLabel\n"
956                 "%idval     = OpLoad %uvec3 %id\n"
957                 "%x         = OpCompositeExtract %u32 %idval 0\n"
958
959                 "OpNoLine\n" // Multiple OpNoLine
960                 "OpNoLine\n"
961                 "OpNoLine\n"
962
963                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
964                 "%inval     = OpLoad %f32 %inloc\n"
965                 "%neg       = OpFNegate %f32 %inval\n"
966                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
967                 "             OpStore %outloc %neg\n"
968                 "             OpReturn\n"
969                 "             OpFunctionEnd\n";
970         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
971         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
972         spec.numWorkGroups = IVec3(numElements, 1, 1);
973
974         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
975
976         return group.release();
977 }
978
979 // Compare instruction for the contraction compute case.
980 // Returns true if the output is what is expected from the test case.
981 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
982 {
983         if (outputAllocs.size() != 1)
984                 return false;
985
986         // Only size is needed because we are not comparing the exact values.
987         size_t byteSize = expectedOutputs[0].getByteSize();
988
989         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
990
991         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
992                 if (outputAsFloat[i] != 0.f &&
993                         outputAsFloat[i] != -ldexp(1, -24)) {
994                         return false;
995                 }
996         }
997
998         return true;
999 }
1000
1001 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1002 {
1003         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1004         vector<CaseParameter>                   cases;
1005         const int                                               numElements             = 100;
1006         vector<float>                                   inputFloats1    (numElements, 0);
1007         vector<float>                                   inputFloats2    (numElements, 0);
1008         vector<float>                                   outputFloats    (numElements, 0);
1009         const StringTemplate                    shaderTemplate  (
1010                 string(getComputeAsmShaderPreamble()) +
1011
1012                 "OpName %main           \"main\"\n"
1013                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1014
1015                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1016
1017                 "${DECORATION}\n"
1018
1019                 "OpDecorate %buf BufferBlock\n"
1020                 "OpDecorate %indata1 DescriptorSet 0\n"
1021                 "OpDecorate %indata1 Binding 0\n"
1022                 "OpDecorate %indata2 DescriptorSet 0\n"
1023                 "OpDecorate %indata2 Binding 1\n"
1024                 "OpDecorate %outdata DescriptorSet 0\n"
1025                 "OpDecorate %outdata Binding 2\n"
1026                 "OpDecorate %f32arr ArrayStride 4\n"
1027                 "OpMemberDecorate %buf 0 Offset 0\n"
1028
1029                 + string(getComputeAsmCommonTypes()) +
1030
1031                 "%buf        = OpTypeStruct %f32arr\n"
1032                 "%bufptr     = OpTypePointer Uniform %buf\n"
1033                 "%indata1    = OpVariable %bufptr Uniform\n"
1034                 "%indata2    = OpVariable %bufptr Uniform\n"
1035                 "%outdata    = OpVariable %bufptr Uniform\n"
1036
1037                 "%id         = OpVariable %uvec3ptr Input\n"
1038                 "%zero       = OpConstant %i32 0\n"
1039                 "%c_f_m1     = OpConstant %f32 -1.\n"
1040
1041                 "%main       = OpFunction %void None %voidf\n"
1042                 "%label      = OpLabel\n"
1043                 "%idval      = OpLoad %uvec3 %id\n"
1044                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1045                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1046                 "%inval1     = OpLoad %f32 %inloc1\n"
1047                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1048                 "%inval2     = OpLoad %f32 %inloc2\n"
1049                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1050                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1051                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1052                 "              OpStore %outloc %add\n"
1053                 "              OpReturn\n"
1054                 "              OpFunctionEnd\n");
1055
1056         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1057         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1058         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1059
1060         for (size_t ndx = 0; ndx < numElements; ++ndx)
1061         {
1062                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1063                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1064                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1065                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1066                 // So the final result will be 0.f or 0x1p-24.
1067                 // If the operation is combined into a precise fused multiply-add, then the result would be
1068                 // 2^-46 (0xa8800000).
1069                 outputFloats[ndx]       = 0.f;
1070         }
1071
1072         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1073         {
1074                 map<string, string>             specializations;
1075                 ComputeShaderSpec               spec;
1076
1077                 specializations["DECORATION"] = cases[caseNdx].param;
1078                 spec.assembly = shaderTemplate.specialize(specializations);
1079                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1080                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1081                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1082                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1083                 // Check against the two possible answers based on rounding mode.
1084                 spec.verifyIO = &compareNoContractCase;
1085
1086                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1087         }
1088         return group.release();
1089 }
1090
1091 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1092 {
1093         if (outputAllocs.size() != 1)
1094                 return false;
1095
1096         vector<deUint8> expectedBytes;
1097         expectedOutputs[0].getBytes(expectedBytes);
1098
1099         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1100         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1101
1102         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1103         {
1104                 const float f0 = expectedOutputAsFloat[idx];
1105                 const float f1 = outputAsFloat[idx];
1106                 // \todo relative error needs to be fairly high because FRem may be implemented as
1107                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1108                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1109                         return false;
1110         }
1111
1112         return true;
1113 }
1114
1115 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1116 {
1117         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1118         ComputeShaderSpec                               spec;
1119         de::Random                                              rnd                             (deStringHash(group->getName()));
1120         const int                                               numElements             = 200;
1121         vector<float>                                   inputFloats1    (numElements, 0);
1122         vector<float>                                   inputFloats2    (numElements, 0);
1123         vector<float>                                   outputFloats    (numElements, 0);
1124
1125         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1126         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1127
1128         for (size_t ndx = 0; ndx < numElements; ++ndx)
1129         {
1130                 // Guard against divisors near zero.
1131                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1132                         inputFloats2[ndx] = 8.f;
1133
1134                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1135                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1136         }
1137
1138         spec.assembly =
1139                 string(getComputeAsmShaderPreamble()) +
1140
1141                 "OpName %main           \"main\"\n"
1142                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1143
1144                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1145
1146                 "OpDecorate %buf BufferBlock\n"
1147                 "OpDecorate %indata1 DescriptorSet 0\n"
1148                 "OpDecorate %indata1 Binding 0\n"
1149                 "OpDecorate %indata2 DescriptorSet 0\n"
1150                 "OpDecorate %indata2 Binding 1\n"
1151                 "OpDecorate %outdata DescriptorSet 0\n"
1152                 "OpDecorate %outdata Binding 2\n"
1153                 "OpDecorate %f32arr ArrayStride 4\n"
1154                 "OpMemberDecorate %buf 0 Offset 0\n"
1155
1156                 + string(getComputeAsmCommonTypes()) +
1157
1158                 "%buf        = OpTypeStruct %f32arr\n"
1159                 "%bufptr     = OpTypePointer Uniform %buf\n"
1160                 "%indata1    = OpVariable %bufptr Uniform\n"
1161                 "%indata2    = OpVariable %bufptr Uniform\n"
1162                 "%outdata    = OpVariable %bufptr Uniform\n"
1163
1164                 "%id        = OpVariable %uvec3ptr Input\n"
1165                 "%zero      = OpConstant %i32 0\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                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1176                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1177                 "             OpStore %outloc %rem\n"
1178                 "             OpReturn\n"
1179                 "             OpFunctionEnd\n";
1180
1181         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1182         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1183         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1184         spec.numWorkGroups = IVec3(numElements, 1, 1);
1185         spec.verifyIO = &compareFRem;
1186
1187         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1188
1189         return group.release();
1190 }
1191
1192 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1193 {
1194         if (outputAllocs.size() != 1)
1195                 return false;
1196
1197         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1198         std::vector<deUint8>    data;
1199         expectedOutput->getBytes(data);
1200
1201         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1202         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1203
1204         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1205         {
1206                 const float f0 = expectedOutputAsFloat[idx];
1207                 const float f1 = outputAsFloat[idx];
1208
1209                 // For NMin, we accept NaN as output if both inputs were NaN.
1210                 // Otherwise the NaN is the wrong choise, as on architectures that
1211                 // do not handle NaN, those are huge values.
1212                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1213                         return false;
1214         }
1215
1216         return true;
1217 }
1218
1219 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1220 {
1221         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1222         ComputeShaderSpec                               spec;
1223         de::Random                                              rnd                             (deStringHash(group->getName()));
1224         const int                                               numElements             = 200;
1225         vector<float>                                   inputFloats1    (numElements, 0);
1226         vector<float>                                   inputFloats2    (numElements, 0);
1227         vector<float>                                   outputFloats    (numElements, 0);
1228
1229         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1230         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1231
1232         // Make the first case a full-NAN case.
1233         inputFloats1[0] = TCU_NAN;
1234         inputFloats2[0] = TCU_NAN;
1235
1236         for (size_t ndx = 0; ndx < numElements; ++ndx)
1237         {
1238                 // By default, pick the smallest
1239                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1240
1241                 // Make half of the cases NaN cases
1242                 if ((ndx & 1) == 0)
1243                 {
1244                         // Alternate between the NaN operand
1245                         if ((ndx & 2) == 0)
1246                         {
1247                                 outputFloats[ndx] = inputFloats2[ndx];
1248                                 inputFloats1[ndx] = TCU_NAN;
1249                         }
1250                         else
1251                         {
1252                                 outputFloats[ndx] = inputFloats1[ndx];
1253                                 inputFloats2[ndx] = TCU_NAN;
1254                         }
1255                 }
1256         }
1257
1258         spec.assembly =
1259                 "OpCapability Shader\n"
1260                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1261                 "OpMemoryModel Logical GLSL450\n"
1262                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1263                 "OpExecutionMode %main LocalSize 1 1 1\n"
1264
1265                 "OpName %main           \"main\"\n"
1266                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1267
1268                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1269
1270                 "OpDecorate %buf BufferBlock\n"
1271                 "OpDecorate %indata1 DescriptorSet 0\n"
1272                 "OpDecorate %indata1 Binding 0\n"
1273                 "OpDecorate %indata2 DescriptorSet 0\n"
1274                 "OpDecorate %indata2 Binding 1\n"
1275                 "OpDecorate %outdata DescriptorSet 0\n"
1276                 "OpDecorate %outdata Binding 2\n"
1277                 "OpDecorate %f32arr ArrayStride 4\n"
1278                 "OpMemberDecorate %buf 0 Offset 0\n"
1279
1280                 + string(getComputeAsmCommonTypes()) +
1281
1282                 "%buf        = OpTypeStruct %f32arr\n"
1283                 "%bufptr     = OpTypePointer Uniform %buf\n"
1284                 "%indata1    = OpVariable %bufptr Uniform\n"
1285                 "%indata2    = OpVariable %bufptr Uniform\n"
1286                 "%outdata    = OpVariable %bufptr Uniform\n"
1287
1288                 "%id        = OpVariable %uvec3ptr Input\n"
1289                 "%zero      = OpConstant %i32 0\n"
1290
1291                 "%main      = OpFunction %void None %voidf\n"
1292                 "%label     = OpLabel\n"
1293                 "%idval     = OpLoad %uvec3 %id\n"
1294                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1295                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1296                 "%inval1    = OpLoad %f32 %inloc1\n"
1297                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1298                 "%inval2    = OpLoad %f32 %inloc2\n"
1299                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1300                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1301                 "             OpStore %outloc %rem\n"
1302                 "             OpReturn\n"
1303                 "             OpFunctionEnd\n";
1304
1305         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1306         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1307         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1308         spec.numWorkGroups = IVec3(numElements, 1, 1);
1309         spec.verifyIO = &compareNMin;
1310
1311         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1312
1313         return group.release();
1314 }
1315
1316 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1317 {
1318         if (outputAllocs.size() != 1)
1319                 return false;
1320
1321         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1322         std::vector<deUint8>    data;
1323         expectedOutput->getBytes(data);
1324
1325         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1326         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1327
1328         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1329         {
1330                 const float f0 = expectedOutputAsFloat[idx];
1331                 const float f1 = outputAsFloat[idx];
1332
1333                 // For NMax, NaN is considered acceptable result, since in
1334                 // architectures that do not handle NaNs, those are huge values.
1335                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1336                         return false;
1337         }
1338
1339         return true;
1340 }
1341
1342 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1343 {
1344         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1345         ComputeShaderSpec                               spec;
1346         de::Random                                              rnd                             (deStringHash(group->getName()));
1347         const int                                               numElements             = 200;
1348         vector<float>                                   inputFloats1    (numElements, 0);
1349         vector<float>                                   inputFloats2    (numElements, 0);
1350         vector<float>                                   outputFloats    (numElements, 0);
1351
1352         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1353         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1354
1355         // Make the first case a full-NAN case.
1356         inputFloats1[0] = TCU_NAN;
1357         inputFloats2[0] = TCU_NAN;
1358
1359         for (size_t ndx = 0; ndx < numElements; ++ndx)
1360         {
1361                 // By default, pick the biggest
1362                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1363
1364                 // Make half of the cases NaN cases
1365                 if ((ndx & 1) == 0)
1366                 {
1367                         // Alternate between the NaN operand
1368                         if ((ndx & 2) == 0)
1369                         {
1370                                 outputFloats[ndx] = inputFloats2[ndx];
1371                                 inputFloats1[ndx] = TCU_NAN;
1372                         }
1373                         else
1374                         {
1375                                 outputFloats[ndx] = inputFloats1[ndx];
1376                                 inputFloats2[ndx] = TCU_NAN;
1377                         }
1378                 }
1379         }
1380
1381         spec.assembly =
1382                 "OpCapability Shader\n"
1383                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1384                 "OpMemoryModel Logical GLSL450\n"
1385                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1386                 "OpExecutionMode %main LocalSize 1 1 1\n"
1387
1388                 "OpName %main           \"main\"\n"
1389                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1390
1391                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1392
1393                 "OpDecorate %buf BufferBlock\n"
1394                 "OpDecorate %indata1 DescriptorSet 0\n"
1395                 "OpDecorate %indata1 Binding 0\n"
1396                 "OpDecorate %indata2 DescriptorSet 0\n"
1397                 "OpDecorate %indata2 Binding 1\n"
1398                 "OpDecorate %outdata DescriptorSet 0\n"
1399                 "OpDecorate %outdata Binding 2\n"
1400                 "OpDecorate %f32arr ArrayStride 4\n"
1401                 "OpMemberDecorate %buf 0 Offset 0\n"
1402
1403                 + string(getComputeAsmCommonTypes()) +
1404
1405                 "%buf        = OpTypeStruct %f32arr\n"
1406                 "%bufptr     = OpTypePointer Uniform %buf\n"
1407                 "%indata1    = OpVariable %bufptr Uniform\n"
1408                 "%indata2    = OpVariable %bufptr Uniform\n"
1409                 "%outdata    = OpVariable %bufptr Uniform\n"
1410
1411                 "%id        = OpVariable %uvec3ptr Input\n"
1412                 "%zero      = OpConstant %i32 0\n"
1413
1414                 "%main      = OpFunction %void None %voidf\n"
1415                 "%label     = OpLabel\n"
1416                 "%idval     = OpLoad %uvec3 %id\n"
1417                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1418                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1419                 "%inval1    = OpLoad %f32 %inloc1\n"
1420                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1421                 "%inval2    = OpLoad %f32 %inloc2\n"
1422                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1423                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1424                 "             OpStore %outloc %rem\n"
1425                 "             OpReturn\n"
1426                 "             OpFunctionEnd\n";
1427
1428         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1429         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1430         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1431         spec.numWorkGroups = IVec3(numElements, 1, 1);
1432         spec.verifyIO = &compareNMax;
1433
1434         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1435
1436         return group.release();
1437 }
1438
1439 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1440 {
1441         if (outputAllocs.size() != 1)
1442                 return false;
1443
1444         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1445         std::vector<deUint8>    data;
1446         expectedOutput->getBytes(data);
1447
1448         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1449         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1450
1451         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1452         {
1453                 const float e0 = expectedOutputAsFloat[idx * 2];
1454                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1455                 const float res = outputAsFloat[idx];
1456
1457                 // For NClamp, we have two possible outcomes based on
1458                 // whether NaNs are handled or not.
1459                 // If either min or max value is NaN, the result is undefined,
1460                 // so this test doesn't stress those. If the clamped value is
1461                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1462                 // handled, they are big values that result in max.
1463                 // If all three parameters are NaN, the result should be NaN.
1464                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1465                          (deFloatAbs(e0 - res) < 0.00001f) ||
1466                          (deFloatAbs(e1 - res) < 0.00001f)))
1467                         return false;
1468         }
1469
1470         return true;
1471 }
1472
1473 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1474 {
1475         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1476         ComputeShaderSpec                               spec;
1477         de::Random                                              rnd                             (deStringHash(group->getName()));
1478         const int                                               numElements             = 200;
1479         vector<float>                                   inputFloats1    (numElements, 0);
1480         vector<float>                                   inputFloats2    (numElements, 0);
1481         vector<float>                                   inputFloats3    (numElements, 0);
1482         vector<float>                                   outputFloats    (numElements * 2, 0);
1483
1484         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1485         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1486         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1487
1488         for (size_t ndx = 0; ndx < numElements; ++ndx)
1489         {
1490                 // Results are only defined if max value is bigger than min value.
1491                 if (inputFloats2[ndx] > inputFloats3[ndx])
1492                 {
1493                         float t = inputFloats2[ndx];
1494                         inputFloats2[ndx] = inputFloats3[ndx];
1495                         inputFloats3[ndx] = t;
1496                 }
1497
1498                 // By default, do the clamp, setting both possible answers
1499                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1500
1501                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1502                 float maxResB = maxResA;
1503
1504                 // Alternate between the NaN cases
1505                 if (ndx & 1)
1506                 {
1507                         inputFloats1[ndx] = TCU_NAN;
1508                         // If NaN is handled, the result should be same as the clamp minimum.
1509                         // If NaN is not handled, the result should clamp to the clamp maximum.
1510                         maxResA = inputFloats2[ndx];
1511                         maxResB = inputFloats3[ndx];
1512                 }
1513                 else
1514                 {
1515                         // Not a NaN case - only one legal result.
1516                         maxResA = defaultRes;
1517                         maxResB = defaultRes;
1518                 }
1519
1520                 outputFloats[ndx * 2] = maxResA;
1521                 outputFloats[ndx * 2 + 1] = maxResB;
1522         }
1523
1524         // Make the first case a full-NAN case.
1525         inputFloats1[0] = TCU_NAN;
1526         inputFloats2[0] = TCU_NAN;
1527         inputFloats3[0] = TCU_NAN;
1528         outputFloats[0] = TCU_NAN;
1529         outputFloats[1] = TCU_NAN;
1530
1531         spec.assembly =
1532                 "OpCapability Shader\n"
1533                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1534                 "OpMemoryModel Logical GLSL450\n"
1535                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1536                 "OpExecutionMode %main LocalSize 1 1 1\n"
1537
1538                 "OpName %main           \"main\"\n"
1539                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1540
1541                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1542
1543                 "OpDecorate %buf BufferBlock\n"
1544                 "OpDecorate %indata1 DescriptorSet 0\n"
1545                 "OpDecorate %indata1 Binding 0\n"
1546                 "OpDecorate %indata2 DescriptorSet 0\n"
1547                 "OpDecorate %indata2 Binding 1\n"
1548                 "OpDecorate %indata3 DescriptorSet 0\n"
1549                 "OpDecorate %indata3 Binding 2\n"
1550                 "OpDecorate %outdata DescriptorSet 0\n"
1551                 "OpDecorate %outdata Binding 3\n"
1552                 "OpDecorate %f32arr ArrayStride 4\n"
1553                 "OpMemberDecorate %buf 0 Offset 0\n"
1554
1555                 + string(getComputeAsmCommonTypes()) +
1556
1557                 "%buf        = OpTypeStruct %f32arr\n"
1558                 "%bufptr     = OpTypePointer Uniform %buf\n"
1559                 "%indata1    = OpVariable %bufptr Uniform\n"
1560                 "%indata2    = OpVariable %bufptr Uniform\n"
1561                 "%indata3    = OpVariable %bufptr Uniform\n"
1562                 "%outdata    = OpVariable %bufptr Uniform\n"
1563
1564                 "%id        = OpVariable %uvec3ptr Input\n"
1565                 "%zero      = OpConstant %i32 0\n"
1566
1567                 "%main      = OpFunction %void None %voidf\n"
1568                 "%label     = OpLabel\n"
1569                 "%idval     = OpLoad %uvec3 %id\n"
1570                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1571                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1572                 "%inval1    = OpLoad %f32 %inloc1\n"
1573                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1574                 "%inval2    = OpLoad %f32 %inloc2\n"
1575                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1576                 "%inval3    = OpLoad %f32 %inloc3\n"
1577                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1578                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1579                 "             OpStore %outloc %rem\n"
1580                 "             OpReturn\n"
1581                 "             OpFunctionEnd\n";
1582
1583         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1584         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1585         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1586         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1587         spec.numWorkGroups = IVec3(numElements, 1, 1);
1588         spec.verifyIO = &compareNClamp;
1589
1590         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1591
1592         return group.release();
1593 }
1594
1595 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1596 {
1597         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1598         de::Random                                              rnd                             (deStringHash(group->getName()));
1599         const int                                               numElements             = 200;
1600
1601         const struct CaseParams
1602         {
1603                 const char*             name;
1604                 const char*             failMessage;            // customized status message
1605                 qpTestResult    failResult;                     // override status on failure
1606                 int                             op1Min, op1Max;         // operand ranges
1607                 int                             op2Min, op2Max;
1608         } cases[] =
1609         {
1610                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1611                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1612         };
1613         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1614
1615         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1616         {
1617                 const CaseParams&       params          = cases[caseNdx];
1618                 ComputeShaderSpec       spec;
1619                 vector<deInt32>         inputInts1      (numElements, 0);
1620                 vector<deInt32>         inputInts2      (numElements, 0);
1621                 vector<deInt32>         outputInts      (numElements, 0);
1622
1623                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1624                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1625
1626                 for (int ndx = 0; ndx < numElements; ++ndx)
1627                 {
1628                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1629                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1630                 }
1631
1632                 spec.assembly =
1633                         string(getComputeAsmShaderPreamble()) +
1634
1635                         "OpName %main           \"main\"\n"
1636                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1637
1638                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1639
1640                         "OpDecorate %buf BufferBlock\n"
1641                         "OpDecorate %indata1 DescriptorSet 0\n"
1642                         "OpDecorate %indata1 Binding 0\n"
1643                         "OpDecorate %indata2 DescriptorSet 0\n"
1644                         "OpDecorate %indata2 Binding 1\n"
1645                         "OpDecorate %outdata DescriptorSet 0\n"
1646                         "OpDecorate %outdata Binding 2\n"
1647                         "OpDecorate %i32arr ArrayStride 4\n"
1648                         "OpMemberDecorate %buf 0 Offset 0\n"
1649
1650                         + string(getComputeAsmCommonTypes()) +
1651
1652                         "%buf        = OpTypeStruct %i32arr\n"
1653                         "%bufptr     = OpTypePointer Uniform %buf\n"
1654                         "%indata1    = OpVariable %bufptr Uniform\n"
1655                         "%indata2    = OpVariable %bufptr Uniform\n"
1656                         "%outdata    = OpVariable %bufptr Uniform\n"
1657
1658                         "%id        = OpVariable %uvec3ptr Input\n"
1659                         "%zero      = OpConstant %i32 0\n"
1660
1661                         "%main      = OpFunction %void None %voidf\n"
1662                         "%label     = OpLabel\n"
1663                         "%idval     = OpLoad %uvec3 %id\n"
1664                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1665                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1666                         "%inval1    = OpLoad %i32 %inloc1\n"
1667                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1668                         "%inval2    = OpLoad %i32 %inloc2\n"
1669                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1670                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1671                         "             OpStore %outloc %rem\n"
1672                         "             OpReturn\n"
1673                         "             OpFunctionEnd\n";
1674
1675                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1676                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1677                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1678                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1679                 spec.failResult                 = params.failResult;
1680                 spec.failMessage                = params.failMessage;
1681
1682                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1683         }
1684
1685         return group.release();
1686 }
1687
1688 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1689 {
1690         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1691         de::Random                                              rnd                             (deStringHash(group->getName()));
1692         const int                                               numElements             = 200;
1693
1694         const struct CaseParams
1695         {
1696                 const char*             name;
1697                 const char*             failMessage;            // customized status message
1698                 qpTestResult    failResult;                     // override status on failure
1699                 bool                    positive;
1700         } cases[] =
1701         {
1702                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1703                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1704         };
1705         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1706
1707         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1708         {
1709                 const CaseParams&       params          = cases[caseNdx];
1710                 ComputeShaderSpec       spec;
1711                 vector<deInt64>         inputInts1      (numElements, 0);
1712                 vector<deInt64>         inputInts2      (numElements, 0);
1713                 vector<deInt64>         outputInts      (numElements, 0);
1714
1715                 if (params.positive)
1716                 {
1717                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1718                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1719                 }
1720                 else
1721                 {
1722                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1723                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1724                 }
1725
1726                 for (int ndx = 0; ndx < numElements; ++ndx)
1727                 {
1728                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1729                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1730                 }
1731
1732                 spec.assembly =
1733                         "OpCapability Int64\n"
1734
1735                         + string(getComputeAsmShaderPreamble()) +
1736
1737                         "OpName %main           \"main\"\n"
1738                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1739
1740                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1741
1742                         "OpDecorate %buf BufferBlock\n"
1743                         "OpDecorate %indata1 DescriptorSet 0\n"
1744                         "OpDecorate %indata1 Binding 0\n"
1745                         "OpDecorate %indata2 DescriptorSet 0\n"
1746                         "OpDecorate %indata2 Binding 1\n"
1747                         "OpDecorate %outdata DescriptorSet 0\n"
1748                         "OpDecorate %outdata Binding 2\n"
1749                         "OpDecorate %i64arr ArrayStride 8\n"
1750                         "OpMemberDecorate %buf 0 Offset 0\n"
1751
1752                         + string(getComputeAsmCommonTypes())
1753                         + string(getComputeAsmCommonInt64Types()) +
1754
1755                         "%buf        = OpTypeStruct %i64arr\n"
1756                         "%bufptr     = OpTypePointer Uniform %buf\n"
1757                         "%indata1    = OpVariable %bufptr Uniform\n"
1758                         "%indata2    = OpVariable %bufptr Uniform\n"
1759                         "%outdata    = OpVariable %bufptr Uniform\n"
1760
1761                         "%id        = OpVariable %uvec3ptr Input\n"
1762                         "%zero      = OpConstant %i64 0\n"
1763
1764                         "%main      = OpFunction %void None %voidf\n"
1765                         "%label     = OpLabel\n"
1766                         "%idval     = OpLoad %uvec3 %id\n"
1767                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1768                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1769                         "%inval1    = OpLoad %i64 %inloc1\n"
1770                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1771                         "%inval2    = OpLoad %i64 %inloc2\n"
1772                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1773                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1774                         "             OpStore %outloc %rem\n"
1775                         "             OpReturn\n"
1776                         "             OpFunctionEnd\n";
1777
1778                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1779                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1780                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1781                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1782                 spec.failResult                 = params.failResult;
1783                 spec.failMessage                = params.failMessage;
1784
1785                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1786
1787                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1788         }
1789
1790         return group.release();
1791 }
1792
1793 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1794 {
1795         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1796         de::Random                                              rnd                             (deStringHash(group->getName()));
1797         const int                                               numElements             = 200;
1798
1799         const struct CaseParams
1800         {
1801                 const char*             name;
1802                 const char*             failMessage;            // customized status message
1803                 qpTestResult    failResult;                     // override status on failure
1804                 int                             op1Min, op1Max;         // operand ranges
1805                 int                             op2Min, op2Max;
1806         } cases[] =
1807         {
1808                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1809                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1810         };
1811         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1812
1813         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1814         {
1815                 const CaseParams&       params          = cases[caseNdx];
1816
1817                 ComputeShaderSpec       spec;
1818                 vector<deInt32>         inputInts1      (numElements, 0);
1819                 vector<deInt32>         inputInts2      (numElements, 0);
1820                 vector<deInt32>         outputInts      (numElements, 0);
1821
1822                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1823                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1824
1825                 for (int ndx = 0; ndx < numElements; ++ndx)
1826                 {
1827                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1828                         if (rem == 0)
1829                         {
1830                                 outputInts[ndx] = 0;
1831                         }
1832                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1833                         {
1834                                 // They have the same sign
1835                                 outputInts[ndx] = rem;
1836                         }
1837                         else
1838                         {
1839                                 // They have opposite sign.  The remainder operation takes the
1840                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1841                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1842                                 // the result has the correct sign and that it is still
1843                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1844                                 //
1845                                 // See also http://mathforum.org/library/drmath/view/52343.html
1846                                 outputInts[ndx] = rem + inputInts2[ndx];
1847                         }
1848                 }
1849
1850                 spec.assembly =
1851                         string(getComputeAsmShaderPreamble()) +
1852
1853                         "OpName %main           \"main\"\n"
1854                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1855
1856                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1857
1858                         "OpDecorate %buf BufferBlock\n"
1859                         "OpDecorate %indata1 DescriptorSet 0\n"
1860                         "OpDecorate %indata1 Binding 0\n"
1861                         "OpDecorate %indata2 DescriptorSet 0\n"
1862                         "OpDecorate %indata2 Binding 1\n"
1863                         "OpDecorate %outdata DescriptorSet 0\n"
1864                         "OpDecorate %outdata Binding 2\n"
1865                         "OpDecorate %i32arr ArrayStride 4\n"
1866                         "OpMemberDecorate %buf 0 Offset 0\n"
1867
1868                         + string(getComputeAsmCommonTypes()) +
1869
1870                         "%buf        = OpTypeStruct %i32arr\n"
1871                         "%bufptr     = OpTypePointer Uniform %buf\n"
1872                         "%indata1    = OpVariable %bufptr Uniform\n"
1873                         "%indata2    = OpVariable %bufptr Uniform\n"
1874                         "%outdata    = OpVariable %bufptr Uniform\n"
1875
1876                         "%id        = OpVariable %uvec3ptr Input\n"
1877                         "%zero      = OpConstant %i32 0\n"
1878
1879                         "%main      = OpFunction %void None %voidf\n"
1880                         "%label     = OpLabel\n"
1881                         "%idval     = OpLoad %uvec3 %id\n"
1882                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1883                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1884                         "%inval1    = OpLoad %i32 %inloc1\n"
1885                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1886                         "%inval2    = OpLoad %i32 %inloc2\n"
1887                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1888                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1889                         "             OpStore %outloc %rem\n"
1890                         "             OpReturn\n"
1891                         "             OpFunctionEnd\n";
1892
1893                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1894                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1895                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1896                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1897                 spec.failResult                 = params.failResult;
1898                 spec.failMessage                = params.failMessage;
1899
1900                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1901         }
1902
1903         return group.release();
1904 }
1905
1906 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1907 {
1908         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1909         de::Random                                              rnd                             (deStringHash(group->getName()));
1910         const int                                               numElements             = 200;
1911
1912         const struct CaseParams
1913         {
1914                 const char*             name;
1915                 const char*             failMessage;            // customized status message
1916                 qpTestResult    failResult;                     // override status on failure
1917                 bool                    positive;
1918         } cases[] =
1919         {
1920                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1921                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1922         };
1923         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1924
1925         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1926         {
1927                 const CaseParams&       params          = cases[caseNdx];
1928
1929                 ComputeShaderSpec       spec;
1930                 vector<deInt64>         inputInts1      (numElements, 0);
1931                 vector<deInt64>         inputInts2      (numElements, 0);
1932                 vector<deInt64>         outputInts      (numElements, 0);
1933
1934
1935                 if (params.positive)
1936                 {
1937                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1938                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1939                 }
1940                 else
1941                 {
1942                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1943                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1944                 }
1945
1946                 for (int ndx = 0; ndx < numElements; ++ndx)
1947                 {
1948                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1949                         if (rem == 0)
1950                         {
1951                                 outputInts[ndx] = 0;
1952                         }
1953                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1954                         {
1955                                 // They have the same sign
1956                                 outputInts[ndx] = rem;
1957                         }
1958                         else
1959                         {
1960                                 // They have opposite sign.  The remainder operation takes the
1961                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1962                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1963                                 // the result has the correct sign and that it is still
1964                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1965                                 //
1966                                 // See also http://mathforum.org/library/drmath/view/52343.html
1967                                 outputInts[ndx] = rem + inputInts2[ndx];
1968                         }
1969                 }
1970
1971                 spec.assembly =
1972                         "OpCapability Int64\n"
1973
1974                         + string(getComputeAsmShaderPreamble()) +
1975
1976                         "OpName %main           \"main\"\n"
1977                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1978
1979                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1980
1981                         "OpDecorate %buf BufferBlock\n"
1982                         "OpDecorate %indata1 DescriptorSet 0\n"
1983                         "OpDecorate %indata1 Binding 0\n"
1984                         "OpDecorate %indata2 DescriptorSet 0\n"
1985                         "OpDecorate %indata2 Binding 1\n"
1986                         "OpDecorate %outdata DescriptorSet 0\n"
1987                         "OpDecorate %outdata Binding 2\n"
1988                         "OpDecorate %i64arr ArrayStride 8\n"
1989                         "OpMemberDecorate %buf 0 Offset 0\n"
1990
1991                         + string(getComputeAsmCommonTypes())
1992                         + string(getComputeAsmCommonInt64Types()) +
1993
1994                         "%buf        = OpTypeStruct %i64arr\n"
1995                         "%bufptr     = OpTypePointer Uniform %buf\n"
1996                         "%indata1    = OpVariable %bufptr Uniform\n"
1997                         "%indata2    = OpVariable %bufptr Uniform\n"
1998                         "%outdata    = OpVariable %bufptr Uniform\n"
1999
2000                         "%id        = OpVariable %uvec3ptr Input\n"
2001                         "%zero      = OpConstant %i64 0\n"
2002
2003                         "%main      = OpFunction %void None %voidf\n"
2004                         "%label     = OpLabel\n"
2005                         "%idval     = OpLoad %uvec3 %id\n"
2006                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2007                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2008                         "%inval1    = OpLoad %i64 %inloc1\n"
2009                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2010                         "%inval2    = OpLoad %i64 %inloc2\n"
2011                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2012                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2013                         "             OpStore %outloc %rem\n"
2014                         "             OpReturn\n"
2015                         "             OpFunctionEnd\n";
2016
2017                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2018                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2019                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2020                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2021                 spec.failResult                 = params.failResult;
2022                 spec.failMessage                = params.failMessage;
2023
2024                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2025
2026                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2027         }
2028
2029         return group.release();
2030 }
2031
2032 // Copy contents in the input buffer to the output buffer.
2033 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2034 {
2035         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2036         de::Random                                              rnd                             (deStringHash(group->getName()));
2037         const int                                               numElements             = 100;
2038
2039         // 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.
2040         ComputeShaderSpec                               spec1;
2041         vector<Vec4>                                    inputFloats1    (numElements);
2042         vector<Vec4>                                    outputFloats1   (numElements);
2043
2044         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2045
2046         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2047         floorAll(inputFloats1);
2048
2049         for (size_t ndx = 0; ndx < numElements; ++ndx)
2050                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2051
2052         spec1.assembly =
2053                 string(getComputeAsmShaderPreamble()) +
2054
2055                 "OpName %main           \"main\"\n"
2056                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2057
2058                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2059                 "OpDecorate %vec4arr ArrayStride 16\n"
2060
2061                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2062
2063                 "%vec4       = OpTypeVector %f32 4\n"
2064                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2065                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2066                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2067                 "%buf        = OpTypeStruct %vec4arr\n"
2068                 "%bufptr     = OpTypePointer Uniform %buf\n"
2069                 "%indata     = OpVariable %bufptr Uniform\n"
2070                 "%outdata    = OpVariable %bufptr Uniform\n"
2071
2072                 "%id         = OpVariable %uvec3ptr Input\n"
2073                 "%zero       = OpConstant %i32 0\n"
2074                 "%c_f_0      = OpConstant %f32 0.\n"
2075                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2076                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2077                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2078                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2079
2080                 "%main       = OpFunction %void None %voidf\n"
2081                 "%label      = OpLabel\n"
2082                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2083                 "%idval      = OpLoad %uvec3 %id\n"
2084                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2085                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2086                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2087                 "              OpCopyMemory %v_vec4 %inloc\n"
2088                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2089                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2090                 "              OpStore %outloc %add\n"
2091                 "              OpReturn\n"
2092                 "              OpFunctionEnd\n";
2093
2094         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2095         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2096         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2097
2098         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2099
2100         // The following case copies a float[100] variable from the input buffer to the output buffer.
2101         ComputeShaderSpec                               spec2;
2102         vector<float>                                   inputFloats2    (numElements);
2103         vector<float>                                   outputFloats2   (numElements);
2104
2105         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2106
2107         for (size_t ndx = 0; ndx < numElements; ++ndx)
2108                 outputFloats2[ndx] = inputFloats2[ndx];
2109
2110         spec2.assembly =
2111                 string(getComputeAsmShaderPreamble()) +
2112
2113                 "OpName %main           \"main\"\n"
2114                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2115
2116                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2117                 "OpDecorate %f32arr100 ArrayStride 4\n"
2118
2119                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2120
2121                 "%hundred        = OpConstant %u32 100\n"
2122                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2123                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2124                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2125                 "%buf            = OpTypeStruct %f32arr100\n"
2126                 "%bufptr         = OpTypePointer Uniform %buf\n"
2127                 "%indata         = OpVariable %bufptr Uniform\n"
2128                 "%outdata        = OpVariable %bufptr Uniform\n"
2129
2130                 "%id             = OpVariable %uvec3ptr Input\n"
2131                 "%zero           = OpConstant %i32 0\n"
2132
2133                 "%main           = OpFunction %void None %voidf\n"
2134                 "%label          = OpLabel\n"
2135                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2136                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2137                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2138                 "                  OpCopyMemory %var %inarr\n"
2139                 "                  OpCopyMemory %outarr %var\n"
2140                 "                  OpReturn\n"
2141                 "                  OpFunctionEnd\n";
2142
2143         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2144         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2145         spec2.numWorkGroups = IVec3(1, 1, 1);
2146
2147         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2148
2149         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2150         ComputeShaderSpec                               spec3;
2151         vector<float>                                   inputFloats3    (16);
2152         vector<float>                                   outputFloats3   (16);
2153
2154         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2155
2156         for (size_t ndx = 0; ndx < 16; ++ndx)
2157                 outputFloats3[ndx] = inputFloats3[ndx];
2158
2159         spec3.assembly =
2160                 string(getComputeAsmShaderPreamble()) +
2161
2162                 "OpName %main           \"main\"\n"
2163                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2164
2165                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2166                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2167                 "OpMemberDecorate %buf 1 Offset 16\n"
2168                 "OpMemberDecorate %buf 2 Offset 32\n"
2169                 "OpMemberDecorate %buf 3 Offset 48\n"
2170
2171                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2172
2173                 "%vec4      = OpTypeVector %f32 4\n"
2174                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2175                 "%bufptr    = OpTypePointer Uniform %buf\n"
2176                 "%indata    = OpVariable %bufptr Uniform\n"
2177                 "%outdata   = OpVariable %bufptr Uniform\n"
2178                 "%vec4stptr = OpTypePointer Function %buf\n"
2179
2180                 "%id        = OpVariable %uvec3ptr Input\n"
2181                 "%zero      = OpConstant %i32 0\n"
2182
2183                 "%main      = OpFunction %void None %voidf\n"
2184                 "%label     = OpLabel\n"
2185                 "%var       = OpVariable %vec4stptr Function\n"
2186                 "             OpCopyMemory %var %indata\n"
2187                 "             OpCopyMemory %outdata %var\n"
2188                 "             OpReturn\n"
2189                 "             OpFunctionEnd\n";
2190
2191         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2192         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2193         spec3.numWorkGroups = IVec3(1, 1, 1);
2194
2195         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2196
2197         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2198         ComputeShaderSpec                               spec4;
2199         vector<float>                                   inputFloats4    (numElements);
2200         vector<float>                                   outputFloats4   (numElements);
2201
2202         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2203
2204         for (size_t ndx = 0; ndx < numElements; ++ndx)
2205                 outputFloats4[ndx] = -inputFloats4[ndx];
2206
2207         spec4.assembly =
2208                 string(getComputeAsmShaderPreamble()) +
2209
2210                 "OpName %main           \"main\"\n"
2211                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2212
2213                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2214
2215                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2216
2217                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2218                 "%id        = OpVariable %uvec3ptr Input\n"
2219                 "%zero      = OpConstant %i32 0\n"
2220
2221                 "%main      = OpFunction %void None %voidf\n"
2222                 "%label     = OpLabel\n"
2223                 "%var       = OpVariable %f32ptr_f Function\n"
2224                 "%idval     = OpLoad %uvec3 %id\n"
2225                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2226                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2227                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2228                 "             OpCopyMemory %var %inloc\n"
2229                 "%val       = OpLoad %f32 %var\n"
2230                 "%neg       = OpFNegate %f32 %val\n"
2231                 "             OpStore %outloc %neg\n"
2232                 "             OpReturn\n"
2233                 "             OpFunctionEnd\n";
2234
2235         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2236         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2237         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2238
2239         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2240
2241         return group.release();
2242 }
2243
2244 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2245 {
2246         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2247         ComputeShaderSpec                               spec;
2248         de::Random                                              rnd                             (deStringHash(group->getName()));
2249         const int                                               numElements             = 100;
2250         vector<float>                                   inputFloats             (numElements, 0);
2251         vector<float>                                   outputFloats    (numElements, 0);
2252
2253         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2254
2255         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2256         floorAll(inputFloats);
2257
2258         for (size_t ndx = 0; ndx < numElements; ++ndx)
2259                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2260
2261         spec.assembly =
2262                 string(getComputeAsmShaderPreamble()) +
2263
2264                 "OpName %main           \"main\"\n"
2265                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2266
2267                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2268
2269                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2270
2271                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2272                 "%three    = OpConstant %u32 3\n"
2273                 "%farr     = OpTypeArray %f32 %three\n"
2274                 "%fst      = OpTypeStruct %f32 %f32\n"
2275
2276                 + string(getComputeAsmInputOutputBuffer()) +
2277
2278                 "%id            = OpVariable %uvec3ptr Input\n"
2279                 "%zero          = OpConstant %i32 0\n"
2280                 "%c_f           = OpConstant %f32 1.5\n"
2281                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2282                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2283                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2284                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2285
2286                 "%main          = OpFunction %void None %voidf\n"
2287                 "%label         = OpLabel\n"
2288                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2289                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2290                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2291                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2292                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2293                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2294                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2295                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2296                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2297                 // Add up. 1.5 * 5 = 7.5.
2298                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2299                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2300                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2301                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2302
2303                 "%idval         = OpLoad %uvec3 %id\n"
2304                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2305                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2306                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2307                 "%inval         = OpLoad %f32 %inloc\n"
2308                 "%add           = OpFAdd %f32 %add4 %inval\n"
2309                 "                 OpStore %outloc %add\n"
2310                 "                 OpReturn\n"
2311                 "                 OpFunctionEnd\n";
2312         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2313         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2314         spec.numWorkGroups = IVec3(numElements, 1, 1);
2315
2316         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2317
2318         return group.release();
2319 }
2320 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2321 //
2322 // #version 430
2323 //
2324 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2325 //   float elements[];
2326 // } input_data;
2327 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2328 //   float elements[];
2329 // } output_data;
2330 //
2331 // void not_called_func() {
2332 //   // place OpUnreachable here
2333 // }
2334 //
2335 // uint modulo4(uint val) {
2336 //   switch (val % uint(4)) {
2337 //     case 0:  return 3;
2338 //     case 1:  return 2;
2339 //     case 2:  return 1;
2340 //     case 3:  return 0;
2341 //     default: return 100; // place OpUnreachable here
2342 //   }
2343 // }
2344 //
2345 // uint const5() {
2346 //   return 5;
2347 //   // place OpUnreachable here
2348 // }
2349 //
2350 // void main() {
2351 //   uint x = gl_GlobalInvocationID.x;
2352 //   if (const5() > modulo4(1000)) {
2353 //     output_data.elements[x] = -input_data.elements[x];
2354 //   } else {
2355 //     // place OpUnreachable here
2356 //     output_data.elements[x] = input_data.elements[x];
2357 //   }
2358 // }
2359
2360 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2361 {
2362         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2363         ComputeShaderSpec                               spec;
2364         de::Random                                              rnd                             (deStringHash(group->getName()));
2365         const int                                               numElements             = 100;
2366         vector<float>                                   positiveFloats  (numElements, 0);
2367         vector<float>                                   negativeFloats  (numElements, 0);
2368
2369         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2370
2371         for (size_t ndx = 0; ndx < numElements; ++ndx)
2372                 negativeFloats[ndx] = -positiveFloats[ndx];
2373
2374         spec.assembly =
2375                 string(getComputeAsmShaderPreamble()) +
2376
2377                 "OpSource GLSL 430\n"
2378                 "OpName %main            \"main\"\n"
2379                 "OpName %func_not_called_func \"not_called_func(\"\n"
2380                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2381                 "OpName %func_const5          \"const5(\"\n"
2382                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2383
2384                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2385
2386                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2387
2388                 "%u32ptr    = OpTypePointer Function %u32\n"
2389                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2390                 "%unitf     = OpTypeFunction %u32\n"
2391
2392                 "%id        = OpVariable %uvec3ptr Input\n"
2393                 "%zero      = OpConstant %u32 0\n"
2394                 "%one       = OpConstant %u32 1\n"
2395                 "%two       = OpConstant %u32 2\n"
2396                 "%three     = OpConstant %u32 3\n"
2397                 "%four      = OpConstant %u32 4\n"
2398                 "%five      = OpConstant %u32 5\n"
2399                 "%hundred   = OpConstant %u32 100\n"
2400                 "%thousand  = OpConstant %u32 1000\n"
2401
2402                 + string(getComputeAsmInputOutputBuffer()) +
2403
2404                 // Main()
2405                 "%main   = OpFunction %void None %voidf\n"
2406                 "%main_entry  = OpLabel\n"
2407                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2408                 "%idval       = OpLoad %uvec3 %id\n"
2409                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2410                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2411                 "%inval       = OpLoad %f32 %inloc\n"
2412                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2413                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2414                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2415                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2416                 "               OpSelectionMerge %if_end None\n"
2417                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2418                 "%if_true     = OpLabel\n"
2419                 "%negate      = OpFNegate %f32 %inval\n"
2420                 "               OpStore %outloc %negate\n"
2421                 "               OpBranch %if_end\n"
2422                 "%if_false    = OpLabel\n"
2423                 "               OpUnreachable\n" // Unreachable else branch for if statement
2424                 "%if_end      = OpLabel\n"
2425                 "               OpReturn\n"
2426                 "               OpFunctionEnd\n"
2427
2428                 // not_called_function()
2429                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2430                 "%not_called_func_entry = OpLabel\n"
2431                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2432                 "                         OpFunctionEnd\n"
2433
2434                 // modulo4()
2435                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2436                 "%valptr        = OpFunctionParameter %u32ptr\n"
2437                 "%modulo4_entry = OpLabel\n"
2438                 "%val           = OpLoad %u32 %valptr\n"
2439                 "%modulo        = OpUMod %u32 %val %four\n"
2440                 "                 OpSelectionMerge %switch_merge None\n"
2441                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2442                 "%case0         = OpLabel\n"
2443                 "                 OpReturnValue %three\n"
2444                 "%case1         = OpLabel\n"
2445                 "                 OpReturnValue %two\n"
2446                 "%case2         = OpLabel\n"
2447                 "                 OpReturnValue %one\n"
2448                 "%case3         = OpLabel\n"
2449                 "                 OpReturnValue %zero\n"
2450                 "%default       = OpLabel\n"
2451                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2452                 "%switch_merge  = OpLabel\n"
2453                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2454                 "                 OpFunctionEnd\n"
2455
2456                 // const5()
2457                 "%func_const5  = OpFunction %u32 None %unitf\n"
2458                 "%const5_entry = OpLabel\n"
2459                 "                OpReturnValue %five\n"
2460                 "%unreachable  = OpLabel\n"
2461                 "                OpUnreachable\n" // Unreachable block in function
2462                 "                OpFunctionEnd\n";
2463         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2464         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2465         spec.numWorkGroups = IVec3(numElements, 1, 1);
2466
2467         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2468
2469         return group.release();
2470 }
2471
2472 // Assembly code used for testing decoration group is based on GLSL source code:
2473 //
2474 // #version 430
2475 //
2476 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2477 //   float elements[];
2478 // } input_data0;
2479 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2480 //   float elements[];
2481 // } input_data1;
2482 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2483 //   float elements[];
2484 // } input_data2;
2485 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2486 //   float elements[];
2487 // } input_data3;
2488 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2489 //   float elements[];
2490 // } input_data4;
2491 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2492 //   float elements[];
2493 // } output_data;
2494 //
2495 // void main() {
2496 //   uint x = gl_GlobalInvocationID.x;
2497 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2498 // }
2499 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2500 {
2501         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2502         ComputeShaderSpec                               spec;
2503         de::Random                                              rnd                             (deStringHash(group->getName()));
2504         const int                                               numElements             = 100;
2505         vector<float>                                   inputFloats0    (numElements, 0);
2506         vector<float>                                   inputFloats1    (numElements, 0);
2507         vector<float>                                   inputFloats2    (numElements, 0);
2508         vector<float>                                   inputFloats3    (numElements, 0);
2509         vector<float>                                   inputFloats4    (numElements, 0);
2510         vector<float>                                   outputFloats    (numElements, 0);
2511
2512         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2513         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2514         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2515         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2516         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2517
2518         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2519         floorAll(inputFloats0);
2520         floorAll(inputFloats1);
2521         floorAll(inputFloats2);
2522         floorAll(inputFloats3);
2523         floorAll(inputFloats4);
2524
2525         for (size_t ndx = 0; ndx < numElements; ++ndx)
2526                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2527
2528         spec.assembly =
2529                 string(getComputeAsmShaderPreamble()) +
2530
2531                 "OpSource GLSL 430\n"
2532                 "OpName %main \"main\"\n"
2533                 "OpName %id \"gl_GlobalInvocationID\"\n"
2534
2535                 // Not using group decoration on variable.
2536                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2537                 // Not using group decoration on type.
2538                 "OpDecorate %f32arr ArrayStride 4\n"
2539
2540                 "OpDecorate %groups BufferBlock\n"
2541                 "OpDecorate %groupm Offset 0\n"
2542                 "%groups = OpDecorationGroup\n"
2543                 "%groupm = OpDecorationGroup\n"
2544
2545                 // Group decoration on multiple structs.
2546                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2547                 // Group decoration on multiple struct members.
2548                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2549
2550                 "OpDecorate %group1 DescriptorSet 0\n"
2551                 "OpDecorate %group3 DescriptorSet 0\n"
2552                 "OpDecorate %group3 NonWritable\n"
2553                 "OpDecorate %group3 Restrict\n"
2554                 "%group0 = OpDecorationGroup\n"
2555                 "%group1 = OpDecorationGroup\n"
2556                 "%group3 = OpDecorationGroup\n"
2557
2558                 // Applying the same decoration group multiple times.
2559                 "OpGroupDecorate %group1 %outdata\n"
2560                 "OpGroupDecorate %group1 %outdata\n"
2561                 "OpGroupDecorate %group1 %outdata\n"
2562                 "OpDecorate %outdata DescriptorSet 0\n"
2563                 "OpDecorate %outdata Binding 5\n"
2564                 // Applying decoration group containing nothing.
2565                 "OpGroupDecorate %group0 %indata0\n"
2566                 "OpDecorate %indata0 DescriptorSet 0\n"
2567                 "OpDecorate %indata0 Binding 0\n"
2568                 // Applying decoration group containing one decoration.
2569                 "OpGroupDecorate %group1 %indata1\n"
2570                 "OpDecorate %indata1 Binding 1\n"
2571                 // Applying decoration group containing multiple decorations.
2572                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2573                 "OpDecorate %indata2 Binding 2\n"
2574                 "OpDecorate %indata3 Binding 3\n"
2575                 // Applying multiple decoration groups (with overlapping).
2576                 "OpGroupDecorate %group0 %indata4\n"
2577                 "OpGroupDecorate %group1 %indata4\n"
2578                 "OpGroupDecorate %group3 %indata4\n"
2579                 "OpDecorate %indata4 Binding 4\n"
2580
2581                 + string(getComputeAsmCommonTypes()) +
2582
2583                 "%id   = OpVariable %uvec3ptr Input\n"
2584                 "%zero = OpConstant %i32 0\n"
2585
2586                 "%outbuf    = OpTypeStruct %f32arr\n"
2587                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2588                 "%outdata   = OpVariable %outbufptr Uniform\n"
2589                 "%inbuf0    = OpTypeStruct %f32arr\n"
2590                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2591                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2592                 "%inbuf1    = OpTypeStruct %f32arr\n"
2593                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2594                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2595                 "%inbuf2    = OpTypeStruct %f32arr\n"
2596                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2597                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2598                 "%inbuf3    = OpTypeStruct %f32arr\n"
2599                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2600                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2601                 "%inbuf4    = OpTypeStruct %f32arr\n"
2602                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2603                 "%indata4   = OpVariable %inbufptr Uniform\n"
2604
2605                 "%main   = OpFunction %void None %voidf\n"
2606                 "%label  = OpLabel\n"
2607                 "%idval  = OpLoad %uvec3 %id\n"
2608                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2609                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2610                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2611                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2612                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2613                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2614                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2615                 "%inval0 = OpLoad %f32 %inloc0\n"
2616                 "%inval1 = OpLoad %f32 %inloc1\n"
2617                 "%inval2 = OpLoad %f32 %inloc2\n"
2618                 "%inval3 = OpLoad %f32 %inloc3\n"
2619                 "%inval4 = OpLoad %f32 %inloc4\n"
2620                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2621                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2622                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2623                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2624                 "          OpStore %outloc %add\n"
2625                 "          OpReturn\n"
2626                 "          OpFunctionEnd\n";
2627         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2628         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2629         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2630         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2631         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2632         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2633         spec.numWorkGroups = IVec3(numElements, 1, 1);
2634
2635         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2636
2637         return group.release();
2638 }
2639
2640 struct SpecConstantTwoIntCase
2641 {
2642         const char*             caseName;
2643         const char*             scDefinition0;
2644         const char*             scDefinition1;
2645         const char*             scResultType;
2646         const char*             scOperation;
2647         deInt32                 scActualValue0;
2648         deInt32                 scActualValue1;
2649         const char*             resultOperation;
2650         vector<deInt32> expectedOutput;
2651         deInt32                 scActualValueLength;
2652
2653                                         SpecConstantTwoIntCase (const char* name,
2654                                                                                         const char* definition0,
2655                                                                                         const char* definition1,
2656                                                                                         const char* resultType,
2657                                                                                         const char* operation,
2658                                                                                         deInt32 value0,
2659                                                                                         deInt32 value1,
2660                                                                                         const char* resultOp,
2661                                                                                         const vector<deInt32>& output,
2662                                                                                         const deInt32   valueLength = sizeof(deInt32))
2663                                                 : caseName                              (name)
2664                                                 , scDefinition0                 (definition0)
2665                                                 , scDefinition1                 (definition1)
2666                                                 , scResultType                  (resultType)
2667                                                 , scOperation                   (operation)
2668                                                 , scActualValue0                (value0)
2669                                                 , scActualValue1                (value1)
2670                                                 , resultOperation               (resultOp)
2671                                                 , expectedOutput                (output)
2672                                                 , scActualValueLength   (valueLength)
2673                                                 {}
2674 };
2675
2676 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2677 {
2678         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2679         vector<SpecConstantTwoIntCase>  cases;
2680         de::Random                                              rnd                             (deStringHash(group->getName()));
2681         const int                                               numElements             = 100;
2682         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2683         vector<deInt32>                                 inputInts               (numElements, 0);
2684         vector<deInt32>                                 outputInts1             (numElements, 0);
2685         vector<deInt32>                                 outputInts2             (numElements, 0);
2686         vector<deInt32>                                 outputInts3             (numElements, 0);
2687         vector<deInt32>                                 outputInts4             (numElements, 0);
2688         const StringTemplate                    shaderTemplate  (
2689                 "${CAPABILITIES:opt}"
2690                 + string(getComputeAsmShaderPreamble()) +
2691
2692                 "OpName %main           \"main\"\n"
2693                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2694
2695                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2696                 "OpDecorate %sc_0  SpecId 0\n"
2697                 "OpDecorate %sc_1  SpecId 1\n"
2698                 "OpDecorate %i32arr ArrayStride 4\n"
2699
2700                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2701
2702                 "${OPTYPE_DEFINITIONS:opt}"
2703                 "%buf     = OpTypeStruct %i32arr\n"
2704                 "%bufptr  = OpTypePointer Uniform %buf\n"
2705                 "%indata    = OpVariable %bufptr Uniform\n"
2706                 "%outdata   = OpVariable %bufptr Uniform\n"
2707
2708                 "%id        = OpVariable %uvec3ptr Input\n"
2709                 "%zero      = OpConstant %i32 0\n"
2710
2711                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2712                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2713                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2714
2715                 "%main      = OpFunction %void None %voidf\n"
2716                 "%label     = OpLabel\n"
2717                 "${TYPE_CONVERT:opt}"
2718                 "%idval     = OpLoad %uvec3 %id\n"
2719                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2720                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2721                 "%inval     = OpLoad %i32 %inloc\n"
2722                 "%final     = ${GEN_RESULT}\n"
2723                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2724                 "             OpStore %outloc %final\n"
2725                 "             OpReturn\n"
2726                 "             OpFunctionEnd\n");
2727
2728         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2729
2730         for (size_t ndx = 0; ndx < numElements; ++ndx)
2731         {
2732                 outputInts1[ndx] = inputInts[ndx] + 42;
2733                 outputInts2[ndx] = inputInts[ndx];
2734                 outputInts3[ndx] = inputInts[ndx] - 11200;
2735                 outputInts4[ndx] = inputInts[ndx] + 1;
2736         }
2737
2738         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2739         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2740         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2741         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2742
2743         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2744         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2745         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2746         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2747         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2748         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2749         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2750         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2751         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2752         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2753         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2754         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2755         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2756         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2757         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2758         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2759         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2760         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2761         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2762         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2763         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2764         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2765         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2766         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2767         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2768         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2769         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2770         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2771         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2772         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2773         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2774         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2775         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2776         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2777         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2778         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2779
2780         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2781         {
2782                 map<string, string>             specializations;
2783                 ComputeShaderSpec               spec;
2784
2785                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2786                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2787                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2788                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2789                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2790
2791                 // Special SPIR-V code for SConvert-case
2792                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2793                 {
2794                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2795                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2796                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2797                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2798                 }
2799
2800                 // Special SPIR-V code for FConvert-case
2801                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2802                 {
2803                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2804                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2805                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2806                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2807                 }
2808
2809                 // Special SPIR-V code for FConvert-case for 16-bit floats
2810                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2811                 {
2812                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2813                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2814                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2815                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2816                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2817                 }
2818
2819                 spec.assembly = shaderTemplate.specialize(specializations);
2820                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2821                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2822                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2823                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2824                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2825
2826                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2827         }
2828
2829         ComputeShaderSpec                               spec;
2830
2831         spec.assembly =
2832                 string(getComputeAsmShaderPreamble()) +
2833
2834                 "OpName %main           \"main\"\n"
2835                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2836
2837                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2838                 "OpDecorate %sc_0  SpecId 0\n"
2839                 "OpDecorate %sc_1  SpecId 1\n"
2840                 "OpDecorate %sc_2  SpecId 2\n"
2841                 "OpDecorate %i32arr ArrayStride 4\n"
2842
2843                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2844
2845                 "%ivec3       = OpTypeVector %i32 3\n"
2846                 "%buf         = OpTypeStruct %i32arr\n"
2847                 "%bufptr      = OpTypePointer Uniform %buf\n"
2848                 "%indata      = OpVariable %bufptr Uniform\n"
2849                 "%outdata     = OpVariable %bufptr Uniform\n"
2850
2851                 "%id          = OpVariable %uvec3ptr Input\n"
2852                 "%zero        = OpConstant %i32 0\n"
2853                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2854                 "%vec3_undef  = OpUndef %ivec3\n"
2855
2856                 "%sc_0        = OpSpecConstant %i32 0\n"
2857                 "%sc_1        = OpSpecConstant %i32 0\n"
2858                 "%sc_2        = OpSpecConstant %i32 0\n"
2859                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2860                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2861                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2862                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2863                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2864                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2865                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2866                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2867                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2868                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2869                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2870                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2871                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2872
2873                 "%main      = OpFunction %void None %voidf\n"
2874                 "%label     = OpLabel\n"
2875                 "%idval     = OpLoad %uvec3 %id\n"
2876                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2877                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2878                 "%inval     = OpLoad %i32 %inloc\n"
2879                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2880                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2881                 "             OpStore %outloc %final\n"
2882                 "             OpReturn\n"
2883                 "             OpFunctionEnd\n";
2884         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2885         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2886         spec.numWorkGroups = IVec3(numElements, 1, 1);
2887         spec.specConstants.append<deInt32>(123);
2888         spec.specConstants.append<deInt32>(56);
2889         spec.specConstants.append<deInt32>(-77);
2890
2891         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2892
2893         return group.release();
2894 }
2895
2896 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2897 {
2898         ComputeShaderSpec       specInt;
2899         ComputeShaderSpec       specFloat;
2900         ComputeShaderSpec       specFloat16;
2901         ComputeShaderSpec       specVec3;
2902         ComputeShaderSpec       specMat4;
2903         ComputeShaderSpec       specArray;
2904         ComputeShaderSpec       specStruct;
2905         de::Random                      rnd                             (deStringHash(group->getName()));
2906         const int                       numElements             = 100;
2907         vector<float>           inputFloats             (numElements, 0);
2908         vector<float>           outputFloats    (numElements, 0);
2909         vector<deFloat16>       inputFloats16   (numElements, 0);
2910         vector<deFloat16>       outputFloats16  (numElements, 0);
2911
2912         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2913
2914         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2915         floorAll(inputFloats);
2916
2917         for (size_t ndx = 0; ndx < numElements; ++ndx)
2918         {
2919                 // Just check if the value is positive or not
2920                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2921         }
2922
2923         for (size_t ndx = 0; ndx < numElements; ++ndx)
2924         {
2925                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2926                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2927         }
2928
2929         // All of the tests are of the form:
2930         //
2931         // testtype r
2932         //
2933         // if (inputdata > 0)
2934         //   r = 1
2935         // else
2936         //   r = -1
2937         //
2938         // return (float)r
2939
2940         specFloat.assembly =
2941                 string(getComputeAsmShaderPreamble()) +
2942
2943                 "OpSource GLSL 430\n"
2944                 "OpName %main \"main\"\n"
2945                 "OpName %id \"gl_GlobalInvocationID\"\n"
2946
2947                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2948
2949                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2950
2951                 "%id = OpVariable %uvec3ptr Input\n"
2952                 "%zero       = OpConstant %i32 0\n"
2953                 "%float_0    = OpConstant %f32 0.0\n"
2954                 "%float_1    = OpConstant %f32 1.0\n"
2955                 "%float_n1   = OpConstant %f32 -1.0\n"
2956
2957                 "%main     = OpFunction %void None %voidf\n"
2958                 "%entry    = OpLabel\n"
2959                 "%idval    = OpLoad %uvec3 %id\n"
2960                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2961                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2962                 "%inval    = OpLoad %f32 %inloc\n"
2963
2964                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2965                 "            OpSelectionMerge %cm None\n"
2966                 "            OpBranchConditional %comp %tb %fb\n"
2967                 "%tb       = OpLabel\n"
2968                 "            OpBranch %cm\n"
2969                 "%fb       = OpLabel\n"
2970                 "            OpBranch %cm\n"
2971                 "%cm       = OpLabel\n"
2972                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2973
2974                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2975                 "            OpStore %outloc %res\n"
2976                 "            OpReturn\n"
2977
2978                 "            OpFunctionEnd\n";
2979         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2980         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2981         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2982
2983         specFloat16.assembly =
2984                 "OpCapability Shader\n"
2985                 "OpCapability StorageUniformBufferBlock16\n"
2986                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
2987                 "OpMemoryModel Logical GLSL450\n"
2988                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2989                 "OpExecutionMode %main LocalSize 1 1 1\n"
2990
2991                 "OpSource GLSL 430\n"
2992                 "OpName %main \"main\"\n"
2993                 "OpName %id \"gl_GlobalInvocationID\"\n"
2994
2995                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2996
2997                 "OpDecorate %buf BufferBlock\n"
2998                 "OpDecorate %indata DescriptorSet 0\n"
2999                 "OpDecorate %indata Binding 0\n"
3000                 "OpDecorate %outdata DescriptorSet 0\n"
3001                 "OpDecorate %outdata Binding 1\n"
3002                 "OpDecorate %f16arr ArrayStride 2\n"
3003                 "OpMemberDecorate %buf 0 Offset 0\n"
3004
3005                 "%f16      = OpTypeFloat 16\n"
3006                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3007                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3008
3009                 + string(getComputeAsmCommonTypes()) +
3010
3011                 "%buf      = OpTypeStruct %f16arr\n"
3012                 "%bufptr   = OpTypePointer Uniform %buf\n"
3013                 "%indata   = OpVariable %bufptr Uniform\n"
3014                 "%outdata  = OpVariable %bufptr Uniform\n"
3015
3016                 "%id       = OpVariable %uvec3ptr Input\n"
3017                 "%zero     = OpConstant %i32 0\n"
3018                 "%float_0  = OpConstant %f16 0.0\n"
3019                 "%float_1  = OpConstant %f16 1.0\n"
3020                 "%float_n1 = OpConstant %f16 -1.0\n"
3021
3022                 "%main     = OpFunction %void None %voidf\n"
3023                 "%entry    = OpLabel\n"
3024                 "%idval    = OpLoad %uvec3 %id\n"
3025                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3026                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3027                 "%inval    = OpLoad %f16 %inloc\n"
3028
3029                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3030                 "            OpSelectionMerge %cm None\n"
3031                 "            OpBranchConditional %comp %tb %fb\n"
3032                 "%tb       = OpLabel\n"
3033                 "            OpBranch %cm\n"
3034                 "%fb       = OpLabel\n"
3035                 "            OpBranch %cm\n"
3036                 "%cm       = OpLabel\n"
3037                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3038
3039                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3040                 "            OpStore %outloc %res\n"
3041                 "            OpReturn\n"
3042
3043                 "            OpFunctionEnd\n";
3044         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3045         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3046         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3047         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3048         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3049
3050         specMat4.assembly =
3051                 string(getComputeAsmShaderPreamble()) +
3052
3053                 "OpSource GLSL 430\n"
3054                 "OpName %main \"main\"\n"
3055                 "OpName %id \"gl_GlobalInvocationID\"\n"
3056
3057                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3058
3059                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3060
3061                 "%id = OpVariable %uvec3ptr Input\n"
3062                 "%v4f32      = OpTypeVector %f32 4\n"
3063                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3064                 "%zero       = OpConstant %i32 0\n"
3065                 "%float_0    = OpConstant %f32 0.0\n"
3066                 "%float_1    = OpConstant %f32 1.0\n"
3067                 "%float_n1   = OpConstant %f32 -1.0\n"
3068                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3069                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3070                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3071                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3072                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3073                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3074                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3075                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3076                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3077                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3078
3079                 "%main     = OpFunction %void None %voidf\n"
3080                 "%entry    = OpLabel\n"
3081                 "%idval    = OpLoad %uvec3 %id\n"
3082                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3083                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3084                 "%inval    = OpLoad %f32 %inloc\n"
3085
3086                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3087                 "            OpSelectionMerge %cm None\n"
3088                 "            OpBranchConditional %comp %tb %fb\n"
3089                 "%tb       = OpLabel\n"
3090                 "            OpBranch %cm\n"
3091                 "%fb       = OpLabel\n"
3092                 "            OpBranch %cm\n"
3093                 "%cm       = OpLabel\n"
3094                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3095                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3096
3097                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3098                 "            OpStore %outloc %res\n"
3099                 "            OpReturn\n"
3100
3101                 "            OpFunctionEnd\n";
3102         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3103         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3104         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3105
3106         specVec3.assembly =
3107                 string(getComputeAsmShaderPreamble()) +
3108
3109                 "OpSource GLSL 430\n"
3110                 "OpName %main \"main\"\n"
3111                 "OpName %id \"gl_GlobalInvocationID\"\n"
3112
3113                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3114
3115                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3116
3117                 "%id = OpVariable %uvec3ptr Input\n"
3118                 "%zero       = OpConstant %i32 0\n"
3119                 "%float_0    = OpConstant %f32 0.0\n"
3120                 "%float_1    = OpConstant %f32 1.0\n"
3121                 "%float_n1   = OpConstant %f32 -1.0\n"
3122                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3123                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3124
3125                 "%main     = OpFunction %void None %voidf\n"
3126                 "%entry    = OpLabel\n"
3127                 "%idval    = OpLoad %uvec3 %id\n"
3128                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3129                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3130                 "%inval    = OpLoad %f32 %inloc\n"
3131
3132                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3133                 "            OpSelectionMerge %cm None\n"
3134                 "            OpBranchConditional %comp %tb %fb\n"
3135                 "%tb       = OpLabel\n"
3136                 "            OpBranch %cm\n"
3137                 "%fb       = OpLabel\n"
3138                 "            OpBranch %cm\n"
3139                 "%cm       = OpLabel\n"
3140                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3141                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3142
3143                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3144                 "            OpStore %outloc %res\n"
3145                 "            OpReturn\n"
3146
3147                 "            OpFunctionEnd\n";
3148         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3149         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3150         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3151
3152         specInt.assembly =
3153                 string(getComputeAsmShaderPreamble()) +
3154
3155                 "OpSource GLSL 430\n"
3156                 "OpName %main \"main\"\n"
3157                 "OpName %id \"gl_GlobalInvocationID\"\n"
3158
3159                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3160
3161                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3162
3163                 "%id = OpVariable %uvec3ptr Input\n"
3164                 "%zero       = OpConstant %i32 0\n"
3165                 "%float_0    = OpConstant %f32 0.0\n"
3166                 "%i1         = OpConstant %i32 1\n"
3167                 "%i2         = OpConstant %i32 -1\n"
3168
3169                 "%main     = OpFunction %void None %voidf\n"
3170                 "%entry    = OpLabel\n"
3171                 "%idval    = OpLoad %uvec3 %id\n"
3172                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3173                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3174                 "%inval    = OpLoad %f32 %inloc\n"
3175
3176                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3177                 "            OpSelectionMerge %cm None\n"
3178                 "            OpBranchConditional %comp %tb %fb\n"
3179                 "%tb       = OpLabel\n"
3180                 "            OpBranch %cm\n"
3181                 "%fb       = OpLabel\n"
3182                 "            OpBranch %cm\n"
3183                 "%cm       = OpLabel\n"
3184                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3185                 "%res      = OpConvertSToF %f32 %ires\n"
3186
3187                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3188                 "            OpStore %outloc %res\n"
3189                 "            OpReturn\n"
3190
3191                 "            OpFunctionEnd\n";
3192         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3193         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3194         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3195
3196         specArray.assembly =
3197                 string(getComputeAsmShaderPreamble()) +
3198
3199                 "OpSource GLSL 430\n"
3200                 "OpName %main \"main\"\n"
3201                 "OpName %id \"gl_GlobalInvocationID\"\n"
3202
3203                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3204
3205                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3206
3207                 "%id = OpVariable %uvec3ptr Input\n"
3208                 "%zero       = OpConstant %i32 0\n"
3209                 "%u7         = OpConstant %u32 7\n"
3210                 "%float_0    = OpConstant %f32 0.0\n"
3211                 "%float_1    = OpConstant %f32 1.0\n"
3212                 "%float_n1   = OpConstant %f32 -1.0\n"
3213                 "%f32a7      = OpTypeArray %f32 %u7\n"
3214                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3215                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3216                 "%main     = OpFunction %void None %voidf\n"
3217                 "%entry    = OpLabel\n"
3218                 "%idval    = OpLoad %uvec3 %id\n"
3219                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3220                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3221                 "%inval    = OpLoad %f32 %inloc\n"
3222
3223                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3224                 "            OpSelectionMerge %cm None\n"
3225                 "            OpBranchConditional %comp %tb %fb\n"
3226                 "%tb       = OpLabel\n"
3227                 "            OpBranch %cm\n"
3228                 "%fb       = OpLabel\n"
3229                 "            OpBranch %cm\n"
3230                 "%cm       = OpLabel\n"
3231                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3232                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3233
3234                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3235                 "            OpStore %outloc %res\n"
3236                 "            OpReturn\n"
3237
3238                 "            OpFunctionEnd\n";
3239         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3240         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3241         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3242
3243         specStruct.assembly =
3244                 string(getComputeAsmShaderPreamble()) +
3245
3246                 "OpSource GLSL 430\n"
3247                 "OpName %main \"main\"\n"
3248                 "OpName %id \"gl_GlobalInvocationID\"\n"
3249
3250                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3251
3252                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3253
3254                 "%id = OpVariable %uvec3ptr Input\n"
3255                 "%zero       = OpConstant %i32 0\n"
3256                 "%float_0    = OpConstant %f32 0.0\n"
3257                 "%float_1    = OpConstant %f32 1.0\n"
3258                 "%float_n1   = OpConstant %f32 -1.0\n"
3259
3260                 "%v2f32      = OpTypeVector %f32 2\n"
3261                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3262                 "%Data       = OpTypeStruct %Data2 %f32\n"
3263
3264                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3265                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3266                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3267                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3268                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3269                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3270
3271                 "%main     = OpFunction %void None %voidf\n"
3272                 "%entry    = OpLabel\n"
3273                 "%idval    = OpLoad %uvec3 %id\n"
3274                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3275                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3276                 "%inval    = OpLoad %f32 %inloc\n"
3277
3278                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3279                 "            OpSelectionMerge %cm None\n"
3280                 "            OpBranchConditional %comp %tb %fb\n"
3281                 "%tb       = OpLabel\n"
3282                 "            OpBranch %cm\n"
3283                 "%fb       = OpLabel\n"
3284                 "            OpBranch %cm\n"
3285                 "%cm       = OpLabel\n"
3286                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3287                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3288
3289                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3290                 "            OpStore %outloc %res\n"
3291                 "            OpReturn\n"
3292
3293                 "            OpFunctionEnd\n";
3294         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3295         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3296         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3297
3298         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3299         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3305 }
3306
3307 string generateConstantDefinitions (int count)
3308 {
3309         std::ostringstream      r;
3310         for (int i = 0; i < count; i++)
3311                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3312         r << "\n";
3313         return r.str();
3314 }
3315
3316 string generateSwitchCases (int count)
3317 {
3318         std::ostringstream      r;
3319         for (int i = 0; i < count; i++)
3320                 r << " " << i << " %case" << i;
3321         r << "\n";
3322         return r.str();
3323 }
3324
3325 string generateSwitchTargets (int count)
3326 {
3327         std::ostringstream      r;
3328         for (int i = 0; i < count; i++)
3329                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3330         r << "\n";
3331         return r.str();
3332 }
3333
3334 string generateOpPhiParams (int count)
3335 {
3336         std::ostringstream      r;
3337         for (int i = 0; i < count; i++)
3338                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3339         r << "\n";
3340         return r.str();
3341 }
3342
3343 string generateIntWidth (int value)
3344 {
3345         std::ostringstream      r;
3346         r << value;
3347         return r.str();
3348 }
3349
3350 // Expand input string by injecting "ABC" between the input
3351 // string characters. The acc/add/treshold parameters are used
3352 // to skip some of the injections to make the result less
3353 // uniform (and a lot shorter).
3354 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3355 {
3356         std::ostringstream      res;
3357         const char*                     p = s.c_str();
3358
3359         while (*p)
3360         {
3361                 res << *p;
3362                 acc += add;
3363                 if (acc > treshold)
3364                 {
3365                         acc -= treshold;
3366                         res << "ABC";
3367                 }
3368                 p++;
3369         }
3370         return res.str();
3371 }
3372
3373 // Calculate expected result based on the code string
3374 float calcOpPhiCase5 (float val, const string& s)
3375 {
3376         const char*             p               = s.c_str();
3377         float                   x[8];
3378         bool                    b[8];
3379         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3380         const float             v               = deFloatAbs(val);
3381         float                   res             = 0;
3382         int                             depth   = -1;
3383         int                             skip    = 0;
3384
3385         for (int i = 7; i >= 0; --i)
3386                 x[i] = std::fmod((float)v, (float)(2 << i));
3387         for (int i = 7; i >= 0; --i)
3388                 b[i] = x[i] > tv[i];
3389
3390         while (*p)
3391         {
3392                 if (*p == 'A')
3393                 {
3394                         depth++;
3395                         if (skip == 0 && b[depth])
3396                         {
3397                                 res++;
3398                         }
3399                         else
3400                                 skip++;
3401                 }
3402                 if (*p == 'B')
3403                 {
3404                         if (skip)
3405                                 skip--;
3406                         if (b[depth] || skip)
3407                                 skip++;
3408                 }
3409                 if (*p == 'C')
3410                 {
3411                         depth--;
3412                         if (skip)
3413                                 skip--;
3414                 }
3415                 p++;
3416         }
3417         return res;
3418 }
3419
3420 // In the code string, the letters represent the following:
3421 //
3422 // A:
3423 //     if (certain bit is set)
3424 //     {
3425 //       result++;
3426 //
3427 // B:
3428 //     } else {
3429 //
3430 // C:
3431 //     }
3432 //
3433 // examples:
3434 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3435 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3436 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3437 //
3438 // Code generation gets a bit complicated due to the else-branches,
3439 // which do not generate new values. Thus, the generator needs to
3440 // keep track of the previous variable change seen by the else
3441 // branch.
3442 string generateOpPhiCase5 (const string& s)
3443 {
3444         std::stack<int>                         idStack;
3445         std::stack<std::string>         value;
3446         std::stack<std::string>         valueLabel;
3447         std::stack<std::string>         mergeLeft;
3448         std::stack<std::string>         mergeRight;
3449         std::ostringstream                      res;
3450         const char*                                     p                       = s.c_str();
3451         int                                                     depth           = -1;
3452         int                                                     currId          = 0;
3453         int                                                     iter            = 0;
3454
3455         idStack.push(-1);
3456         value.push("%f32_0");
3457         valueLabel.push("%f32_0 %entry");
3458
3459         while (*p)
3460         {
3461                 if (*p == 'A')
3462                 {
3463                         depth++;
3464                         currId = iter;
3465                         idStack.push(currId);
3466                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3467                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3468                         res << "%t" << currId << " = OpLabel\n";
3469                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3470                         std::ostringstream tag;
3471                         tag << "%rt" << currId;
3472                         value.push(tag.str());
3473                         tag << " %t" << currId;
3474                         valueLabel.push(tag.str());
3475                 }
3476
3477                 if (*p == 'B')
3478                 {
3479                         mergeLeft.push(valueLabel.top());
3480                         value.pop();
3481                         valueLabel.pop();
3482                         res << "\tOpBranch %m" << currId << "\n";
3483                         res << "%f" << currId << " = OpLabel\n";
3484                         std::ostringstream tag;
3485                         tag << value.top() << " %f" << currId;
3486                         valueLabel.pop();
3487                         valueLabel.push(tag.str());
3488                 }
3489
3490                 if (*p == 'C')
3491                 {
3492                         mergeRight.push(valueLabel.top());
3493                         res << "\tOpBranch %m" << currId << "\n";
3494                         res << "%m" << currId << " = OpLabel\n";
3495                         if (*(p + 1) == 0)
3496                                 res << "%res"; // last result goes to %res
3497                         else
3498                                 res << "%rm" << currId;
3499                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3500                         std::ostringstream tag;
3501                         tag << "%rm" << currId;
3502                         value.pop();
3503                         value.push(tag.str());
3504                         tag << " %m" << currId;
3505                         valueLabel.pop();
3506                         valueLabel.push(tag.str());
3507                         mergeLeft.pop();
3508                         mergeRight.pop();
3509                         depth--;
3510                         idStack.pop();
3511                         currId = idStack.top();
3512                 }
3513                 p++;
3514                 iter++;
3515         }
3516         return res.str();
3517 }
3518
3519 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3520 {
3521         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3522         ComputeShaderSpec                               spec1;
3523         ComputeShaderSpec                               spec2;
3524         ComputeShaderSpec                               spec3;
3525         ComputeShaderSpec                               spec4;
3526         ComputeShaderSpec                               spec5;
3527         de::Random                                              rnd                             (deStringHash(group->getName()));
3528         const int                                               numElements             = 100;
3529         vector<float>                                   inputFloats             (numElements, 0);
3530         vector<float>                                   outputFloats1   (numElements, 0);
3531         vector<float>                                   outputFloats2   (numElements, 0);
3532         vector<float>                                   outputFloats3   (numElements, 0);
3533         vector<float>                                   outputFloats4   (numElements, 0);
3534         vector<float>                                   outputFloats5   (numElements, 0);
3535         std::string                                             codestring              = "ABC";
3536         const int                                               test4Width              = 1024;
3537
3538         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3539         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3540         // shader code.
3541         for (int i = 0, acc = 0; i < 9; i++)
3542                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3543
3544         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3545
3546         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3547         floorAll(inputFloats);
3548
3549         for (size_t ndx = 0; ndx < numElements; ++ndx)
3550         {
3551                 switch (ndx % 3)
3552                 {
3553                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3554                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3555                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3556                         default:        break;
3557                 }
3558                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3559                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3560
3561                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3562                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3563
3564                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3565         }
3566
3567         spec1.assembly =
3568                 string(getComputeAsmShaderPreamble()) +
3569
3570                 "OpSource GLSL 430\n"
3571                 "OpName %main \"main\"\n"
3572                 "OpName %id \"gl_GlobalInvocationID\"\n"
3573
3574                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3575
3576                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3577
3578                 "%id = OpVariable %uvec3ptr Input\n"
3579                 "%zero       = OpConstant %i32 0\n"
3580                 "%three      = OpConstant %u32 3\n"
3581                 "%constf5p5  = OpConstant %f32 5.5\n"
3582                 "%constf20p5 = OpConstant %f32 20.5\n"
3583                 "%constf1p75 = OpConstant %f32 1.75\n"
3584                 "%constf8p5  = OpConstant %f32 8.5\n"
3585                 "%constf6p5  = OpConstant %f32 6.5\n"
3586
3587                 "%main     = OpFunction %void None %voidf\n"
3588                 "%entry    = OpLabel\n"
3589                 "%idval    = OpLoad %uvec3 %id\n"
3590                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3591                 "%selector = OpUMod %u32 %x %three\n"
3592                 "            OpSelectionMerge %phi None\n"
3593                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3594
3595                 // Case 1 before OpPhi.
3596                 "%case1    = OpLabel\n"
3597                 "            OpBranch %phi\n"
3598
3599                 "%default  = OpLabel\n"
3600                 "            OpUnreachable\n"
3601
3602                 "%phi      = OpLabel\n"
3603                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3604                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3605                 "%inval    = OpLoad %f32 %inloc\n"
3606                 "%add      = OpFAdd %f32 %inval %operand\n"
3607                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3608                 "            OpStore %outloc %add\n"
3609                 "            OpReturn\n"
3610
3611                 // Case 0 after OpPhi.
3612                 "%case0    = OpLabel\n"
3613                 "            OpBranch %phi\n"
3614
3615
3616                 // Case 2 after OpPhi.
3617                 "%case2    = OpLabel\n"
3618                 "            OpBranch %phi\n"
3619
3620                 "            OpFunctionEnd\n";
3621         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3622         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3623         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3624
3625         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3626
3627         spec2.assembly =
3628                 string(getComputeAsmShaderPreamble()) +
3629
3630                 "OpName %main \"main\"\n"
3631                 "OpName %id \"gl_GlobalInvocationID\"\n"
3632
3633                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3634
3635                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3636
3637                 "%id         = OpVariable %uvec3ptr Input\n"
3638                 "%zero       = OpConstant %i32 0\n"
3639                 "%one        = OpConstant %i32 1\n"
3640                 "%three      = OpConstant %i32 3\n"
3641                 "%constf6p5  = OpConstant %f32 6.5\n"
3642
3643                 "%main       = OpFunction %void None %voidf\n"
3644                 "%entry      = OpLabel\n"
3645                 "%idval      = OpLoad %uvec3 %id\n"
3646                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3647                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3648                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3649                 "%inval      = OpLoad %f32 %inloc\n"
3650                 "              OpBranch %phi\n"
3651
3652                 "%phi        = OpLabel\n"
3653                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3654                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3655                 "%step_next  = OpIAdd %i32 %step %one\n"
3656                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3657                 "%still_loop = OpSLessThan %bool %step %three\n"
3658                 "              OpLoopMerge %exit %phi None\n"
3659                 "              OpBranchConditional %still_loop %phi %exit\n"
3660
3661                 "%exit       = OpLabel\n"
3662                 "              OpStore %outloc %accum\n"
3663                 "              OpReturn\n"
3664                 "              OpFunctionEnd\n";
3665         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3666         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3667         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3668
3669         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3670
3671         spec3.assembly =
3672                 string(getComputeAsmShaderPreamble()) +
3673
3674                 "OpName %main \"main\"\n"
3675                 "OpName %id \"gl_GlobalInvocationID\"\n"
3676
3677                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3678
3679                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3680
3681                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3682                 "%id         = OpVariable %uvec3ptr Input\n"
3683                 "%true       = OpConstantTrue %bool\n"
3684                 "%false      = OpConstantFalse %bool\n"
3685                 "%zero       = OpConstant %i32 0\n"
3686                 "%constf8p5  = OpConstant %f32 8.5\n"
3687
3688                 "%main       = OpFunction %void None %voidf\n"
3689                 "%entry      = OpLabel\n"
3690                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3691                 "%idval      = OpLoad %uvec3 %id\n"
3692                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3693                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3694                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3695                 "%a_init     = OpLoad %f32 %inloc\n"
3696                 "%b_init     = OpLoad %f32 %b\n"
3697                 "              OpBranch %phi\n"
3698
3699                 "%phi        = OpLabel\n"
3700                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3701                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3702                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3703                 "              OpLoopMerge %exit %phi None\n"
3704                 "              OpBranchConditional %still_loop %phi %exit\n"
3705
3706                 "%exit       = OpLabel\n"
3707                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3708                 "              OpStore %outloc %sub\n"
3709                 "              OpReturn\n"
3710                 "              OpFunctionEnd\n";
3711         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3712         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3713         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3714
3715         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3716
3717         spec4.assembly =
3718                 "OpCapability Shader\n"
3719                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3720                 "OpMemoryModel Logical GLSL450\n"
3721                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3722                 "OpExecutionMode %main LocalSize 1 1 1\n"
3723
3724                 "OpSource GLSL 430\n"
3725                 "OpName %main \"main\"\n"
3726                 "OpName %id \"gl_GlobalInvocationID\"\n"
3727
3728                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3729
3730                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3731
3732                 "%id       = OpVariable %uvec3ptr Input\n"
3733                 "%zero     = OpConstant %i32 0\n"
3734                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3735
3736                 + generateConstantDefinitions(test4Width) +
3737
3738                 "%main     = OpFunction %void None %voidf\n"
3739                 "%entry    = OpLabel\n"
3740                 "%idval    = OpLoad %uvec3 %id\n"
3741                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3742                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3743                 "%inval    = OpLoad %f32 %inloc\n"
3744                 "%xf       = OpConvertUToF %f32 %x\n"
3745                 "%xm       = OpFMul %f32 %xf %inval\n"
3746                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3747                 "%xi       = OpConvertFToU %u32 %xa\n"
3748                 "%selector = OpUMod %u32 %xi %cimod\n"
3749                 "            OpSelectionMerge %phi None\n"
3750                 "            OpSwitch %selector %default "
3751
3752                 + generateSwitchCases(test4Width) +
3753
3754                 "%default  = OpLabel\n"
3755                 "            OpUnreachable\n"
3756
3757                 + generateSwitchTargets(test4Width) +
3758
3759                 "%phi      = OpLabel\n"
3760                 "%result   = OpPhi %f32"
3761
3762                 + generateOpPhiParams(test4Width) +
3763
3764                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3765                 "            OpStore %outloc %result\n"
3766                 "            OpReturn\n"
3767
3768                 "            OpFunctionEnd\n";
3769         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3770         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3771         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3772
3773         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3774
3775         spec5.assembly =
3776                 "OpCapability Shader\n"
3777                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3778                 "OpMemoryModel Logical GLSL450\n"
3779                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3780                 "OpExecutionMode %main LocalSize 1 1 1\n"
3781                 "%code     = OpString \"" + codestring + "\"\n"
3782
3783                 "OpSource GLSL 430\n"
3784                 "OpName %main \"main\"\n"
3785                 "OpName %id \"gl_GlobalInvocationID\"\n"
3786
3787                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3788
3789                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3790
3791                 "%id       = OpVariable %uvec3ptr Input\n"
3792                 "%zero     = OpConstant %i32 0\n"
3793                 "%f32_0    = OpConstant %f32 0.0\n"
3794                 "%f32_0_5  = OpConstant %f32 0.5\n"
3795                 "%f32_1    = OpConstant %f32 1.0\n"
3796                 "%f32_1_5  = OpConstant %f32 1.5\n"
3797                 "%f32_2    = OpConstant %f32 2.0\n"
3798                 "%f32_3_5  = OpConstant %f32 3.5\n"
3799                 "%f32_4    = OpConstant %f32 4.0\n"
3800                 "%f32_7_5  = OpConstant %f32 7.5\n"
3801                 "%f32_8    = OpConstant %f32 8.0\n"
3802                 "%f32_15_5 = OpConstant %f32 15.5\n"
3803                 "%f32_16   = OpConstant %f32 16.0\n"
3804                 "%f32_31_5 = OpConstant %f32 31.5\n"
3805                 "%f32_32   = OpConstant %f32 32.0\n"
3806                 "%f32_63_5 = OpConstant %f32 63.5\n"
3807                 "%f32_64   = OpConstant %f32 64.0\n"
3808                 "%f32_127_5 = OpConstant %f32 127.5\n"
3809                 "%f32_128  = OpConstant %f32 128.0\n"
3810                 "%f32_256  = OpConstant %f32 256.0\n"
3811
3812                 "%main     = OpFunction %void None %voidf\n"
3813                 "%entry    = OpLabel\n"
3814                 "%idval    = OpLoad %uvec3 %id\n"
3815                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3816                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3817                 "%inval    = OpLoad %f32 %inloc\n"
3818
3819                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3820                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3821                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3822                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3823                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3824                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3825                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3826                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3827                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3828
3829                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3830                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3831                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3832                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3833                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3834                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3835                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3836                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3837
3838                 + generateOpPhiCase5(codestring) +
3839
3840                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3841                 "            OpStore %outloc %res\n"
3842                 "            OpReturn\n"
3843
3844                 "            OpFunctionEnd\n";
3845         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3846         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3847         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3848
3849         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3850
3851         createOpPhiVartypeTests(group, testCtx);
3852
3853         return group.release();
3854 }
3855
3856 // Assembly code used for testing block order is based on GLSL source code:
3857 //
3858 // #version 430
3859 //
3860 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3861 //   float elements[];
3862 // } input_data;
3863 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3864 //   float elements[];
3865 // } output_data;
3866 //
3867 // void main() {
3868 //   uint x = gl_GlobalInvocationID.x;
3869 //   output_data.elements[x] = input_data.elements[x];
3870 //   if (x > uint(50)) {
3871 //     switch (x % uint(3)) {
3872 //       case 0: output_data.elements[x] += 1.5f; break;
3873 //       case 1: output_data.elements[x] += 42.f; break;
3874 //       case 2: output_data.elements[x] -= 27.f; break;
3875 //       default: break;
3876 //     }
3877 //   } else {
3878 //     output_data.elements[x] = -input_data.elements[x];
3879 //   }
3880 // }
3881 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3882 {
3883         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3884         ComputeShaderSpec                               spec;
3885         de::Random                                              rnd                             (deStringHash(group->getName()));
3886         const int                                               numElements             = 100;
3887         vector<float>                                   inputFloats             (numElements, 0);
3888         vector<float>                                   outputFloats    (numElements, 0);
3889
3890         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3891
3892         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3893         floorAll(inputFloats);
3894
3895         for (size_t ndx = 0; ndx <= 50; ++ndx)
3896                 outputFloats[ndx] = -inputFloats[ndx];
3897
3898         for (size_t ndx = 51; ndx < numElements; ++ndx)
3899         {
3900                 switch (ndx % 3)
3901                 {
3902                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3903                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3904                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3905                         default:        break;
3906                 }
3907         }
3908
3909         spec.assembly =
3910                 string(getComputeAsmShaderPreamble()) +
3911
3912                 "OpSource GLSL 430\n"
3913                 "OpName %main \"main\"\n"
3914                 "OpName %id \"gl_GlobalInvocationID\"\n"
3915
3916                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3917
3918                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3919
3920                 "%u32ptr       = OpTypePointer Function %u32\n"
3921                 "%u32ptr_input = OpTypePointer Input %u32\n"
3922
3923                 + string(getComputeAsmInputOutputBuffer()) +
3924
3925                 "%id        = OpVariable %uvec3ptr Input\n"
3926                 "%zero      = OpConstant %i32 0\n"
3927                 "%const3    = OpConstant %u32 3\n"
3928                 "%const50   = OpConstant %u32 50\n"
3929                 "%constf1p5 = OpConstant %f32 1.5\n"
3930                 "%constf27  = OpConstant %f32 27.0\n"
3931                 "%constf42  = OpConstant %f32 42.0\n"
3932
3933                 "%main = OpFunction %void None %voidf\n"
3934
3935                 // entry block.
3936                 "%entry    = OpLabel\n"
3937
3938                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3939                 "%xvar     = OpVariable %u32ptr Function\n"
3940                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3941                 "%x        = OpLoad %u32 %xptr\n"
3942                 "            OpStore %xvar %x\n"
3943
3944                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3945                 "            OpSelectionMerge %if_merge None\n"
3946                 "            OpBranchConditional %cmp %if_true %if_false\n"
3947
3948                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3949                 "%if_false = OpLabel\n"
3950                 "%x_f      = OpLoad %u32 %xvar\n"
3951                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3952                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3953                 "%negate   = OpFNegate %f32 %inval_f\n"
3954                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3955                 "            OpStore %outloc_f %negate\n"
3956                 "            OpBranch %if_merge\n"
3957
3958                 // Merge block for if-statement: placed in the middle of true and false branch.
3959                 "%if_merge = OpLabel\n"
3960                 "            OpReturn\n"
3961
3962                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3963                 "%if_true  = OpLabel\n"
3964                 "%xval_t   = OpLoad %u32 %xvar\n"
3965                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3966                 "            OpSelectionMerge %switch_merge None\n"
3967                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3968
3969                 // Merge block for switch-statement: placed before the case
3970                 // bodies.  But it must follow OpSwitch which dominates it.
3971                 "%switch_merge = OpLabel\n"
3972                 "                OpBranch %if_merge\n"
3973
3974                 // Case 1 for switch-statement: placed before case 0.
3975                 // It must follow the OpSwitch that dominates it.
3976                 "%case1    = OpLabel\n"
3977                 "%x_1      = OpLoad %u32 %xvar\n"
3978                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3979                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3980                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3981                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3982                 "            OpStore %outloc_1 %addf42\n"
3983                 "            OpBranch %switch_merge\n"
3984
3985                 // Case 2 for switch-statement.
3986                 "%case2    = OpLabel\n"
3987                 "%x_2      = OpLoad %u32 %xvar\n"
3988                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3989                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3990                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3991                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3992                 "            OpStore %outloc_2 %subf27\n"
3993                 "            OpBranch %switch_merge\n"
3994
3995                 // Default case for switch-statement: placed in the middle of normal cases.
3996                 "%default = OpLabel\n"
3997                 "           OpBranch %switch_merge\n"
3998
3999                 // Case 0 for switch-statement: out of order.
4000                 "%case0    = OpLabel\n"
4001                 "%x_0      = OpLoad %u32 %xvar\n"
4002                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4003                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4004                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4005                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4006                 "            OpStore %outloc_0 %addf1p5\n"
4007                 "            OpBranch %switch_merge\n"
4008
4009                 "            OpFunctionEnd\n";
4010         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4011         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4012         spec.numWorkGroups = IVec3(numElements, 1, 1);
4013
4014         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4015
4016         return group.release();
4017 }
4018
4019 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4020 {
4021         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4022         ComputeShaderSpec                               spec1;
4023         ComputeShaderSpec                               spec2;
4024         de::Random                                              rnd                             (deStringHash(group->getName()));
4025         const int                                               numElements             = 100;
4026         vector<float>                                   inputFloats             (numElements, 0);
4027         vector<float>                                   outputFloats1   (numElements, 0);
4028         vector<float>                                   outputFloats2   (numElements, 0);
4029         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4030
4031         for (size_t ndx = 0; ndx < numElements; ++ndx)
4032         {
4033                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4034                 outputFloats2[ndx] = -inputFloats[ndx];
4035         }
4036
4037         const string assembly(
4038                 "OpCapability Shader\n"
4039                 "OpMemoryModel Logical GLSL450\n"
4040                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4041                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4042                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4043                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4044                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4045                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4046
4047                 "OpName %comp_main1              \"entrypoint1\"\n"
4048                 "OpName %comp_main2              \"entrypoint2\"\n"
4049                 "OpName %vert_main               \"entrypoint2\"\n"
4050                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4051                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4052                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4053                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4054                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4055                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4056                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4057
4058                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4059                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4060                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4061                 "OpDecorate %vert_builtin_st         Block\n"
4062                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4063                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4064                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4065
4066                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4067
4068                 "%zero       = OpConstant %i32 0\n"
4069                 "%one        = OpConstant %u32 1\n"
4070                 "%c_f32_1    = OpConstant %f32 1\n"
4071
4072                 "%i32inputptr         = OpTypePointer Input %i32\n"
4073                 "%vec4                = OpTypeVector %f32 4\n"
4074                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4075                 "%f32arr1             = OpTypeArray %f32 %one\n"
4076                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4077                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4078                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4079
4080                 "%id         = OpVariable %uvec3ptr Input\n"
4081                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4082                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4083                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4084
4085                 // gl_Position = vec4(1.);
4086                 "%vert_main  = OpFunction %void None %voidf\n"
4087                 "%vert_entry = OpLabel\n"
4088                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4089                 "              OpStore %position %c_vec4_1\n"
4090                 "              OpReturn\n"
4091                 "              OpFunctionEnd\n"
4092
4093                 // Double inputs.
4094                 "%comp_main1  = OpFunction %void None %voidf\n"
4095                 "%comp1_entry = OpLabel\n"
4096                 "%idval1      = OpLoad %uvec3 %id\n"
4097                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4098                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4099                 "%inval1      = OpLoad %f32 %inloc1\n"
4100                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4101                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4102                 "               OpStore %outloc1 %add\n"
4103                 "               OpReturn\n"
4104                 "               OpFunctionEnd\n"
4105
4106                 // Negate inputs.
4107                 "%comp_main2  = OpFunction %void None %voidf\n"
4108                 "%comp2_entry = OpLabel\n"
4109                 "%idval2      = OpLoad %uvec3 %id\n"
4110                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4111                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4112                 "%inval2      = OpLoad %f32 %inloc2\n"
4113                 "%neg         = OpFNegate %f32 %inval2\n"
4114                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4115                 "               OpStore %outloc2 %neg\n"
4116                 "               OpReturn\n"
4117                 "               OpFunctionEnd\n");
4118
4119         spec1.assembly = assembly;
4120         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4121         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4122         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4123         spec1.entryPoint = "entrypoint1";
4124
4125         spec2.assembly = assembly;
4126         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4127         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4128         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4129         spec2.entryPoint = "entrypoint2";
4130
4131         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4132         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4133
4134         return group.release();
4135 }
4136
4137 inline std::string makeLongUTF8String (size_t num4ByteChars)
4138 {
4139         // An example of a longest valid UTF-8 character.  Be explicit about the
4140         // character type because Microsoft compilers can otherwise interpret the
4141         // character string as being over wide (16-bit) characters. Ideally, we
4142         // would just use a C++11 UTF-8 string literal, but we want to support older
4143         // Microsoft compilers.
4144         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4145         std::string longString;
4146         longString.reserve(num4ByteChars * 4);
4147         for (size_t count = 0; count < num4ByteChars; count++)
4148         {
4149                 longString += earthAfrica;
4150         }
4151         return longString;
4152 }
4153
4154 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4155 {
4156         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4157         vector<CaseParameter>                   cases;
4158         de::Random                                              rnd                             (deStringHash(group->getName()));
4159         const int                                               numElements             = 100;
4160         vector<float>                                   positiveFloats  (numElements, 0);
4161         vector<float>                                   negativeFloats  (numElements, 0);
4162         const StringTemplate                    shaderTemplate  (
4163                 "OpCapability Shader\n"
4164                 "OpMemoryModel Logical GLSL450\n"
4165
4166                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4167                 "OpExecutionMode %main LocalSize 1 1 1\n"
4168
4169                 "${SOURCE}\n"
4170
4171                 "OpName %main           \"main\"\n"
4172                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4173
4174                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4175
4176                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4177
4178                 "%id        = OpVariable %uvec3ptr Input\n"
4179                 "%zero      = OpConstant %i32 0\n"
4180
4181                 "%main      = OpFunction %void None %voidf\n"
4182                 "%label     = OpLabel\n"
4183                 "%idval     = OpLoad %uvec3 %id\n"
4184                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4185                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4186                 "%inval     = OpLoad %f32 %inloc\n"
4187                 "%neg       = OpFNegate %f32 %inval\n"
4188                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4189                 "             OpStore %outloc %neg\n"
4190                 "             OpReturn\n"
4191                 "             OpFunctionEnd\n");
4192
4193         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4194         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4195         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4196                                                                                                                                                         "OpSource GLSL 430 %fname"));
4197         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4198                                                                                                                                                         "OpSource GLSL 430 %fname"));
4199         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4200                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4201         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4202                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4203         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4204                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4205         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4206                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4207         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4208                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4209                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4210         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4211                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4212                                                                                                                                                         "OpSourceContinued \"\""));
4213         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4214                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4215                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4216         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4217                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4218                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4219         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4220                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4221                                                                                                                                                         "OpSourceContinued \"void\"\n"
4222                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4223                                                                                                                                                         "OpSourceContinued \"{}\""));
4224         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4225                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4226                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4227
4228         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4229
4230         for (size_t ndx = 0; ndx < numElements; ++ndx)
4231                 negativeFloats[ndx] = -positiveFloats[ndx];
4232
4233         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4234         {
4235                 map<string, string>             specializations;
4236                 ComputeShaderSpec               spec;
4237
4238                 specializations["SOURCE"] = cases[caseNdx].param;
4239                 spec.assembly = shaderTemplate.specialize(specializations);
4240                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4241                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4242                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4243
4244                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4245         }
4246
4247         return group.release();
4248 }
4249
4250 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4251 {
4252         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4253         vector<CaseParameter>                   cases;
4254         de::Random                                              rnd                             (deStringHash(group->getName()));
4255         const int                                               numElements             = 100;
4256         vector<float>                                   inputFloats             (numElements, 0);
4257         vector<float>                                   outputFloats    (numElements, 0);
4258         const StringTemplate                    shaderTemplate  (
4259                 string(getComputeAsmShaderPreamble()) +
4260
4261                 "OpSourceExtension \"${EXTENSION}\"\n"
4262
4263                 "OpName %main           \"main\"\n"
4264                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4265
4266                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4267
4268                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4269
4270                 "%id        = OpVariable %uvec3ptr Input\n"
4271                 "%zero      = OpConstant %i32 0\n"
4272
4273                 "%main      = OpFunction %void None %voidf\n"
4274                 "%label     = OpLabel\n"
4275                 "%idval     = OpLoad %uvec3 %id\n"
4276                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4277                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4278                 "%inval     = OpLoad %f32 %inloc\n"
4279                 "%neg       = OpFNegate %f32 %inval\n"
4280                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4281                 "             OpStore %outloc %neg\n"
4282                 "             OpReturn\n"
4283                 "             OpFunctionEnd\n");
4284
4285         cases.push_back(CaseParameter("empty_extension",        ""));
4286         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4287         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4288         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4289         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4290
4291         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4292
4293         for (size_t ndx = 0; ndx < numElements; ++ndx)
4294                 outputFloats[ndx] = -inputFloats[ndx];
4295
4296         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4297         {
4298                 map<string, string>             specializations;
4299                 ComputeShaderSpec               spec;
4300
4301                 specializations["EXTENSION"] = cases[caseNdx].param;
4302                 spec.assembly = shaderTemplate.specialize(specializations);
4303                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4304                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4305                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4306
4307                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4308         }
4309
4310         return group.release();
4311 }
4312
4313 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4314 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4315 {
4316         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4317         vector<CaseParameter>                   cases;
4318         de::Random                                              rnd                             (deStringHash(group->getName()));
4319         const int                                               numElements             = 100;
4320         vector<float>                                   positiveFloats  (numElements, 0);
4321         vector<float>                                   negativeFloats  (numElements, 0);
4322         const StringTemplate                    shaderTemplate  (
4323                 string(getComputeAsmShaderPreamble()) +
4324
4325                 "OpSource GLSL 430\n"
4326                 "OpName %main           \"main\"\n"
4327                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4328
4329                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4330
4331                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4332                 "%uvec2     = OpTypeVector %u32 2\n"
4333                 "%bvec3     = OpTypeVector %bool 3\n"
4334                 "%fvec4     = OpTypeVector %f32 4\n"
4335                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4336                 "%const100  = OpConstant %u32 100\n"
4337                 "%uarr100   = OpTypeArray %i32 %const100\n"
4338                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4339                 "%pointer   = OpTypePointer Function %i32\n"
4340                 + string(getComputeAsmInputOutputBuffer()) +
4341
4342                 "%null      = OpConstantNull ${TYPE}\n"
4343
4344                 "%id        = OpVariable %uvec3ptr Input\n"
4345                 "%zero      = OpConstant %i32 0\n"
4346
4347                 "%main      = OpFunction %void None %voidf\n"
4348                 "%label     = OpLabel\n"
4349                 "%idval     = OpLoad %uvec3 %id\n"
4350                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4351                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4352                 "%inval     = OpLoad %f32 %inloc\n"
4353                 "%neg       = OpFNegate %f32 %inval\n"
4354                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4355                 "             OpStore %outloc %neg\n"
4356                 "             OpReturn\n"
4357                 "             OpFunctionEnd\n");
4358
4359         cases.push_back(CaseParameter("bool",                   "%bool"));
4360         cases.push_back(CaseParameter("sint32",                 "%i32"));
4361         cases.push_back(CaseParameter("uint32",                 "%u32"));
4362         cases.push_back(CaseParameter("float32",                "%f32"));
4363         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4364         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4365         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4366         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4367         cases.push_back(CaseParameter("array",                  "%uarr100"));
4368         cases.push_back(CaseParameter("struct",                 "%struct"));
4369         cases.push_back(CaseParameter("pointer",                "%pointer"));
4370
4371         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4372
4373         for (size_t ndx = 0; ndx < numElements; ++ndx)
4374                 negativeFloats[ndx] = -positiveFloats[ndx];
4375
4376         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4377         {
4378                 map<string, string>             specializations;
4379                 ComputeShaderSpec               spec;
4380
4381                 specializations["TYPE"] = cases[caseNdx].param;
4382                 spec.assembly = shaderTemplate.specialize(specializations);
4383                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4384                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4385                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4386
4387                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4388         }
4389
4390         return group.release();
4391 }
4392
4393 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4394 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4395 {
4396         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4397         vector<CaseParameter>                   cases;
4398         de::Random                                              rnd                             (deStringHash(group->getName()));
4399         const int                                               numElements             = 100;
4400         vector<float>                                   positiveFloats  (numElements, 0);
4401         vector<float>                                   negativeFloats  (numElements, 0);
4402         const StringTemplate                    shaderTemplate  (
4403                 string(getComputeAsmShaderPreamble()) +
4404
4405                 "OpSource GLSL 430\n"
4406                 "OpName %main           \"main\"\n"
4407                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4408
4409                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4410
4411                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4412
4413                 "%id        = OpVariable %uvec3ptr Input\n"
4414                 "%zero      = OpConstant %i32 0\n"
4415
4416                 "${CONSTANT}\n"
4417
4418                 "%main      = OpFunction %void None %voidf\n"
4419                 "%label     = OpLabel\n"
4420                 "%idval     = OpLoad %uvec3 %id\n"
4421                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4422                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4423                 "%inval     = OpLoad %f32 %inloc\n"
4424                 "%neg       = OpFNegate %f32 %inval\n"
4425                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4426                 "             OpStore %outloc %neg\n"
4427                 "             OpReturn\n"
4428                 "             OpFunctionEnd\n");
4429
4430         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4431                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4432         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4433                                                                                                         "%ten = OpConstant %f32 10.\n"
4434                                                                                                         "%fzero = OpConstant %f32 0.\n"
4435                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4436                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4437         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4438                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4439                                                                                                         "%fzero = OpConstant %f32 0.\n"
4440                                                                                                         "%one = OpConstant %f32 1.\n"
4441                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4442                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4443                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4444                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4445         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4446                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4447                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4448                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4449                                                                                                         "%one = OpConstant %u32 1\n"
4450                                                                                                         "%ten = OpConstant %i32 10\n"
4451                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4452                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4453                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4454
4455         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4456
4457         for (size_t ndx = 0; ndx < numElements; ++ndx)
4458                 negativeFloats[ndx] = -positiveFloats[ndx];
4459
4460         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4461         {
4462                 map<string, string>             specializations;
4463                 ComputeShaderSpec               spec;
4464
4465                 specializations["CONSTANT"] = cases[caseNdx].param;
4466                 spec.assembly = shaderTemplate.specialize(specializations);
4467                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4468                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4469                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4470
4471                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4472         }
4473
4474         return group.release();
4475 }
4476
4477 // Creates a floating point number with the given exponent, and significand
4478 // bits set. It can only create normalized numbers. Only the least significant
4479 // 24 bits of the significand will be examined. The final bit of the
4480 // significand will also be ignored. This allows alignment to be written
4481 // similarly to C99 hex-floats.
4482 // For example if you wanted to write 0x1.7f34p-12 you would call
4483 // constructNormalizedFloat(-12, 0x7f3400)
4484 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4485 {
4486         float f = 1.0f;
4487
4488         for (deInt32 idx = 0; idx < 23; ++idx)
4489         {
4490                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4491                 significand <<= 1;
4492         }
4493
4494         return std::ldexp(f, exponent);
4495 }
4496
4497 // Compare instruction for the OpQuantizeF16 compute exact case.
4498 // Returns true if the output is what is expected from the test case.
4499 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4500 {
4501         if (outputAllocs.size() != 1)
4502                 return false;
4503
4504         // Only size is needed because we cannot compare Nans.
4505         size_t byteSize = expectedOutputs[0].getByteSize();
4506
4507         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4508
4509         if (byteSize != 4*sizeof(float)) {
4510                 return false;
4511         }
4512
4513         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4514                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4515                 return false;
4516         }
4517         outputAsFloat++;
4518
4519         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4520                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4521                 return false;
4522         }
4523         outputAsFloat++;
4524
4525         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4526                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4527                 return false;
4528         }
4529         outputAsFloat++;
4530
4531         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4532                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4533                 return false;
4534         }
4535
4536         return true;
4537 }
4538
4539 // Checks that every output from a test-case is a float NaN.
4540 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4541 {
4542         if (outputAllocs.size() != 1)
4543                 return false;
4544
4545         // Only size is needed because we cannot compare Nans.
4546         size_t byteSize = expectedOutputs[0].getByteSize();
4547
4548         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4549
4550         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4551         {
4552                 if (!deFloatIsNaN(output_as_float[idx]))
4553                 {
4554                         return false;
4555                 }
4556         }
4557
4558         return true;
4559 }
4560
4561 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4562 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4563 {
4564         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4565
4566         const std::string shader (
4567                 string(getComputeAsmShaderPreamble()) +
4568
4569                 "OpSource GLSL 430\n"
4570                 "OpName %main           \"main\"\n"
4571                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4572
4573                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4574
4575                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4576
4577                 "%id        = OpVariable %uvec3ptr Input\n"
4578                 "%zero      = OpConstant %i32 0\n"
4579
4580                 "%main      = OpFunction %void None %voidf\n"
4581                 "%label     = OpLabel\n"
4582                 "%idval     = OpLoad %uvec3 %id\n"
4583                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4584                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4585                 "%inval     = OpLoad %f32 %inloc\n"
4586                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4587                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4588                 "             OpStore %outloc %quant\n"
4589                 "             OpReturn\n"
4590                 "             OpFunctionEnd\n");
4591
4592         {
4593                 ComputeShaderSpec       spec;
4594                 const deUint32          numElements             = 100;
4595                 vector<float>           infinities;
4596                 vector<float>           results;
4597
4598                 infinities.reserve(numElements);
4599                 results.reserve(numElements);
4600
4601                 for (size_t idx = 0; idx < numElements; ++idx)
4602                 {
4603                         switch(idx % 4)
4604                         {
4605                                 case 0:
4606                                         infinities.push_back(std::numeric_limits<float>::infinity());
4607                                         results.push_back(std::numeric_limits<float>::infinity());
4608                                         break;
4609                                 case 1:
4610                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4611                                         results.push_back(-std::numeric_limits<float>::infinity());
4612                                         break;
4613                                 case 2:
4614                                         infinities.push_back(std::ldexp(1.0f, 16));
4615                                         results.push_back(std::numeric_limits<float>::infinity());
4616                                         break;
4617                                 case 3:
4618                                         infinities.push_back(std::ldexp(-1.0f, 32));
4619                                         results.push_back(-std::numeric_limits<float>::infinity());
4620                                         break;
4621                         }
4622                 }
4623
4624                 spec.assembly = shader;
4625                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4626                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4627                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4628
4629                 group->addChild(new SpvAsmComputeShaderCase(
4630                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4631         }
4632
4633         {
4634                 ComputeShaderSpec       spec;
4635                 vector<float>           nans;
4636                 const deUint32          numElements             = 100;
4637
4638                 nans.reserve(numElements);
4639
4640                 for (size_t idx = 0; idx < numElements; ++idx)
4641                 {
4642                         if (idx % 2 == 0)
4643                         {
4644                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4645                         }
4646                         else
4647                         {
4648                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4649                         }
4650                 }
4651
4652                 spec.assembly = shader;
4653                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4654                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4655                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4656                 spec.verifyIO = &compareNan;
4657
4658                 group->addChild(new SpvAsmComputeShaderCase(
4659                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4660         }
4661
4662         {
4663                 ComputeShaderSpec       spec;
4664                 vector<float>           small;
4665                 vector<float>           zeros;
4666                 const deUint32          numElements             = 100;
4667
4668                 small.reserve(numElements);
4669                 zeros.reserve(numElements);
4670
4671                 for (size_t idx = 0; idx < numElements; ++idx)
4672                 {
4673                         switch(idx % 6)
4674                         {
4675                                 case 0:
4676                                         small.push_back(0.f);
4677                                         zeros.push_back(0.f);
4678                                         break;
4679                                 case 1:
4680                                         small.push_back(-0.f);
4681                                         zeros.push_back(-0.f);
4682                                         break;
4683                                 case 2:
4684                                         small.push_back(std::ldexp(1.0f, -16));
4685                                         zeros.push_back(0.f);
4686                                         break;
4687                                 case 3:
4688                                         small.push_back(std::ldexp(-1.0f, -32));
4689                                         zeros.push_back(-0.f);
4690                                         break;
4691                                 case 4:
4692                                         small.push_back(std::ldexp(1.0f, -127));
4693                                         zeros.push_back(0.f);
4694                                         break;
4695                                 case 5:
4696                                         small.push_back(-std::ldexp(1.0f, -128));
4697                                         zeros.push_back(-0.f);
4698                                         break;
4699                         }
4700                 }
4701
4702                 spec.assembly = shader;
4703                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4704                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4705                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4706
4707                 group->addChild(new SpvAsmComputeShaderCase(
4708                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4709         }
4710
4711         {
4712                 ComputeShaderSpec       spec;
4713                 vector<float>           exact;
4714                 const deUint32          numElements             = 200;
4715
4716                 exact.reserve(numElements);
4717
4718                 for (size_t idx = 0; idx < numElements; ++idx)
4719                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4720
4721                 spec.assembly = shader;
4722                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4723                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4724                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4725
4726                 group->addChild(new SpvAsmComputeShaderCase(
4727                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4728         }
4729
4730         {
4731                 ComputeShaderSpec       spec;
4732                 vector<float>           inputs;
4733                 const deUint32          numElements             = 4;
4734
4735                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4736                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4737                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4738                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4739
4740                 spec.assembly = shader;
4741                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4742                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4743                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4744                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4745
4746                 group->addChild(new SpvAsmComputeShaderCase(
4747                         testCtx, "rounded", "Check that are rounded when needed", spec));
4748         }
4749
4750         return group.release();
4751 }
4752
4753 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4754 {
4755         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4756
4757         const std::string shader (
4758                 string(getComputeAsmShaderPreamble()) +
4759
4760                 "OpName %main           \"main\"\n"
4761                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4762
4763                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4764
4765                 "OpDecorate %sc_0  SpecId 0\n"
4766                 "OpDecorate %sc_1  SpecId 1\n"
4767                 "OpDecorate %sc_2  SpecId 2\n"
4768                 "OpDecorate %sc_3  SpecId 3\n"
4769                 "OpDecorate %sc_4  SpecId 4\n"
4770                 "OpDecorate %sc_5  SpecId 5\n"
4771
4772                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4773
4774                 "%id        = OpVariable %uvec3ptr Input\n"
4775                 "%zero      = OpConstant %i32 0\n"
4776                 "%c_u32_6   = OpConstant %u32 6\n"
4777
4778                 "%sc_0      = OpSpecConstant %f32 0.\n"
4779                 "%sc_1      = OpSpecConstant %f32 0.\n"
4780                 "%sc_2      = OpSpecConstant %f32 0.\n"
4781                 "%sc_3      = OpSpecConstant %f32 0.\n"
4782                 "%sc_4      = OpSpecConstant %f32 0.\n"
4783                 "%sc_5      = OpSpecConstant %f32 0.\n"
4784
4785                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4786                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4787                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4788                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4789                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4790                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4791
4792                 "%main      = OpFunction %void None %voidf\n"
4793                 "%label     = OpLabel\n"
4794                 "%idval     = OpLoad %uvec3 %id\n"
4795                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4796                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4797                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4798                 "            OpSelectionMerge %exit None\n"
4799                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4800
4801                 "%case0     = OpLabel\n"
4802                 "             OpStore %outloc %sc_0_quant\n"
4803                 "             OpBranch %exit\n"
4804
4805                 "%case1     = OpLabel\n"
4806                 "             OpStore %outloc %sc_1_quant\n"
4807                 "             OpBranch %exit\n"
4808
4809                 "%case2     = OpLabel\n"
4810                 "             OpStore %outloc %sc_2_quant\n"
4811                 "             OpBranch %exit\n"
4812
4813                 "%case3     = OpLabel\n"
4814                 "             OpStore %outloc %sc_3_quant\n"
4815                 "             OpBranch %exit\n"
4816
4817                 "%case4     = OpLabel\n"
4818                 "             OpStore %outloc %sc_4_quant\n"
4819                 "             OpBranch %exit\n"
4820
4821                 "%case5     = OpLabel\n"
4822                 "             OpStore %outloc %sc_5_quant\n"
4823                 "             OpBranch %exit\n"
4824
4825                 "%exit      = OpLabel\n"
4826                 "             OpReturn\n"
4827
4828                 "             OpFunctionEnd\n");
4829
4830         {
4831                 ComputeShaderSpec       spec;
4832                 const deUint8           numCases        = 4;
4833                 vector<float>           inputs          (numCases, 0.f);
4834                 vector<float>           outputs;
4835
4836                 spec.assembly           = shader;
4837                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4838
4839                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4840                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4841                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4842                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4843
4844                 outputs.push_back(std::numeric_limits<float>::infinity());
4845                 outputs.push_back(-std::numeric_limits<float>::infinity());
4846                 outputs.push_back(std::numeric_limits<float>::infinity());
4847                 outputs.push_back(-std::numeric_limits<float>::infinity());
4848
4849                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4850                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4851
4852                 group->addChild(new SpvAsmComputeShaderCase(
4853                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4854         }
4855
4856         {
4857                 ComputeShaderSpec       spec;
4858                 const deUint8           numCases        = 2;
4859                 vector<float>           inputs          (numCases, 0.f);
4860                 vector<float>           outputs;
4861
4862                 spec.assembly           = shader;
4863                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4864                 spec.verifyIO           = &compareNan;
4865
4866                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4867                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4868
4869                 for (deUint8 idx = 0; idx < numCases; ++idx)
4870                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4871
4872                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4873                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4874
4875                 group->addChild(new SpvAsmComputeShaderCase(
4876                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4877         }
4878
4879         {
4880                 ComputeShaderSpec       spec;
4881                 const deUint8           numCases        = 6;
4882                 vector<float>           inputs          (numCases, 0.f);
4883                 vector<float>           outputs;
4884
4885                 spec.assembly           = shader;
4886                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4887
4888                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4889                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4890                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4891                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4892                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4893                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4894
4895                 outputs.push_back(0.f);
4896                 outputs.push_back(-0.f);
4897                 outputs.push_back(0.f);
4898                 outputs.push_back(-0.f);
4899                 outputs.push_back(0.f);
4900                 outputs.push_back(-0.f);
4901
4902                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4903                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4904
4905                 group->addChild(new SpvAsmComputeShaderCase(
4906                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4907         }
4908
4909         {
4910                 ComputeShaderSpec       spec;
4911                 const deUint8           numCases        = 6;
4912                 vector<float>           inputs          (numCases, 0.f);
4913                 vector<float>           outputs;
4914
4915                 spec.assembly           = shader;
4916                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4917
4918                 for (deUint8 idx = 0; idx < 6; ++idx)
4919                 {
4920                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4921                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4922                         outputs.push_back(f);
4923                 }
4924
4925                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4926                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4927
4928                 group->addChild(new SpvAsmComputeShaderCase(
4929                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4930         }
4931
4932         {
4933                 ComputeShaderSpec       spec;
4934                 const deUint8           numCases        = 4;
4935                 vector<float>           inputs          (numCases, 0.f);
4936                 vector<float>           outputs;
4937
4938                 spec.assembly           = shader;
4939                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4940                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4941
4942                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4943                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4944                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4945                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4946
4947                 for (deUint8 idx = 0; idx < numCases; ++idx)
4948                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4949
4950                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4951                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4952
4953                 group->addChild(new SpvAsmComputeShaderCase(
4954                         testCtx, "rounded", "Check that are rounded when needed", spec));
4955         }
4956
4957         return group.release();
4958 }
4959
4960 // Checks that constant null/composite values can be used in computation.
4961 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4962 {
4963         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4964         ComputeShaderSpec                               spec;
4965         de::Random                                              rnd                             (deStringHash(group->getName()));
4966         const int                                               numElements             = 100;
4967         vector<float>                                   positiveFloats  (numElements, 0);
4968         vector<float>                                   negativeFloats  (numElements, 0);
4969
4970         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4971
4972         for (size_t ndx = 0; ndx < numElements; ++ndx)
4973                 negativeFloats[ndx] = -positiveFloats[ndx];
4974
4975         spec.assembly =
4976                 "OpCapability Shader\n"
4977                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4978                 "OpMemoryModel Logical GLSL450\n"
4979                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4980                 "OpExecutionMode %main LocalSize 1 1 1\n"
4981
4982                 "OpSource GLSL 430\n"
4983                 "OpName %main           \"main\"\n"
4984                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4985
4986                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4987
4988                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4989
4990                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4991                 "%ten       = OpConstant %u32 10\n"
4992                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4993                 "%fst       = OpTypeStruct %f32 %f32\n"
4994
4995                 + string(getComputeAsmInputOutputBuffer()) +
4996
4997                 "%id        = OpVariable %uvec3ptr Input\n"
4998                 "%zero      = OpConstant %i32 0\n"
4999
5000                 // Create a bunch of null values
5001                 "%unull     = OpConstantNull %u32\n"
5002                 "%fnull     = OpConstantNull %f32\n"
5003                 "%vnull     = OpConstantNull %fvec3\n"
5004                 "%mnull     = OpConstantNull %fmat\n"
5005                 "%anull     = OpConstantNull %f32arr10\n"
5006                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5007
5008                 "%main      = OpFunction %void None %voidf\n"
5009                 "%label     = OpLabel\n"
5010                 "%idval     = OpLoad %uvec3 %id\n"
5011                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5012                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5013                 "%inval     = OpLoad %f32 %inloc\n"
5014                 "%neg       = OpFNegate %f32 %inval\n"
5015
5016                 // Get the abs() of (a certain element of) those null values
5017                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5018                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5019                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5020                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5021                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5022                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5023                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5024                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5025                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5026                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5027                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5028
5029                 // Add them all
5030                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5031                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5032                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5033                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5034                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5035                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5036
5037                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5038                 "             OpStore %outloc %final\n" // write to output
5039                 "             OpReturn\n"
5040                 "             OpFunctionEnd\n";
5041         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5042         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5043         spec.numWorkGroups = IVec3(numElements, 1, 1);
5044
5045         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5046
5047         return group.release();
5048 }
5049
5050 // Assembly code used for testing loop control is based on GLSL source code:
5051 // #version 430
5052 //
5053 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5054 //   float elements[];
5055 // } input_data;
5056 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5057 //   float elements[];
5058 // } output_data;
5059 //
5060 // void main() {
5061 //   uint x = gl_GlobalInvocationID.x;
5062 //   output_data.elements[x] = input_data.elements[x];
5063 //   for (uint i = 0; i < 4; ++i)
5064 //     output_data.elements[x] += 1.f;
5065 // }
5066 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5067 {
5068         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5069         vector<CaseParameter>                   cases;
5070         de::Random                                              rnd                             (deStringHash(group->getName()));
5071         const int                                               numElements             = 100;
5072         vector<float>                                   inputFloats             (numElements, 0);
5073         vector<float>                                   outputFloats    (numElements, 0);
5074         const StringTemplate                    shaderTemplate  (
5075                 string(getComputeAsmShaderPreamble()) +
5076
5077                 "OpSource GLSL 430\n"
5078                 "OpName %main \"main\"\n"
5079                 "OpName %id \"gl_GlobalInvocationID\"\n"
5080
5081                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5082
5083                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5084
5085                 "%u32ptr      = OpTypePointer Function %u32\n"
5086
5087                 "%id          = OpVariable %uvec3ptr Input\n"
5088                 "%zero        = OpConstant %i32 0\n"
5089                 "%uzero       = OpConstant %u32 0\n"
5090                 "%one         = OpConstant %i32 1\n"
5091                 "%constf1     = OpConstant %f32 1.0\n"
5092                 "%four        = OpConstant %u32 4\n"
5093
5094                 "%main        = OpFunction %void None %voidf\n"
5095                 "%entry       = OpLabel\n"
5096                 "%i           = OpVariable %u32ptr Function\n"
5097                 "               OpStore %i %uzero\n"
5098
5099                 "%idval       = OpLoad %uvec3 %id\n"
5100                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5101                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5102                 "%inval       = OpLoad %f32 %inloc\n"
5103                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5104                 "               OpStore %outloc %inval\n"
5105                 "               OpBranch %loop_entry\n"
5106
5107                 "%loop_entry  = OpLabel\n"
5108                 "%i_val       = OpLoad %u32 %i\n"
5109                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5110                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5111                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5112                 "%loop_body   = OpLabel\n"
5113                 "%outval      = OpLoad %f32 %outloc\n"
5114                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5115                 "               OpStore %outloc %addf1\n"
5116                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5117                 "               OpStore %i %new_i\n"
5118                 "               OpBranch %loop_entry\n"
5119                 "%loop_merge  = OpLabel\n"
5120                 "               OpReturn\n"
5121                 "               OpFunctionEnd\n");
5122
5123         cases.push_back(CaseParameter("none",                           "None"));
5124         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5125         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5126
5127         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5128
5129         for (size_t ndx = 0; ndx < numElements; ++ndx)
5130                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5131
5132         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5133         {
5134                 map<string, string>             specializations;
5135                 ComputeShaderSpec               spec;
5136
5137                 specializations["CONTROL"] = cases[caseNdx].param;
5138                 spec.assembly = shaderTemplate.specialize(specializations);
5139                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5140                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5141                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5142
5143                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5144         }
5145
5146         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5147         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5148
5149         return group.release();
5150 }
5151
5152 // Assembly code used for testing selection control is based on GLSL source code:
5153 // #version 430
5154 //
5155 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5156 //   float elements[];
5157 // } input_data;
5158 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5159 //   float elements[];
5160 // } output_data;
5161 //
5162 // void main() {
5163 //   uint x = gl_GlobalInvocationID.x;
5164 //   float val = input_data.elements[x];
5165 //   if (val > 10.f)
5166 //     output_data.elements[x] = val + 1.f;
5167 //   else
5168 //     output_data.elements[x] = val - 1.f;
5169 // }
5170 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5171 {
5172         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5173         vector<CaseParameter>                   cases;
5174         de::Random                                              rnd                             (deStringHash(group->getName()));
5175         const int                                               numElements             = 100;
5176         vector<float>                                   inputFloats             (numElements, 0);
5177         vector<float>                                   outputFloats    (numElements, 0);
5178         const StringTemplate                    shaderTemplate  (
5179                 string(getComputeAsmShaderPreamble()) +
5180
5181                 "OpSource GLSL 430\n"
5182                 "OpName %main \"main\"\n"
5183                 "OpName %id \"gl_GlobalInvocationID\"\n"
5184
5185                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5186
5187                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5188
5189                 "%id       = OpVariable %uvec3ptr Input\n"
5190                 "%zero     = OpConstant %i32 0\n"
5191                 "%constf1  = OpConstant %f32 1.0\n"
5192                 "%constf10 = OpConstant %f32 10.0\n"
5193
5194                 "%main     = OpFunction %void None %voidf\n"
5195                 "%entry    = OpLabel\n"
5196                 "%idval    = OpLoad %uvec3 %id\n"
5197                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5198                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5199                 "%inval    = OpLoad %f32 %inloc\n"
5200                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5201                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5202
5203                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5204                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5205                 "%if_true  = OpLabel\n"
5206                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5207                 "            OpStore %outloc %addf1\n"
5208                 "            OpBranch %if_end\n"
5209                 "%if_false = OpLabel\n"
5210                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5211                 "            OpStore %outloc %subf1\n"
5212                 "            OpBranch %if_end\n"
5213                 "%if_end   = OpLabel\n"
5214                 "            OpReturn\n"
5215                 "            OpFunctionEnd\n");
5216
5217         cases.push_back(CaseParameter("none",                                   "None"));
5218         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5219         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5220         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5221
5222         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5223
5224         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5225         floorAll(inputFloats);
5226
5227         for (size_t ndx = 0; ndx < numElements; ++ndx)
5228                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5229
5230         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5231         {
5232                 map<string, string>             specializations;
5233                 ComputeShaderSpec               spec;
5234
5235                 specializations["CONTROL"] = cases[caseNdx].param;
5236                 spec.assembly = shaderTemplate.specialize(specializations);
5237                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5238                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5239                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5240
5241                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5242         }
5243
5244         return group.release();
5245 }
5246
5247 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5248 {
5249         // Generate a long name.
5250         std::string longname;
5251         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5252
5253         // Some bad names, abusing utf-8 encoding. This may also cause problems
5254         // with the logs.
5255         // 1. Various illegal code points in utf-8
5256         std::string utf8illegal =
5257                 "Illegal bytes in UTF-8: "
5258                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5259                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5260
5261         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5262         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5263
5264         // 3. Some overlong encodings
5265         std::string utf8overlong =
5266                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5267                 "\xf0\x8f\xbf\xbf";
5268
5269         // 4. Internet "zalgo" meme "bleeding text"
5270         std::string utf8zalgo =
5271                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5272                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5273                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5274                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5275                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5276                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5277                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5278                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5279                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5280                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5281                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5282                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5283                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5284                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5285                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5286                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5287                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5288                 "\x93\xcd\x96\xcc\x97\xff";
5289
5290         // General name abuses
5291         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5292         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5293         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5294         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5295         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5296
5297         // GL keywords
5298         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5299         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5300         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5301         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5302         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5303         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5304         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5305         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5306         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5307         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5308         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5309         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5310         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5311         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5312         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5313         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5314         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5315         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5316         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5317         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5318         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5319 }
5320
5321 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5322 {
5323         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5324         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5325         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5326         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5327         vector<CaseParameter>                   cases;
5328         vector<CaseParameter>                   abuseCases;
5329         vector<string>                                  testFunc;
5330         de::Random                                              rnd                             (deStringHash(group->getName()));
5331         const int                                               numElements             = 128;
5332         vector<float>                                   inputFloats             (numElements, 0);
5333         vector<float>                                   outputFloats    (numElements, 0);
5334
5335         getOpNameAbuseCases(abuseCases);
5336
5337         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5338
5339         for(size_t ndx = 0; ndx < numElements; ++ndx)
5340                 outputFloats[ndx] = -inputFloats[ndx];
5341
5342         const string commonShaderHeader =
5343                 "OpCapability Shader\n"
5344                 "OpMemoryModel Logical GLSL450\n"
5345                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5346                 "OpExecutionMode %main LocalSize 1 1 1\n";
5347
5348         const string commonShaderFooter =
5349                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5350
5351                 + string(getComputeAsmInputOutputBufferTraits())
5352                 + string(getComputeAsmCommonTypes())
5353                 + string(getComputeAsmInputOutputBuffer()) +
5354
5355                 "%id        = OpVariable %uvec3ptr Input\n"
5356                 "%zero      = OpConstant %i32 0\n"
5357
5358                 "%func      = OpFunction %void None %voidf\n"
5359                 "%5         = OpLabel\n"
5360                 "             OpReturn\n"
5361                 "             OpFunctionEnd\n"
5362
5363                 "%main      = OpFunction %void None %voidf\n"
5364                 "%entry     = OpLabel\n"
5365                 "%7         = OpFunctionCall %void %func\n"
5366
5367                 "%idval     = OpLoad %uvec3 %id\n"
5368                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5369
5370                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5371                 "%inval     = OpLoad %f32 %inloc\n"
5372                 "%neg       = OpFNegate %f32 %inval\n"
5373                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5374                 "             OpStore %outloc %neg\n"
5375
5376                 "             OpReturn\n"
5377                 "             OpFunctionEnd\n";
5378
5379         const StringTemplate shaderTemplate (
5380                 "OpCapability Shader\n"
5381                 "OpMemoryModel Logical GLSL450\n"
5382                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5383                 "OpExecutionMode %main LocalSize 1 1 1\n"
5384                 "OpName %${ID} \"${NAME}\"\n" +
5385                 commonShaderFooter);
5386
5387         const std::string multipleNames =
5388                 commonShaderHeader +
5389                 "OpName %main \"to_be\"\n"
5390                 "OpName %id   \"or_not\"\n"
5391                 "OpName %main \"to_be\"\n"
5392                 "OpName %main \"makes_no\"\n"
5393                 "OpName %func \"difference\"\n"
5394                 "OpName %5    \"to_me\"\n" +
5395                 commonShaderFooter;
5396
5397         {
5398                 ComputeShaderSpec       spec;
5399
5400                 spec.assembly           = multipleNames;
5401                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5402                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5403                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5404
5405                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5406         }
5407
5408         const std::string everythingNamed =
5409                 commonShaderHeader +
5410                 "OpName %main   \"name1\"\n"
5411                 "OpName %id     \"name2\"\n"
5412                 "OpName %zero   \"name3\"\n"
5413                 "OpName %entry  \"name4\"\n"
5414                 "OpName %func   \"name5\"\n"
5415                 "OpName %5      \"name6\"\n"
5416                 "OpName %7      \"name7\"\n"
5417                 "OpName %idval  \"name8\"\n"
5418                 "OpName %inloc  \"name9\"\n"
5419                 "OpName %inval  \"name10\"\n"
5420                 "OpName %neg    \"name11\"\n"
5421                 "OpName %outloc \"name12\"\n"+
5422                 commonShaderFooter;
5423         {
5424                 ComputeShaderSpec       spec;
5425
5426                 spec.assembly           = everythingNamed;
5427                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5428                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5429                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5430
5431                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5432         }
5433
5434         const std::string everythingNamedTheSame =
5435                 commonShaderHeader +
5436                 "OpName %main   \"the_same\"\n"
5437                 "OpName %id     \"the_same\"\n"
5438                 "OpName %zero   \"the_same\"\n"
5439                 "OpName %entry  \"the_same\"\n"
5440                 "OpName %func   \"the_same\"\n"
5441                 "OpName %5      \"the_same\"\n"
5442                 "OpName %7      \"the_same\"\n"
5443                 "OpName %idval  \"the_same\"\n"
5444                 "OpName %inloc  \"the_same\"\n"
5445                 "OpName %inval  \"the_same\"\n"
5446                 "OpName %neg    \"the_same\"\n"
5447                 "OpName %outloc \"the_same\"\n"+
5448                 commonShaderFooter;
5449         {
5450                 ComputeShaderSpec       spec;
5451
5452                 spec.assembly           = everythingNamedTheSame;
5453                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5454                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5455                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5456
5457                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5458         }
5459
5460         // main_is_...
5461         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5462         {
5463                 map<string, string>     specializations;
5464                 ComputeShaderSpec       spec;
5465
5466                 specializations["ENTRY"]        = "main";
5467                 specializations["ID"]           = "main";
5468                 specializations["NAME"]         = abuseCases[ndx].param;
5469                 spec.assembly                           = shaderTemplate.specialize(specializations);
5470                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5471                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5472                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5473
5474                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5475         }
5476
5477         // x_is_....
5478         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5479         {
5480                 map<string, string>     specializations;
5481                 ComputeShaderSpec       spec;
5482
5483                 specializations["ENTRY"]        = "main";
5484                 specializations["ID"]           = "x";
5485                 specializations["NAME"]         = abuseCases[ndx].param;
5486                 spec.assembly                           = shaderTemplate.specialize(specializations);
5487                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5488                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5489                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5490
5491                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5492         }
5493
5494         cases.push_back(CaseParameter("_is_main", "main"));
5495         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5496         testFunc.push_back("main");
5497         testFunc.push_back("func");
5498
5499         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5500         {
5501                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5502                 {
5503                         map<string, string>     specializations;
5504                         ComputeShaderSpec       spec;
5505
5506                         specializations["ENTRY"]        = "main";
5507                         specializations["ID"]           = testFunc[fNdx];
5508                         specializations["NAME"]         = cases[ndx].param;
5509                         spec.assembly                           = shaderTemplate.specialize(specializations);
5510                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5511                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5512                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5513
5514                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5515                 }
5516         }
5517
5518         cases.push_back(CaseParameter("_is_entry", "rdc"));
5519
5520         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5521         {
5522                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5523                 {
5524                         map<string, string>     specializations;
5525                         ComputeShaderSpec       spec;
5526
5527                         specializations["ENTRY"]        = "rdc";
5528                         specializations["ID"]           = testFunc[fNdx];
5529                         specializations["NAME"]         = cases[ndx].param;
5530                         spec.assembly                           = shaderTemplate.specialize(specializations);
5531                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5532                         spec.entryPoint                         = "rdc";
5533                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5534                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5535
5536                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5537                 }
5538         }
5539
5540         group->addChild(entryMainGroup.release());
5541         group->addChild(entryNotGroup.release());
5542         group->addChild(abuseGroup.release());
5543
5544         return group.release();
5545 }
5546
5547 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5548 {
5549         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5550         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5551         vector<CaseParameter>                   abuseCases;
5552         vector<string>                                  testFunc;
5553         de::Random                                              rnd(deStringHash(group->getName()));
5554         const int                                               numElements = 128;
5555         vector<float>                                   inputFloats(numElements, 0);
5556         vector<float>                                   outputFloats(numElements, 0);
5557
5558         getOpNameAbuseCases(abuseCases);
5559
5560         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5561
5562         for (size_t ndx = 0; ndx < numElements; ++ndx)
5563                 outputFloats[ndx] = -inputFloats[ndx];
5564
5565         const string commonShaderHeader =
5566                 "OpCapability Shader\n"
5567                 "OpMemoryModel Logical GLSL450\n"
5568                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5569                 "OpExecutionMode %main LocalSize 1 1 1\n";
5570
5571         const string commonShaderFooter =
5572                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5573
5574                 + string(getComputeAsmInputOutputBufferTraits())
5575                 + string(getComputeAsmCommonTypes())
5576                 + string(getComputeAsmInputOutputBuffer()) +
5577
5578                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5579
5580                 "%id        = OpVariable %uvec3ptr Input\n"
5581                 "%zero      = OpConstant %i32 0\n"
5582
5583                 "%main      = OpFunction %void None %voidf\n"
5584                 "%entry     = OpLabel\n"
5585
5586                 "%idval     = OpLoad %uvec3 %id\n"
5587                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5588
5589                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5590                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5591
5592                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5593                 "%inval     = OpLoad %f32 %inloc\n"
5594                 "%neg       = OpFNegate %f32 %inval\n"
5595                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5596                 "             OpStore %outloc %neg\n"
5597
5598                 "             OpReturn\n"
5599                 "             OpFunctionEnd\n";
5600
5601         const StringTemplate shaderTemplate(
5602                 commonShaderHeader +
5603                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5604                 commonShaderFooter);
5605
5606         const std::string multipleNames =
5607                 commonShaderHeader +
5608                 "OpMemberName %u3str 0 \"to_be\"\n"
5609                 "OpMemberName %u3str 1 \"or_not\"\n"
5610                 "OpMemberName %u3str 0 \"to_be\"\n"
5611                 "OpMemberName %u3str 2 \"makes_no\"\n"
5612                 "OpMemberName %u3str 0 \"difference\"\n"
5613                 "OpMemberName %u3str 0 \"to_me\"\n" +
5614                 commonShaderFooter;
5615         {
5616                 ComputeShaderSpec       spec;
5617
5618                 spec.assembly = multipleNames;
5619                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5620                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5621                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5622
5623                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5624         }
5625
5626         const std::string everythingNamedTheSame =
5627                 commonShaderHeader +
5628                 "OpMemberName %u3str 0 \"the_same\"\n"
5629                 "OpMemberName %u3str 1 \"the_same\"\n"
5630                 "OpMemberName %u3str 2 \"the_same\"\n" +
5631                 commonShaderFooter;
5632
5633         {
5634                 ComputeShaderSpec       spec;
5635
5636                 spec.assembly = everythingNamedTheSame;
5637                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5638                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5639                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5640
5641                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5642         }
5643
5644         // u3str_x_is_....
5645         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5646         {
5647                 map<string, string>     specializations;
5648                 ComputeShaderSpec       spec;
5649
5650                 specializations["NAME"] = abuseCases[ndx].param;
5651                 spec.assembly = shaderTemplate.specialize(specializations);
5652                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5653                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5654                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5655
5656                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5657         }
5658
5659         group->addChild(abuseGroup.release());
5660
5661         return group.release();
5662 }
5663
5664 // Assembly code used for testing function control is based on GLSL source code:
5665 //
5666 // #version 430
5667 //
5668 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5669 //   float elements[];
5670 // } input_data;
5671 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5672 //   float elements[];
5673 // } output_data;
5674 //
5675 // float const10() { return 10.f; }
5676 //
5677 // void main() {
5678 //   uint x = gl_GlobalInvocationID.x;
5679 //   output_data.elements[x] = input_data.elements[x] + const10();
5680 // }
5681 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5682 {
5683         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5684         vector<CaseParameter>                   cases;
5685         de::Random                                              rnd                             (deStringHash(group->getName()));
5686         const int                                               numElements             = 100;
5687         vector<float>                                   inputFloats             (numElements, 0);
5688         vector<float>                                   outputFloats    (numElements, 0);
5689         const StringTemplate                    shaderTemplate  (
5690                 string(getComputeAsmShaderPreamble()) +
5691
5692                 "OpSource GLSL 430\n"
5693                 "OpName %main \"main\"\n"
5694                 "OpName %func_const10 \"const10(\"\n"
5695                 "OpName %id \"gl_GlobalInvocationID\"\n"
5696
5697                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5698
5699                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5700
5701                 "%f32f = OpTypeFunction %f32\n"
5702                 "%id = OpVariable %uvec3ptr Input\n"
5703                 "%zero = OpConstant %i32 0\n"
5704                 "%constf10 = OpConstant %f32 10.0\n"
5705
5706                 "%main         = OpFunction %void None %voidf\n"
5707                 "%entry        = OpLabel\n"
5708                 "%idval        = OpLoad %uvec3 %id\n"
5709                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5710                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5711                 "%inval        = OpLoad %f32 %inloc\n"
5712                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5713                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5714                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5715                 "                OpStore %outloc %fadd\n"
5716                 "                OpReturn\n"
5717                 "                OpFunctionEnd\n"
5718
5719                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5720                 "%label        = OpLabel\n"
5721                 "                OpReturnValue %constf10\n"
5722                 "                OpFunctionEnd\n");
5723
5724         cases.push_back(CaseParameter("none",                                           "None"));
5725         cases.push_back(CaseParameter("inline",                                         "Inline"));
5726         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5727         cases.push_back(CaseParameter("pure",                                           "Pure"));
5728         cases.push_back(CaseParameter("const",                                          "Const"));
5729         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5730         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5731         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5732         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5733
5734         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5735
5736         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5737         floorAll(inputFloats);
5738
5739         for (size_t ndx = 0; ndx < numElements; ++ndx)
5740                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5741
5742         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5743         {
5744                 map<string, string>             specializations;
5745                 ComputeShaderSpec               spec;
5746
5747                 specializations["CONTROL"] = cases[caseNdx].param;
5748                 spec.assembly = shaderTemplate.specialize(specializations);
5749                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5750                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5751                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5752
5753                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5754         }
5755
5756         return group.release();
5757 }
5758
5759 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5760 {
5761         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5762         vector<CaseParameter>                   cases;
5763         de::Random                                              rnd                             (deStringHash(group->getName()));
5764         const int                                               numElements             = 100;
5765         vector<float>                                   inputFloats             (numElements, 0);
5766         vector<float>                                   outputFloats    (numElements, 0);
5767         const StringTemplate                    shaderTemplate  (
5768                 string(getComputeAsmShaderPreamble()) +
5769
5770                 "OpSource GLSL 430\n"
5771                 "OpName %main           \"main\"\n"
5772                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5773
5774                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5775
5776                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5777
5778                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5779
5780                 "%id        = OpVariable %uvec3ptr Input\n"
5781                 "%zero      = OpConstant %i32 0\n"
5782                 "%four      = OpConstant %i32 4\n"
5783
5784                 "%main      = OpFunction %void None %voidf\n"
5785                 "%label     = OpLabel\n"
5786                 "%copy      = OpVariable %f32ptr_f Function\n"
5787                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5788                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5789                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5790                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5791                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5792                 "%val1      = OpLoad %f32 %copy\n"
5793                 "%val2      = OpLoad %f32 %inloc\n"
5794                 "%add       = OpFAdd %f32 %val1 %val2\n"
5795                 "             OpStore %outloc %add ${ACCESS}\n"
5796                 "             OpReturn\n"
5797                 "             OpFunctionEnd\n");
5798
5799         cases.push_back(CaseParameter("null",                                   ""));
5800         cases.push_back(CaseParameter("none",                                   "None"));
5801         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5802         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5803         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5804         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5805         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5806
5807         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5808
5809         for (size_t ndx = 0; ndx < numElements; ++ndx)
5810                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5811
5812         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5813         {
5814                 map<string, string>             specializations;
5815                 ComputeShaderSpec               spec;
5816
5817                 specializations["ACCESS"] = cases[caseNdx].param;
5818                 spec.assembly = shaderTemplate.specialize(specializations);
5819                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5820                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5821                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5822
5823                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5824         }
5825
5826         return group.release();
5827 }
5828
5829 // Checks that we can get undefined values for various types, without exercising a computation with it.
5830 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5831 {
5832         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5833         vector<CaseParameter>                   cases;
5834         de::Random                                              rnd                             (deStringHash(group->getName()));
5835         const int                                               numElements             = 100;
5836         vector<float>                                   positiveFloats  (numElements, 0);
5837         vector<float>                                   negativeFloats  (numElements, 0);
5838         const StringTemplate                    shaderTemplate  (
5839                 string(getComputeAsmShaderPreamble()) +
5840
5841                 "OpSource GLSL 430\n"
5842                 "OpName %main           \"main\"\n"
5843                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5844
5845                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5846
5847                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5848                 "%uvec2     = OpTypeVector %u32 2\n"
5849                 "%fvec4     = OpTypeVector %f32 4\n"
5850                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5851                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5852                 "%sampler   = OpTypeSampler\n"
5853                 "%simage    = OpTypeSampledImage %image\n"
5854                 "%const100  = OpConstant %u32 100\n"
5855                 "%uarr100   = OpTypeArray %i32 %const100\n"
5856                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5857                 "%pointer   = OpTypePointer Function %i32\n"
5858                 + string(getComputeAsmInputOutputBuffer()) +
5859
5860                 "%id        = OpVariable %uvec3ptr Input\n"
5861                 "%zero      = OpConstant %i32 0\n"
5862
5863                 "%main      = OpFunction %void None %voidf\n"
5864                 "%label     = OpLabel\n"
5865
5866                 "%undef     = OpUndef ${TYPE}\n"
5867
5868                 "%idval     = OpLoad %uvec3 %id\n"
5869                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5870
5871                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5872                 "%inval     = OpLoad %f32 %inloc\n"
5873                 "%neg       = OpFNegate %f32 %inval\n"
5874                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5875                 "             OpStore %outloc %neg\n"
5876                 "             OpReturn\n"
5877                 "             OpFunctionEnd\n");
5878
5879         cases.push_back(CaseParameter("bool",                   "%bool"));
5880         cases.push_back(CaseParameter("sint32",                 "%i32"));
5881         cases.push_back(CaseParameter("uint32",                 "%u32"));
5882         cases.push_back(CaseParameter("float32",                "%f32"));
5883         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5884         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5885         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5886         cases.push_back(CaseParameter("image",                  "%image"));
5887         cases.push_back(CaseParameter("sampler",                "%sampler"));
5888         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5889         cases.push_back(CaseParameter("array",                  "%uarr100"));
5890         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5891         cases.push_back(CaseParameter("struct",                 "%struct"));
5892         cases.push_back(CaseParameter("pointer",                "%pointer"));
5893
5894         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5895
5896         for (size_t ndx = 0; ndx < numElements; ++ndx)
5897                 negativeFloats[ndx] = -positiveFloats[ndx];
5898
5899         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5900         {
5901                 map<string, string>             specializations;
5902                 ComputeShaderSpec               spec;
5903
5904                 specializations["TYPE"] = cases[caseNdx].param;
5905                 spec.assembly = shaderTemplate.specialize(specializations);
5906                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5907                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5908                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5909
5910                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5911         }
5912
5913                 return group.release();
5914 }
5915
5916 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
5917 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5918 {
5919         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5920         vector<CaseParameter>                   cases;
5921         de::Random                                              rnd                             (deStringHash(group->getName()));
5922         const int                                               numElements             = 100;
5923         vector<float>                                   positiveFloats  (numElements, 0);
5924         vector<float>                                   negativeFloats  (numElements, 0);
5925         const StringTemplate                    shaderTemplate  (
5926                 "OpCapability Shader\n"
5927                 "OpCapability Float16\n"
5928                 "OpMemoryModel Logical GLSL450\n"
5929                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5930                 "OpExecutionMode %main LocalSize 1 1 1\n"
5931                 "OpSource GLSL 430\n"
5932                 "OpName %main           \"main\"\n"
5933                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5934
5935                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5936
5937                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5938
5939                 "%id        = OpVariable %uvec3ptr Input\n"
5940                 "%zero      = OpConstant %i32 0\n"
5941                 "%f16       = OpTypeFloat 16\n"
5942                 "%c_f16_0   = OpConstant %f16 0.0\n"
5943                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
5944                 "%c_f16_1   = OpConstant %f16 1.0\n"
5945                 "%v2f16     = OpTypeVector %f16 2\n"
5946                 "%v3f16     = OpTypeVector %f16 3\n"
5947                 "%v4f16     = OpTypeVector %f16 4\n"
5948
5949                 "${CONSTANT}\n"
5950
5951                 "%main      = OpFunction %void None %voidf\n"
5952                 "%label     = OpLabel\n"
5953                 "%idval     = OpLoad %uvec3 %id\n"
5954                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5955                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5956                 "%inval     = OpLoad %f32 %inloc\n"
5957                 "%neg       = OpFNegate %f32 %inval\n"
5958                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5959                 "             OpStore %outloc %neg\n"
5960                 "             OpReturn\n"
5961                 "             OpFunctionEnd\n");
5962
5963
5964         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5965         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5966                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5967                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5968         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5969                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5970                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5971                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5972                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5973         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
5974                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
5975                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
5976                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5977                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
5978                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
5979
5980         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5981
5982         for (size_t ndx = 0; ndx < numElements; ++ndx)
5983                 negativeFloats[ndx] = -positiveFloats[ndx];
5984
5985         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5986         {
5987                 map<string, string>             specializations;
5988                 ComputeShaderSpec               spec;
5989
5990                 specializations["CONSTANT"] = cases[caseNdx].param;
5991                 spec.assembly = shaderTemplate.specialize(specializations);
5992                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5993                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5994                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5995
5996                 spec.extensions.push_back("VK_KHR_16bit_storage");
5997                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
5998
5999                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6000                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6001
6002                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6003         }
6004
6005         return group.release();
6006 }
6007
6008 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6009 {
6010         const size_t            inDataLength    = inData.size();
6011         vector<deFloat16>       result;
6012
6013         result.reserve(inDataLength * inDataLength);
6014
6015         if (argNo == 0)
6016         {
6017                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6018                         result.insert(result.end(), inData.begin(), inData.end());
6019         }
6020
6021         if (argNo == 1)
6022         {
6023                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6024                 {
6025                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6026
6027                         result.insert(result.end(), tmp.begin(), tmp.end());
6028                 }
6029         }
6030
6031         return result;
6032 }
6033
6034 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6035 {
6036         vector<deFloat16>       vec;
6037         vector<deFloat16>       result;
6038
6039         // Create vectors. vec will contain each possible pair from inData
6040         {
6041                 const size_t    inDataLength    = inData.size();
6042
6043                 DE_ASSERT(inDataLength <= 64);
6044
6045                 vec.reserve(2 * inDataLength * inDataLength);
6046
6047                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6048                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6049                 {
6050                         vec.push_back(inData[numIdxX]);
6051                         vec.push_back(inData[numIdxY]);
6052                 }
6053         }
6054
6055         // Create vector pairs. result will contain each possible pair from vec
6056         {
6057                 const size_t    coordsPerVector = 2;
6058                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6059
6060                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6061
6062                 if (argNo == 0)
6063                 {
6064                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6065                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6066                         {
6067                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6068                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6069                         }
6070                 }
6071
6072                 if (argNo == 1)
6073                 {
6074                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6075                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6076                         {
6077                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6078                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6079                         }
6080                 }
6081         }
6082
6083         return result;
6084 }
6085
6086 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6087 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6088 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6089 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6090 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6091 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6092 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6093 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6094
6095 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6096 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6097 {
6098         if (inputs.size() != 2 || outputAllocs.size() != 1)
6099                 return false;
6100
6101         vector<deUint8> input1Bytes;
6102         vector<deUint8> input2Bytes;
6103
6104         inputs[0].getBytes(input1Bytes);
6105         inputs[1].getBytes(input2Bytes);
6106
6107         const deUint32                  denormModesCount                        = 2;
6108         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6109         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6110         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6111         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6112         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6113         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6114         deUint32                                successfulRuns                          = denormModesCount;
6115         std::string                             results[denormModesCount];
6116         TestedLogicalFunction   testedLogicalFunction;
6117
6118         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6119         {
6120                 const bool flushToZero = (denormMode == 1);
6121
6122                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6123                 {
6124                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6125                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6126                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6127                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6128                         deFloat16                       expectedOutput  = float16zero;
6129
6130                         if (onlyTestFunc)
6131                         {
6132                                 if (testedLogicalFunction(f1, f2))
6133                                         expectedOutput = float16one;
6134                         }
6135                         else
6136                         {
6137                                 const bool      f1nan   = f1.isNaN();
6138                                 const bool      f2nan   = f2.isNaN();
6139
6140                                 // Skip NaN floats if not supported by implementation
6141                                 if (!nanSupported && (f1nan || f2nan))
6142                                         continue;
6143
6144                                 if (unationModeAnd)
6145                                 {
6146                                         const bool      ordered         = !f1nan && !f2nan;
6147
6148                                         if (ordered && testedLogicalFunction(f1, f2))
6149                                                 expectedOutput = float16one;
6150                                 }
6151                                 else
6152                                 {
6153                                         const bool      unordered       = f1nan || f2nan;
6154
6155                                         if (unordered || testedLogicalFunction(f1, f2))
6156                                                 expectedOutput = float16one;
6157                                 }
6158                         }
6159
6160                         if (outputAsFP16[idx] != expectedOutput)
6161                         {
6162                                 std::ostringstream str;
6163
6164                                 str << "ERROR: Sub-case #" << idx
6165                                         << " flushToZero:" << flushToZero
6166                                         << std::hex
6167                                         << " failed, inputs: 0x" << f1.bits()
6168                                         << ";0x" << f2.bits()
6169                                         << " output: 0x" << outputAsFP16[idx]
6170                                         << " expected output: 0x" << expectedOutput;
6171
6172                                 results[denormMode] = str.str();
6173
6174                                 successfulRuns--;
6175
6176                                 break;
6177                         }
6178                 }
6179         }
6180
6181         if (successfulRuns == 0)
6182                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6183                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6184
6185         return successfulRuns > 0;
6186 }
6187
6188 } // anonymous
6189
6190 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6191 {
6192         struct NameCodePair { string name, code; };
6193         RGBA                                                    defaultColors[4];
6194         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6195         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6196         map<string, string>                             fragments                               = passthruFragments();
6197         const NameCodePair                              tests[]                                 =
6198         {
6199                 {"unknown", "OpSource Unknown 321"},
6200                 {"essl", "OpSource ESSL 310"},
6201                 {"glsl", "OpSource GLSL 450"},
6202                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6203                 {"opencl_c", "OpSource OpenCL_C 120"},
6204                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6205                 {"file", opsourceGLSLWithFile},
6206                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6207                 // Longest possible source string: SPIR-V limits instructions to 65535
6208                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6209                 // contain 65530 UTF8 characters (one word each) plus one last word
6210                 // containing 3 ASCII characters and \0.
6211                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6212         };
6213
6214         getDefaultColors(defaultColors);
6215         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6216         {
6217                 fragments["debug"] = tests[testNdx].code;
6218                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6219         }
6220
6221         return opSourceTests.release();
6222 }
6223
6224 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6225 {
6226         struct NameCodePair { string name, code; };
6227         RGBA                                                            defaultColors[4];
6228         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6229         map<string, string>                                     fragments                       = passthruFragments();
6230         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6231         const NameCodePair                                      tests[]                         =
6232         {
6233                 {"empty", opsource + "OpSourceContinued \"\""},
6234                 {"short", opsource + "OpSourceContinued \"abcde\""},
6235                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6236                 // Longest possible source string: SPIR-V limits instructions to 65535
6237                 // words, of which the first one is OpSourceContinued/length; the rest
6238                 // will contain 65533 UTF8 characters (one word each) plus one last word
6239                 // containing 3 ASCII characters and \0.
6240                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6241         };
6242
6243         getDefaultColors(defaultColors);
6244         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6245         {
6246                 fragments["debug"] = tests[testNdx].code;
6247                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6248         }
6249
6250         return opSourceTests.release();
6251 }
6252 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6253 {
6254         RGBA                                                             defaultColors[4];
6255         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6256         map<string, string>                                      fragments;
6257         getDefaultColors(defaultColors);
6258         fragments["debug"]                      =
6259                 "%name = OpString \"name\"\n";
6260
6261         fragments["pre_main"]   =
6262                 "OpNoLine\n"
6263                 "OpNoLine\n"
6264                 "OpLine %name 1 1\n"
6265                 "OpNoLine\n"
6266                 "OpLine %name 1 1\n"
6267                 "OpLine %name 1 1\n"
6268                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6269                 "OpNoLine\n"
6270                 "OpLine %name 1 1\n"
6271                 "OpNoLine\n"
6272                 "OpLine %name 1 1\n"
6273                 "OpLine %name 1 1\n"
6274                 "%second_param1 = OpFunctionParameter %v4f32\n"
6275                 "OpNoLine\n"
6276                 "OpNoLine\n"
6277                 "%label_secondfunction = OpLabel\n"
6278                 "OpNoLine\n"
6279                 "OpReturnValue %second_param1\n"
6280                 "OpFunctionEnd\n"
6281                 "OpNoLine\n"
6282                 "OpNoLine\n";
6283
6284         fragments["testfun"]            =
6285                 // A %test_code function that returns its argument unchanged.
6286                 "OpNoLine\n"
6287                 "OpNoLine\n"
6288                 "OpLine %name 1 1\n"
6289                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6290                 "OpNoLine\n"
6291                 "%param1 = OpFunctionParameter %v4f32\n"
6292                 "OpNoLine\n"
6293                 "OpNoLine\n"
6294                 "%label_testfun = OpLabel\n"
6295                 "OpNoLine\n"
6296                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6297                 "OpReturnValue %val1\n"
6298                 "OpFunctionEnd\n"
6299                 "OpLine %name 1 1\n"
6300                 "OpNoLine\n";
6301
6302         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6303
6304         return opLineTests.release();
6305 }
6306
6307 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6308 {
6309         RGBA                                                            defaultColors[4];
6310         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6311         map<string, string>                                     fragments;
6312         std::vector<std::string>                        noExtensions;
6313         GraphicsResources                                       resources;
6314
6315         getDefaultColors(defaultColors);
6316         resources.verifyBinary = veryfiBinaryShader;
6317         resources.spirvVersion = SPIRV_VERSION_1_3;
6318
6319         fragments["moduleprocessed"]                                                    =
6320                 "OpModuleProcessed \"VULKAN CTS\"\n"
6321                 "OpModuleProcessed \"Negative values\"\n"
6322                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6323
6324         fragments["pre_main"]   =
6325                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6326                 "%second_param1 = OpFunctionParameter %v4f32\n"
6327                 "%label_secondfunction = OpLabel\n"
6328                 "OpReturnValue %second_param1\n"
6329                 "OpFunctionEnd\n";
6330
6331         fragments["testfun"]            =
6332                 // A %test_code function that returns its argument unchanged.
6333                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6334                 "%param1 = OpFunctionParameter %v4f32\n"
6335                 "%label_testfun = OpLabel\n"
6336                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6337                 "OpReturnValue %val1\n"
6338                 "OpFunctionEnd\n";
6339
6340         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6341
6342         return opModuleProcessedTests.release();
6343 }
6344
6345
6346 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6347 {
6348         RGBA                                                                                                    defaultColors[4];
6349         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6350         map<string, string>                                                                             fragments;
6351         std::vector<std::pair<std::string, std::string> >               problemStrings;
6352
6353         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6354         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6355         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6356         getDefaultColors(defaultColors);
6357
6358         fragments["debug"]                      =
6359                 "%other_name = OpString \"other_name\"\n";
6360
6361         fragments["pre_main"]   =
6362                 "OpLine %file_name 32 0\n"
6363                 "OpLine %file_name 32 32\n"
6364                 "OpLine %file_name 32 40\n"
6365                 "OpLine %other_name 32 40\n"
6366                 "OpLine %other_name 0 100\n"
6367                 "OpLine %other_name 0 4294967295\n"
6368                 "OpLine %other_name 4294967295 0\n"
6369                 "OpLine %other_name 32 40\n"
6370                 "OpLine %file_name 0 0\n"
6371                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6372                 "OpLine %file_name 1 0\n"
6373                 "%second_param1 = OpFunctionParameter %v4f32\n"
6374                 "OpLine %file_name 1 3\n"
6375                 "OpLine %file_name 1 2\n"
6376                 "%label_secondfunction = OpLabel\n"
6377                 "OpLine %file_name 0 2\n"
6378                 "OpReturnValue %second_param1\n"
6379                 "OpFunctionEnd\n"
6380                 "OpLine %file_name 0 2\n"
6381                 "OpLine %file_name 0 2\n";
6382
6383         fragments["testfun"]            =
6384                 // A %test_code function that returns its argument unchanged.
6385                 "OpLine %file_name 1 0\n"
6386                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6387                 "OpLine %file_name 16 330\n"
6388                 "%param1 = OpFunctionParameter %v4f32\n"
6389                 "OpLine %file_name 14 442\n"
6390                 "%label_testfun = OpLabel\n"
6391                 "OpLine %file_name 11 1024\n"
6392                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6393                 "OpLine %file_name 2 97\n"
6394                 "OpReturnValue %val1\n"
6395                 "OpFunctionEnd\n"
6396                 "OpLine %file_name 5 32\n";
6397
6398         for (size_t i = 0; i < problemStrings.size(); ++i)
6399         {
6400                 map<string, string> testFragments = fragments;
6401                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6402                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6403         }
6404
6405         return opLineTests.release();
6406 }
6407
6408 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6409 {
6410         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6411         RGBA                                                    colors[4];
6412
6413
6414         const char                                              functionStart[] =
6415                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6416                 "%param1 = OpFunctionParameter %v4f32\n"
6417                 "%lbl    = OpLabel\n";
6418
6419         const char                                              functionEnd[]   =
6420                 "OpReturnValue %transformed_param\n"
6421                 "OpFunctionEnd\n";
6422
6423         struct NameConstantsCode
6424         {
6425                 string name;
6426                 string constants;
6427                 string code;
6428         };
6429
6430         NameConstantsCode tests[] =
6431         {
6432                 {
6433                         "vec4",
6434                         "%cnull = OpConstantNull %v4f32\n",
6435                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6436                 },
6437                 {
6438                         "float",
6439                         "%cnull = OpConstantNull %f32\n",
6440                         "%vp = OpVariable %fp_v4f32 Function\n"
6441                         "%v  = OpLoad %v4f32 %vp\n"
6442                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6443                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6444                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6445                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6446                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6447                 },
6448                 {
6449                         "bool",
6450                         "%cnull             = OpConstantNull %bool\n",
6451                         "%v                 = OpVariable %fp_v4f32 Function\n"
6452                         "                     OpStore %v %param1\n"
6453                         "                     OpSelectionMerge %false_label None\n"
6454                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6455                         "%true_label        = OpLabel\n"
6456                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6457                         "                     OpBranch %false_label\n"
6458                         "%false_label       = OpLabel\n"
6459                         "%transformed_param = OpLoad %v4f32 %v\n"
6460                 },
6461                 {
6462                         "i32",
6463                         "%cnull             = OpConstantNull %i32\n",
6464                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6465                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6466                         "                     OpSelectionMerge %false_label None\n"
6467                         "                     OpBranchConditional %b %true_label %false_label\n"
6468                         "%true_label        = OpLabel\n"
6469                         "                     OpStore %v %param1\n"
6470                         "                     OpBranch %false_label\n"
6471                         "%false_label       = OpLabel\n"
6472                         "%transformed_param = OpLoad %v4f32 %v\n"
6473                 },
6474                 {
6475                         "struct",
6476                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6477                         "%fp_stype          = OpTypePointer Function %stype\n"
6478                         "%cnull             = OpConstantNull %stype\n",
6479                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6480                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6481                         "%f_val             = OpLoad %v4f32 %f\n"
6482                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6483                 },
6484                 {
6485                         "array",
6486                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6487                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6488                         "%cnull             = OpConstantNull %a4_v4f32\n",
6489                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6490                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6491                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6492                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6493                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6494                         "%f_val             = OpLoad %v4f32 %f\n"
6495                         "%f1_val            = OpLoad %v4f32 %f1\n"
6496                         "%f2_val            = OpLoad %v4f32 %f2\n"
6497                         "%f3_val            = OpLoad %v4f32 %f3\n"
6498                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6499                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6500                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6501                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6502                 },
6503                 {
6504                         "matrix",
6505                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6506                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6507                         // Our null matrix * any vector should result in a zero vector.
6508                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6509                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6510                 }
6511         };
6512
6513         getHalfColorsFullAlpha(colors);
6514
6515         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6516         {
6517                 map<string, string> fragments;
6518                 fragments["pre_main"] = tests[testNdx].constants;
6519                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6520                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6521         }
6522         return opConstantNullTests.release();
6523 }
6524 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6525 {
6526         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6527         RGBA                                                    inputColors[4];
6528         RGBA                                                    outputColors[4];
6529
6530
6531         const char                                              functionStart[]  =
6532                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6533                 "%param1 = OpFunctionParameter %v4f32\n"
6534                 "%lbl    = OpLabel\n";
6535
6536         const char                                              functionEnd[]           =
6537                 "OpReturnValue %transformed_param\n"
6538                 "OpFunctionEnd\n";
6539
6540         struct NameConstantsCode
6541         {
6542                 string name;
6543                 string constants;
6544                 string code;
6545         };
6546
6547         NameConstantsCode tests[] =
6548         {
6549                 {
6550                         "vec4",
6551
6552                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6553                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6554                 },
6555                 {
6556                         "struct",
6557
6558                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6559                         "%fp_stype          = OpTypePointer Function %stype\n"
6560                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6561                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6562                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6563                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6564
6565                         "%v                 = OpVariable %fp_stype Function %cval\n"
6566                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6567                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6568                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6569                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6570                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6571                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6572                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6573                 },
6574                 {
6575                         // [1|0|0|0.5] [x] = x + 0.5
6576                         // [0|1|0|0.5] [y] = y + 0.5
6577                         // [0|0|1|0.5] [z] = z + 0.5
6578                         // [0|0|0|1  ] [1] = 1
6579                         "matrix",
6580
6581                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6582                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6583                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6584                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6585                         "%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"
6586                         "%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",
6587
6588                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6589                 },
6590                 {
6591                         "array",
6592
6593                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6594                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6595                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6596                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6597                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6598
6599                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6600                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6601                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6602                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6603                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6604                         "%f_val               = OpLoad %f32 %f\n"
6605                         "%f1_val              = OpLoad %f32 %f1\n"
6606                         "%f2_val              = OpLoad %f32 %f2\n"
6607                         "%f3_val              = OpLoad %f32 %f3\n"
6608                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6609                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6610                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6611                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6612                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6613                 },
6614                 {
6615                         //
6616                         // [
6617                         //   {
6618                         //      0.0,
6619                         //      [ 1.0, 1.0, 1.0, 1.0]
6620                         //   },
6621                         //   {
6622                         //      1.0,
6623                         //      [ 0.0, 0.5, 0.0, 0.0]
6624                         //   }, //     ^^^
6625                         //   {
6626                         //      0.0,
6627                         //      [ 1.0, 1.0, 1.0, 1.0]
6628                         //   }
6629                         // ]
6630                         "array_of_struct_of_array",
6631
6632                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6633                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6634                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6635                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6636                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6637                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6638                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6639                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6640                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6641                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6642
6643                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6644                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6645                         "%f_l                 = OpLoad %f32 %f\n"
6646                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6647                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6648                 }
6649         };
6650
6651         getHalfColorsFullAlpha(inputColors);
6652         outputColors[0] = RGBA(255, 255, 255, 255);
6653         outputColors[1] = RGBA(255, 127, 127, 255);
6654         outputColors[2] = RGBA(127, 255, 127, 255);
6655         outputColors[3] = RGBA(127, 127, 255, 255);
6656
6657         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6658         {
6659                 map<string, string> fragments;
6660                 fragments["pre_main"] = tests[testNdx].constants;
6661                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6662                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6663         }
6664         return opConstantCompositeTests.release();
6665 }
6666
6667 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6668 {
6669         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6670         RGBA                                                    inputColors[4];
6671         RGBA                                                    outputColors[4];
6672         map<string, string>                             fragments;
6673
6674         // vec4 test_code(vec4 param) {
6675         //   vec4 result = param;
6676         //   for (int i = 0; i < 4; ++i) {
6677         //     if (i == 0) result[i] = 0.;
6678         //     else        result[i] = 1. - result[i];
6679         //   }
6680         //   return result;
6681         // }
6682         const char                                              function[]                      =
6683                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6684                 "%param1    = OpFunctionParameter %v4f32\n"
6685                 "%lbl       = OpLabel\n"
6686                 "%iptr      = OpVariable %fp_i32 Function\n"
6687                 "%result    = OpVariable %fp_v4f32 Function\n"
6688                 "             OpStore %iptr %c_i32_0\n"
6689                 "             OpStore %result %param1\n"
6690                 "             OpBranch %loop\n"
6691
6692                 // Loop entry block.
6693                 "%loop      = OpLabel\n"
6694                 "%ival      = OpLoad %i32 %iptr\n"
6695                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6696                 "             OpLoopMerge %exit %if_entry None\n"
6697                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6698
6699                 // Merge block for loop.
6700                 "%exit      = OpLabel\n"
6701                 "%ret       = OpLoad %v4f32 %result\n"
6702                 "             OpReturnValue %ret\n"
6703
6704                 // If-statement entry block.
6705                 "%if_entry  = OpLabel\n"
6706                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6707                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6708                 "             OpSelectionMerge %if_exit None\n"
6709                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6710
6711                 // False branch for if-statement.
6712                 "%if_false  = OpLabel\n"
6713                 "%val       = OpLoad %f32 %loc\n"
6714                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6715                 "             OpStore %loc %sub\n"
6716                 "             OpBranch %if_exit\n"
6717
6718                 // Merge block for if-statement.
6719                 "%if_exit   = OpLabel\n"
6720                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6721                 "             OpStore %iptr %ival_next\n"
6722                 "             OpBranch %loop\n"
6723
6724                 // True branch for if-statement.
6725                 "%if_true   = OpLabel\n"
6726                 "             OpStore %loc %c_f32_0\n"
6727                 "             OpBranch %if_exit\n"
6728
6729                 "             OpFunctionEnd\n";
6730
6731         fragments["testfun"]    = function;
6732
6733         inputColors[0]                  = RGBA(127, 127, 127, 0);
6734         inputColors[1]                  = RGBA(127, 0,   0,   0);
6735         inputColors[2]                  = RGBA(0,   127, 0,   0);
6736         inputColors[3]                  = RGBA(0,   0,   127, 0);
6737
6738         outputColors[0]                 = RGBA(0, 128, 128, 255);
6739         outputColors[1]                 = RGBA(0, 255, 255, 255);
6740         outputColors[2]                 = RGBA(0, 128, 255, 255);
6741         outputColors[3]                 = RGBA(0, 255, 128, 255);
6742
6743         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6744
6745         return group.release();
6746 }
6747
6748 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6749 {
6750         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6751         RGBA                                                    inputColors[4];
6752         RGBA                                                    outputColors[4];
6753         map<string, string>                             fragments;
6754
6755         const char                                              typesAndConstants[]     =
6756                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6757                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6758                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6759                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6760
6761         // vec4 test_code(vec4 param) {
6762         //   vec4 result = param;
6763         //   for (int i = 0; i < 4; ++i) {
6764         //     switch (i) {
6765         //       case 0: result[i] += .2; break;
6766         //       case 1: result[i] += .6; break;
6767         //       case 2: result[i] += .4; break;
6768         //       case 3: result[i] += .8; break;
6769         //       default: break; // unreachable
6770         //     }
6771         //   }
6772         //   return result;
6773         // }
6774         const char                                              function[]                      =
6775                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6776                 "%param1    = OpFunctionParameter %v4f32\n"
6777                 "%lbl       = OpLabel\n"
6778                 "%iptr      = OpVariable %fp_i32 Function\n"
6779                 "%result    = OpVariable %fp_v4f32 Function\n"
6780                 "             OpStore %iptr %c_i32_0\n"
6781                 "             OpStore %result %param1\n"
6782                 "             OpBranch %loop\n"
6783
6784                 // Loop entry block.
6785                 "%loop      = OpLabel\n"
6786                 "%ival      = OpLoad %i32 %iptr\n"
6787                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6788                 "             OpLoopMerge %exit %switch_exit None\n"
6789                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6790
6791                 // Merge block for loop.
6792                 "%exit      = OpLabel\n"
6793                 "%ret       = OpLoad %v4f32 %result\n"
6794                 "             OpReturnValue %ret\n"
6795
6796                 // Switch-statement entry block.
6797                 "%switch_entry   = OpLabel\n"
6798                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6799                 "%val            = OpLoad %f32 %loc\n"
6800                 "                  OpSelectionMerge %switch_exit None\n"
6801                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6802
6803                 "%case2          = OpLabel\n"
6804                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6805                 "                  OpStore %loc %addp4\n"
6806                 "                  OpBranch %switch_exit\n"
6807
6808                 "%switch_default = OpLabel\n"
6809                 "                  OpUnreachable\n"
6810
6811                 "%case3          = OpLabel\n"
6812                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6813                 "                  OpStore %loc %addp8\n"
6814                 "                  OpBranch %switch_exit\n"
6815
6816                 "%case0          = OpLabel\n"
6817                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6818                 "                  OpStore %loc %addp2\n"
6819                 "                  OpBranch %switch_exit\n"
6820
6821                 // Merge block for switch-statement.
6822                 "%switch_exit    = OpLabel\n"
6823                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6824                 "                  OpStore %iptr %ival_next\n"
6825                 "                  OpBranch %loop\n"
6826
6827                 "%case1          = OpLabel\n"
6828                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6829                 "                  OpStore %loc %addp6\n"
6830                 "                  OpBranch %switch_exit\n"
6831
6832                 "                  OpFunctionEnd\n";
6833
6834         fragments["pre_main"]   = typesAndConstants;
6835         fragments["testfun"]    = function;
6836
6837         inputColors[0]                  = RGBA(127, 27,  127, 51);
6838         inputColors[1]                  = RGBA(127, 0,   0,   51);
6839         inputColors[2]                  = RGBA(0,   27,  0,   51);
6840         inputColors[3]                  = RGBA(0,   0,   127, 51);
6841
6842         outputColors[0]                 = RGBA(178, 180, 229, 255);
6843         outputColors[1]                 = RGBA(178, 153, 102, 255);
6844         outputColors[2]                 = RGBA(51,  180, 102, 255);
6845         outputColors[3]                 = RGBA(51,  153, 229, 255);
6846
6847         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6848
6849         return group.release();
6850 }
6851
6852 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6853 {
6854         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6855         RGBA                                                    inputColors[4];
6856         RGBA                                                    outputColors[4];
6857         map<string, string>                             fragments;
6858
6859         const char                                              decorations[]           =
6860                 "OpDecorate %array_group         ArrayStride 4\n"
6861                 "OpDecorate %struct_member_group Offset 0\n"
6862                 "%array_group         = OpDecorationGroup\n"
6863                 "%struct_member_group = OpDecorationGroup\n"
6864
6865                 "OpDecorate %group1 RelaxedPrecision\n"
6866                 "OpDecorate %group3 RelaxedPrecision\n"
6867                 "OpDecorate %group3 Invariant\n"
6868                 "OpDecorate %group3 Restrict\n"
6869                 "%group0 = OpDecorationGroup\n"
6870                 "%group1 = OpDecorationGroup\n"
6871                 "%group3 = OpDecorationGroup\n";
6872
6873         const char                                              typesAndConstants[]     =
6874                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6875                 "%struct1   = OpTypeStruct %a3f32\n"
6876                 "%struct2   = OpTypeStruct %a3f32\n"
6877                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6878                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6879                 "%c_f32_2    = OpConstant %f32 2.\n"
6880                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6881
6882                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6883                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6884                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6885                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6886
6887         const char                                              function[]                      =
6888                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6889                 "%param     = OpFunctionParameter %v4f32\n"
6890                 "%entry     = OpLabel\n"
6891                 "%result    = OpVariable %fp_v4f32 Function\n"
6892                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6893                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6894                 "             OpStore %result %param\n"
6895                 "             OpStore %v_struct1 %c_struct1\n"
6896                 "             OpStore %v_struct2 %c_struct2\n"
6897                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6898                 "%val1      = OpLoad %f32 %ptr1\n"
6899                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6900                 "%val2      = OpLoad %f32 %ptr2\n"
6901                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6902                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6903                 "%val       = OpLoad %f32 %ptr\n"
6904                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6905                 "             OpStore %ptr %addresult\n"
6906                 "%ret       = OpLoad %v4f32 %result\n"
6907                 "             OpReturnValue %ret\n"
6908                 "             OpFunctionEnd\n";
6909
6910         struct CaseNameDecoration
6911         {
6912                 string name;
6913                 string decoration;
6914         };
6915
6916         CaseNameDecoration tests[] =
6917         {
6918                 {
6919                         "same_decoration_group_on_multiple_types",
6920                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6921                 },
6922                 {
6923                         "empty_decoration_group",
6924                         "OpGroupDecorate %group0      %a3f32\n"
6925                         "OpGroupDecorate %group0      %result\n"
6926                 },
6927                 {
6928                         "one_element_decoration_group",
6929                         "OpGroupDecorate %array_group %a3f32\n"
6930                 },
6931                 {
6932                         "multiple_elements_decoration_group",
6933                         "OpGroupDecorate %group3      %v_struct1\n"
6934                 },
6935                 {
6936                         "multiple_decoration_groups_on_same_variable",
6937                         "OpGroupDecorate %group0      %v_struct2\n"
6938                         "OpGroupDecorate %group1      %v_struct2\n"
6939                         "OpGroupDecorate %group3      %v_struct2\n"
6940                 },
6941                 {
6942                         "same_decoration_group_multiple_times",
6943                         "OpGroupDecorate %group1      %addvalues\n"
6944                         "OpGroupDecorate %group1      %addvalues\n"
6945                         "OpGroupDecorate %group1      %addvalues\n"
6946                 },
6947
6948         };
6949
6950         getHalfColorsFullAlpha(inputColors);
6951         getHalfColorsFullAlpha(outputColors);
6952
6953         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6954         {
6955                 fragments["decoration"] = decorations + tests[idx].decoration;
6956                 fragments["pre_main"]   = typesAndConstants;
6957                 fragments["testfun"]    = function;
6958
6959                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6960         }
6961
6962         return group.release();
6963 }
6964
6965 struct SpecConstantTwoIntGraphicsCase
6966 {
6967         const char*             caseName;
6968         const char*             scDefinition0;
6969         const char*             scDefinition1;
6970         const char*             scResultType;
6971         const char*             scOperation;
6972         deInt32                 scActualValue0;
6973         deInt32                 scActualValue1;
6974         const char*             resultOperation;
6975         RGBA                    expectedColors[4];
6976         deInt32                 scActualValueLength;
6977
6978                                         SpecConstantTwoIntGraphicsCase (const char*             name,
6979                                                                                                         const char*             definition0,
6980                                                                                                         const char*             definition1,
6981                                                                                                         const char*             resultType,
6982                                                                                                         const char*             operation,
6983                                                                                                         const deInt32   value0,
6984                                                                                                         const deInt32   value1,
6985                                                                                                         const char*             resultOp,
6986                                                                                                         const RGBA              (&output)[4],
6987                                                                                                         const deInt32   valueLength = sizeof(deInt32))
6988                                                 : caseName                              (name)
6989                                                 , scDefinition0                 (definition0)
6990                                                 , scDefinition1                 (definition1)
6991                                                 , scResultType                  (resultType)
6992                                                 , scOperation                   (operation)
6993                                                 , scActualValue0                (value0)
6994                                                 , scActualValue1                (value1)
6995                                                 , resultOperation               (resultOp)
6996                                                 , scActualValueLength   (valueLength)
6997         {
6998                 expectedColors[0] = output[0];
6999                 expectedColors[1] = output[1];
7000                 expectedColors[2] = output[2];
7001                 expectedColors[3] = output[3];
7002         }
7003 };
7004
7005 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7006 {
7007         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7008         vector<SpecConstantTwoIntGraphicsCase>  cases;
7009         RGBA                                                    inputColors[4];
7010         RGBA                                                    outputColors0[4];
7011         RGBA                                                    outputColors1[4];
7012         RGBA                                                    outputColors2[4];
7013
7014         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7015
7016         const char      decorations1[]                  =
7017                 "OpDecorate %sc_0  SpecId 0\n"
7018                 "OpDecorate %sc_1  SpecId 1\n";
7019
7020         const char      typesAndConstants1[]    =
7021                 "${OPTYPE_DEFINITIONS:opt}"
7022                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7023                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7024                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7025
7026         const char      function1[]                             =
7027                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7028                 "%param     = OpFunctionParameter %v4f32\n"
7029                 "%label     = OpLabel\n"
7030                 "%result    = OpVariable %fp_v4f32 Function\n"
7031                 "${TYPE_CONVERT:opt}"
7032                 "             OpStore %result %param\n"
7033                 "%gen       = ${GEN_RESULT}\n"
7034                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7035                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7036                 "%val       = OpLoad %f32 %loc\n"
7037                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7038                 "             OpStore %loc %add\n"
7039                 "%ret       = OpLoad %v4f32 %result\n"
7040                 "             OpReturnValue %ret\n"
7041                 "             OpFunctionEnd\n";
7042
7043         inputColors[0] = RGBA(127, 127, 127, 255);
7044         inputColors[1] = RGBA(127, 0,   0,   255);
7045         inputColors[2] = RGBA(0,   127, 0,   255);
7046         inputColors[3] = RGBA(0,   0,   127, 255);
7047
7048         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7049         outputColors0[0] = RGBA(255, 127, 127, 255);
7050         outputColors0[1] = RGBA(255, 0,   0,   255);
7051         outputColors0[2] = RGBA(128, 127, 0,   255);
7052         outputColors0[3] = RGBA(128, 0,   127, 255);
7053
7054         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7055         outputColors1[0] = RGBA(127, 255, 127, 255);
7056         outputColors1[1] = RGBA(127, 128, 0,   255);
7057         outputColors1[2] = RGBA(0,   255, 0,   255);
7058         outputColors1[3] = RGBA(0,   128, 127, 255);
7059
7060         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7061         outputColors2[0] = RGBA(127, 127, 255, 255);
7062         outputColors2[1] = RGBA(127, 0,   128, 255);
7063         outputColors2[2] = RGBA(0,   127, 128, 255);
7064         outputColors2[3] = RGBA(0,   0,   255, 255);
7065
7066         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7067         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7068         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7069         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7070
7071         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7072         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7073         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7074         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7075         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7076         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7077         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7078         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7079         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7080         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7081         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7082         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7083         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7084         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7085         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7086         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7087         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7088         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7089         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7090         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7091         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7092         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7093         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7094         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7095         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7096         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7097         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7098         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7099         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7100         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7101         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7102         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7103         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7104         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7105         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7106         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7107         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7108
7109         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7110         {
7111                 map<string, string>                     specializations;
7112                 map<string, string>                     fragments;
7113                 SpecConstants                           specConstants;
7114                 PushConstants                           noPushConstants;
7115                 GraphicsResources                       noResources;
7116                 GraphicsInterfaces                      noInterfaces;
7117                 vector<string>                          extensions;
7118                 VulkanFeatures                          requiredFeatures;
7119
7120                 // Special SPIR-V code for SConvert-case
7121                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7122                 {
7123                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7124                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7125                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7126                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7127                 }
7128
7129                 // Special SPIR-V code for FConvert-case
7130                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7131                 {
7132                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7133                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7134                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7135                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7136                 }
7137
7138                 // Special SPIR-V code for FConvert-case for 16-bit floats
7139                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7140                 {
7141                         extensions.push_back("VK_KHR_shader_float16_int8");
7142                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7143                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7144                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7145                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7146                 }
7147
7148                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7149                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7150                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7151                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7152                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7153
7154                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7155                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7156                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7157
7158                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7159                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7160
7161                 createTestsForAllStages(
7162                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7163                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7164         }
7165
7166         const char      decorations2[]                  =
7167                 "OpDecorate %sc_0  SpecId 0\n"
7168                 "OpDecorate %sc_1  SpecId 1\n"
7169                 "OpDecorate %sc_2  SpecId 2\n";
7170
7171         const char      typesAndConstants2[]    =
7172                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7173                 "%vec3_undef  = OpUndef %v3i32\n"
7174
7175                 "%sc_0        = OpSpecConstant %i32 0\n"
7176                 "%sc_1        = OpSpecConstant %i32 0\n"
7177                 "%sc_2        = OpSpecConstant %i32 0\n"
7178                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7179                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7180                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7181                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7182                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7183                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7184                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7185                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7186                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7187                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7188                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7189                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7190                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7191
7192         const char      function2[]                             =
7193                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7194                 "%param     = OpFunctionParameter %v4f32\n"
7195                 "%label     = OpLabel\n"
7196                 "%result    = OpVariable %fp_v4f32 Function\n"
7197                 "             OpStore %result %param\n"
7198                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7199                 "%val       = OpLoad %f32 %loc\n"
7200                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7201                 "             OpStore %loc %add\n"
7202                 "%ret       = OpLoad %v4f32 %result\n"
7203                 "             OpReturnValue %ret\n"
7204                 "             OpFunctionEnd\n";
7205
7206         map<string, string>     fragments;
7207         SpecConstants           specConstants;
7208
7209         fragments["decoration"] = decorations2;
7210         fragments["pre_main"]   = typesAndConstants2;
7211         fragments["testfun"]    = function2;
7212
7213         specConstants.append<deInt32>(56789);
7214         specConstants.append<deInt32>(-2);
7215         specConstants.append<deInt32>(56788);
7216
7217         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7218
7219         return group.release();
7220 }
7221
7222 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7223 {
7224         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7225         RGBA                                                    inputColors[4];
7226         RGBA                                                    outputColors1[4];
7227         RGBA                                                    outputColors2[4];
7228         RGBA                                                    outputColors3[4];
7229         RGBA                                                    outputColors4[4];
7230         map<string, string>                             fragments1;
7231         map<string, string>                             fragments2;
7232         map<string, string>                             fragments3;
7233         map<string, string>                             fragments4;
7234         std::vector<std::string>                extensions4;
7235         GraphicsResources                               resources4;
7236         VulkanFeatures                                  vulkanFeatures4;
7237
7238         const char      typesAndConstants1[]    =
7239                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7240                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7241                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7242                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7243
7244         // vec4 test_code(vec4 param) {
7245         //   vec4 result = param;
7246         //   for (int i = 0; i < 4; ++i) {
7247         //     float operand;
7248         //     switch (i) {
7249         //       case 0: operand = .2; break;
7250         //       case 1: operand = .5; break;
7251         //       case 2: operand = .4; break;
7252         //       case 3: operand = .0; break;
7253         //       default: break; // unreachable
7254         //     }
7255         //     result[i] += operand;
7256         //   }
7257         //   return result;
7258         // }
7259         const char      function1[]                             =
7260                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7261                 "%param1    = OpFunctionParameter %v4f32\n"
7262                 "%lbl       = OpLabel\n"
7263                 "%iptr      = OpVariable %fp_i32 Function\n"
7264                 "%result    = OpVariable %fp_v4f32 Function\n"
7265                 "             OpStore %iptr %c_i32_0\n"
7266                 "             OpStore %result %param1\n"
7267                 "             OpBranch %loop\n"
7268
7269                 "%loop      = OpLabel\n"
7270                 "%ival      = OpLoad %i32 %iptr\n"
7271                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7272                 "             OpLoopMerge %exit %phi None\n"
7273                 "             OpBranchConditional %lt_4 %entry %exit\n"
7274
7275                 "%entry     = OpLabel\n"
7276                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7277                 "%val       = OpLoad %f32 %loc\n"
7278                 "             OpSelectionMerge %phi None\n"
7279                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7280
7281                 "%case0     = OpLabel\n"
7282                 "             OpBranch %phi\n"
7283                 "%case1     = OpLabel\n"
7284                 "             OpBranch %phi\n"
7285                 "%case2     = OpLabel\n"
7286                 "             OpBranch %phi\n"
7287                 "%case3     = OpLabel\n"
7288                 "             OpBranch %phi\n"
7289
7290                 "%default   = OpLabel\n"
7291                 "             OpUnreachable\n"
7292
7293                 "%phi       = OpLabel\n"
7294                 "%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
7295                 "%add       = OpFAdd %f32 %val %operand\n"
7296                 "             OpStore %loc %add\n"
7297                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7298                 "             OpStore %iptr %ival_next\n"
7299                 "             OpBranch %loop\n"
7300
7301                 "%exit      = OpLabel\n"
7302                 "%ret       = OpLoad %v4f32 %result\n"
7303                 "             OpReturnValue %ret\n"
7304
7305                 "             OpFunctionEnd\n";
7306
7307         fragments1["pre_main"]  = typesAndConstants1;
7308         fragments1["testfun"]   = function1;
7309
7310         getHalfColorsFullAlpha(inputColors);
7311
7312         outputColors1[0]                = RGBA(178, 255, 229, 255);
7313         outputColors1[1]                = RGBA(178, 127, 102, 255);
7314         outputColors1[2]                = RGBA(51,  255, 102, 255);
7315         outputColors1[3]                = RGBA(51,  127, 229, 255);
7316
7317         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7318
7319         const char      typesAndConstants2[]    =
7320                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7321
7322         // Add .4 to the second element of the given parameter.
7323         const char      function2[]                             =
7324                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7325                 "%param     = OpFunctionParameter %v4f32\n"
7326                 "%entry     = OpLabel\n"
7327                 "%result    = OpVariable %fp_v4f32 Function\n"
7328                 "             OpStore %result %param\n"
7329                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7330                 "%val       = OpLoad %f32 %loc\n"
7331                 "             OpBranch %phi\n"
7332
7333                 "%phi        = OpLabel\n"
7334                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7335                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7336                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7337                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7338                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7339                 "              OpLoopMerge %exit %phi None\n"
7340                 "              OpBranchConditional %still_loop %phi %exit\n"
7341
7342                 "%exit       = OpLabel\n"
7343                 "              OpStore %loc %accum\n"
7344                 "%ret        = OpLoad %v4f32 %result\n"
7345                 "              OpReturnValue %ret\n"
7346
7347                 "              OpFunctionEnd\n";
7348
7349         fragments2["pre_main"]  = typesAndConstants2;
7350         fragments2["testfun"]   = function2;
7351
7352         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7353         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7354         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7355         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7356
7357         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7358
7359         const char      typesAndConstants3[]    =
7360                 "%true      = OpConstantTrue %bool\n"
7361                 "%false     = OpConstantFalse %bool\n"
7362                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7363
7364         // Swap the second and the third element of the given parameter.
7365         const char      function3[]                             =
7366                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7367                 "%param     = OpFunctionParameter %v4f32\n"
7368                 "%entry     = OpLabel\n"
7369                 "%result    = OpVariable %fp_v4f32 Function\n"
7370                 "             OpStore %result %param\n"
7371                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7372                 "%a_init    = OpLoad %f32 %a_loc\n"
7373                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7374                 "%b_init    = OpLoad %f32 %b_loc\n"
7375                 "             OpBranch %phi\n"
7376
7377                 "%phi        = OpLabel\n"
7378                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7379                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7380                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7381                 "              OpLoopMerge %exit %phi None\n"
7382                 "              OpBranchConditional %still_loop %phi %exit\n"
7383
7384                 "%exit       = OpLabel\n"
7385                 "              OpStore %a_loc %a_next\n"
7386                 "              OpStore %b_loc %b_next\n"
7387                 "%ret        = OpLoad %v4f32 %result\n"
7388                 "              OpReturnValue %ret\n"
7389
7390                 "              OpFunctionEnd\n";
7391
7392         fragments3["pre_main"]  = typesAndConstants3;
7393         fragments3["testfun"]   = function3;
7394
7395         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7396         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7397         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7398         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7399
7400         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7401
7402         const char      typesAndConstants4[]    =
7403                 "%f16        = OpTypeFloat 16\n"
7404                 "%v4f16      = OpTypeVector %f16 4\n"
7405                 "%fp_f16     = OpTypePointer Function %f16\n"
7406                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7407                 "%true       = OpConstantTrue %bool\n"
7408                 "%false      = OpConstantFalse %bool\n"
7409                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7410
7411         // Swap the second and the third element of the given parameter.
7412         const char      function4[]                             =
7413                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7414                 "%param      = OpFunctionParameter %v4f32\n"
7415                 "%entry      = OpLabel\n"
7416                 "%result     = OpVariable %fp_v4f16 Function\n"
7417                 "%param16    = OpFConvert %v4f16 %param\n"
7418                 "              OpStore %result %param16\n"
7419                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7420                 "%a_init     = OpLoad %f16 %a_loc\n"
7421                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7422                 "%b_init     = OpLoad %f16 %b_loc\n"
7423                 "              OpBranch %phi\n"
7424
7425                 "%phi        = OpLabel\n"
7426                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7427                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7428                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7429                 "              OpLoopMerge %exit %phi None\n"
7430                 "              OpBranchConditional %still_loop %phi %exit\n"
7431
7432                 "%exit       = OpLabel\n"
7433                 "              OpStore %a_loc %a_next\n"
7434                 "              OpStore %b_loc %b_next\n"
7435                 "%ret16      = OpLoad %v4f16 %result\n"
7436                 "%ret        = OpFConvert %v4f32 %ret16\n"
7437                 "              OpReturnValue %ret\n"
7438
7439                 "              OpFunctionEnd\n";
7440
7441         fragments4["pre_main"]          = typesAndConstants4;
7442         fragments4["testfun"]           = function4;
7443         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7444         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7445
7446         extensions4.push_back("VK_KHR_16bit_storage");
7447         extensions4.push_back("VK_KHR_shader_float16_int8");
7448
7449         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7450         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7451
7452         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7453         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7454         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7455         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7456
7457         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7458
7459         return group.release();
7460 }
7461
7462 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7463 {
7464         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7465         RGBA                                                    inputColors[4];
7466         RGBA                                                    outputColors[4];
7467
7468         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7469         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7470         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7471         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7472         const char                                              constantsAndTypes[]      =
7473                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7474                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7475                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7476                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7477                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7478
7479         const char                                              function[]       =
7480                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7481                 "%param          = OpFunctionParameter %v4f32\n"
7482                 "%label          = OpLabel\n"
7483                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7484                 "%var2           = OpVariable %fp_f32 Function\n"
7485                 "%red            = OpCompositeExtract %f32 %param 0\n"
7486                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7487                 "                  OpStore %var2 %plus_red\n"
7488                 "%val1           = OpLoad %f32 %var1\n"
7489                 "%val2           = OpLoad %f32 %var2\n"
7490                 "%mul            = OpFMul %f32 %val1 %val2\n"
7491                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7492                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7493                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7494                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7495                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7496                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7497                 "                  OpReturnValue %ret\n"
7498                 "                  OpFunctionEnd\n";
7499
7500         struct CaseNameDecoration
7501         {
7502                 string name;
7503                 string decoration;
7504         };
7505
7506
7507         CaseNameDecoration tests[] = {
7508                 {"multiplication",      "OpDecorate %mul NoContraction"},
7509                 {"addition",            "OpDecorate %add NoContraction"},
7510                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7511         };
7512
7513         getHalfColorsFullAlpha(inputColors);
7514
7515         for (deUint8 idx = 0; idx < 4; ++idx)
7516         {
7517                 inputColors[idx].setRed(0);
7518                 outputColors[idx] = RGBA(0, 0, 0, 255);
7519         }
7520
7521         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7522         {
7523                 map<string, string> fragments;
7524
7525                 fragments["decoration"] = tests[testNdx].decoration;
7526                 fragments["pre_main"] = constantsAndTypes;
7527                 fragments["testfun"] = function;
7528
7529                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7530         }
7531
7532         return group.release();
7533 }
7534
7535 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7536 {
7537         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7538         RGBA                                                    colors[4];
7539
7540         const char                                              constantsAndTypes[]      =
7541                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7542                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7543                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7544                 "%fp_stype          = OpTypePointer Function %stype\n";
7545
7546         const char                                              function[]       =
7547                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7548                 "%param1            = OpFunctionParameter %v4f32\n"
7549                 "%lbl               = OpLabel\n"
7550                 "%v1                = OpVariable %fp_v4f32 Function\n"
7551                 "%v2                = OpVariable %fp_a2f32 Function\n"
7552                 "%v3                = OpVariable %fp_f32 Function\n"
7553                 "%v                 = OpVariable %fp_stype Function\n"
7554                 "%vv                = OpVariable %fp_stype Function\n"
7555                 "%vvv               = OpVariable %fp_f32 Function\n"
7556
7557                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7558                 "                     OpStore %v2 %c_a2f32_1\n"
7559                 "                     OpStore %v3 %c_f32_1\n"
7560
7561                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7562                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7563                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7564                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7565                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7566                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7567
7568                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7569                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7570                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7571
7572                 "                    OpCopyMemory %vv %v ${access_type}\n"
7573                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7574
7575                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7576                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7577                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7578
7579                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7580                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7581                 "                    OpReturnValue %ret2\n"
7582                 "                    OpFunctionEnd\n";
7583
7584         struct NameMemoryAccess
7585         {
7586                 string name;
7587                 string accessType;
7588         };
7589
7590
7591         NameMemoryAccess tests[] =
7592         {
7593                 { "none", "" },
7594                 { "volatile", "Volatile" },
7595                 { "aligned",  "Aligned 1" },
7596                 { "volatile_aligned",  "Volatile|Aligned 1" },
7597                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7598                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7599                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7600         };
7601
7602         getHalfColorsFullAlpha(colors);
7603
7604         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7605         {
7606                 map<string, string> fragments;
7607                 map<string, string> memoryAccess;
7608                 memoryAccess["access_type"] = tests[testNdx].accessType;
7609
7610                 fragments["pre_main"] = constantsAndTypes;
7611                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7612                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7613         }
7614         return memoryAccessTests.release();
7615 }
7616 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7617 {
7618         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7619         RGBA                                                            defaultColors[4];
7620         map<string, string>                                     fragments;
7621         getDefaultColors(defaultColors);
7622
7623         // First, simple cases that don't do anything with the OpUndef result.
7624         struct NameCodePair { string name, decl, type; };
7625         const NameCodePair tests[] =
7626         {
7627                 {"bool", "", "%bool"},
7628                 {"vec2uint32", "", "%v2u32"},
7629                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7630                 {"sampler", "%type = OpTypeSampler", "%type"},
7631                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7632                 {"pointer", "", "%fp_i32"},
7633                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7634                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7635                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7636         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7637         {
7638                 fragments["undef_type"] = tests[testNdx].type;
7639                 fragments["testfun"] = StringTemplate(
7640                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7641                         "%param1 = OpFunctionParameter %v4f32\n"
7642                         "%label_testfun = OpLabel\n"
7643                         "%undef = OpUndef ${undef_type}\n"
7644                         "OpReturnValue %param1\n"
7645                         "OpFunctionEnd\n").specialize(fragments);
7646                 fragments["pre_main"] = tests[testNdx].decl;
7647                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7648         }
7649         fragments.clear();
7650
7651         fragments["testfun"] =
7652                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7653                 "%param1 = OpFunctionParameter %v4f32\n"
7654                 "%label_testfun = OpLabel\n"
7655                 "%undef = OpUndef %f32\n"
7656                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7657                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7658                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7659                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7660                 "%b = OpFAdd %f32 %a %actually_zero\n"
7661                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7662                 "OpReturnValue %ret\n"
7663                 "OpFunctionEnd\n";
7664
7665         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7666
7667         fragments["testfun"] =
7668                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7669                 "%param1 = OpFunctionParameter %v4f32\n"
7670                 "%label_testfun = OpLabel\n"
7671                 "%undef = OpUndef %i32\n"
7672                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7673                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7674                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7675                 "OpReturnValue %ret\n"
7676                 "OpFunctionEnd\n";
7677
7678         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7679
7680         fragments["testfun"] =
7681                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7682                 "%param1 = OpFunctionParameter %v4f32\n"
7683                 "%label_testfun = OpLabel\n"
7684                 "%undef = OpUndef %u32\n"
7685                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7686                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7687                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7688                 "OpReturnValue %ret\n"
7689                 "OpFunctionEnd\n";
7690
7691         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7692
7693         fragments["testfun"] =
7694                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7695                 "%param1 = OpFunctionParameter %v4f32\n"
7696                 "%label_testfun = OpLabel\n"
7697                 "%undef = OpUndef %v4f32\n"
7698                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7699                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7700                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7701                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7702                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7703                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7704                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7705                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7706                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7707                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7708                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7709                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7710                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7711                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7712                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7713                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7714                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7715                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7716                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7717                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7718                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7719                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7720                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7721                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7722                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7723                 "OpReturnValue %ret\n"
7724                 "OpFunctionEnd\n";
7725
7726         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7727
7728         fragments["pre_main"] =
7729                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7730         fragments["testfun"] =
7731                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7732                 "%param1 = OpFunctionParameter %v4f32\n"
7733                 "%label_testfun = OpLabel\n"
7734                 "%undef = OpUndef %m2x2f32\n"
7735                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7736                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7737                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7738                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7739                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7740                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7741                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7742                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7743                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7744                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7745                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7746                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7747                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7748                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7749                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7750                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7751                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7752                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7753                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7754                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7755                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7756                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7757                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7758                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7759                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7760                 "OpReturnValue %ret\n"
7761                 "OpFunctionEnd\n";
7762
7763         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7764
7765         return opUndefTests.release();
7766 }
7767
7768 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7769 {
7770         const RGBA              inputColors[4]          =
7771         {
7772                 RGBA(0,         0,              0,              255),
7773                 RGBA(0,         0,              255,    255),
7774                 RGBA(0,         255,    0,              255),
7775                 RGBA(0,         255,    255,    255)
7776         };
7777
7778         const RGBA              expectedColors[4]       =
7779         {
7780                 RGBA(255,        0,              0,              255),
7781                 RGBA(255,        0,              0,              255),
7782                 RGBA(255,        0,              0,              255),
7783                 RGBA(255,        0,              0,              255)
7784         };
7785
7786         const struct SingleFP16Possibility
7787         {
7788                 const char* name;
7789                 const char* constant;  // Value to assign to %test_constant.
7790                 float           valueAsFloat;
7791                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7792         }                               tests[]                         =
7793         {
7794                 {
7795                         "negative",
7796                         "-0x1.3p1\n",
7797                         -constructNormalizedFloat(1, 0x300000),
7798                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7799                 }, // -19
7800                 {
7801                         "positive",
7802                         "0x1.0p7\n",
7803                         constructNormalizedFloat(7, 0x000000),
7804                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7805                 },  // +128
7806                 // SPIR-V requires that OpQuantizeToF16 flushes
7807                 // any numbers that would end up denormalized in F16 to zero.
7808                 {
7809                         "denorm",
7810                         "0x0.0006p-126\n",
7811                         std::ldexp(1.5f, -140),
7812                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7813                 },  // denorm
7814                 {
7815                         "negative_denorm",
7816                         "-0x0.0006p-126\n",
7817                         -std::ldexp(1.5f, -140),
7818                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7819                 }, // -denorm
7820                 {
7821                         "too_small",
7822                         "0x1.0p-16\n",
7823                         std::ldexp(1.0f, -16),
7824                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7825                 },     // too small positive
7826                 {
7827                         "negative_too_small",
7828                         "-0x1.0p-32\n",
7829                         -std::ldexp(1.0f, -32),
7830                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7831                 },      // too small negative
7832                 {
7833                         "negative_inf",
7834                         "-0x1.0p128\n",
7835                         -std::ldexp(1.0f, 128),
7836
7837                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7838                         "%inf = OpIsInf %bool %c\n"
7839                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7840                 },     // -inf to -inf
7841                 {
7842                         "inf",
7843                         "0x1.0p128\n",
7844                         std::ldexp(1.0f, 128),
7845
7846                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7847                         "%inf = OpIsInf %bool %c\n"
7848                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7849                 },     // +inf to +inf
7850                 {
7851                         "round_to_negative_inf",
7852                         "-0x1.0p32\n",
7853                         -std::ldexp(1.0f, 32),
7854
7855                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7856                         "%inf = OpIsInf %bool %c\n"
7857                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7858                 },     // round to -inf
7859                 {
7860                         "round_to_inf",
7861                         "0x1.0p16\n",
7862                         std::ldexp(1.0f, 16),
7863
7864                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7865                         "%inf = OpIsInf %bool %c\n"
7866                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7867                 },     // round to +inf
7868                 {
7869                         "nan",
7870                         "0x1.1p128\n",
7871                         std::numeric_limits<float>::quiet_NaN(),
7872
7873                         // Test for any NaN value, as NaNs are not preserved
7874                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7875                         "%cond = OpIsNan %bool %direct_quant\n"
7876                 }, // nan
7877                 {
7878                         "negative_nan",
7879                         "-0x1.0001p128\n",
7880                         std::numeric_limits<float>::quiet_NaN(),
7881
7882                         // Test for any NaN value, as NaNs are not preserved
7883                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7884                         "%cond = OpIsNan %bool %direct_quant\n"
7885                 } // -nan
7886         };
7887         const char*             constants                       =
7888                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7889
7890         StringTemplate  function                        (
7891                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7892                 "%param1        = OpFunctionParameter %v4f32\n"
7893                 "%label_testfun = OpLabel\n"
7894                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7895                 "%b             = OpFAdd %f32 %test_constant %a\n"
7896                 "%c             = OpQuantizeToF16 %f32 %b\n"
7897                 "${condition}\n"
7898                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7899                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7900                 "                 OpReturnValue %retval\n"
7901                 "OpFunctionEnd\n"
7902         );
7903
7904         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7905         const char*             specConstants           =
7906                         "%test_constant = OpSpecConstant %f32 0.\n"
7907                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7908
7909         StringTemplate  specConstantFunction(
7910                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7911                 "%param1        = OpFunctionParameter %v4f32\n"
7912                 "%label_testfun = OpLabel\n"
7913                 "${condition}\n"
7914                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7915                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7916                 "                 OpReturnValue %retval\n"
7917                 "OpFunctionEnd\n"
7918         );
7919
7920         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7921         {
7922                 map<string, string>                                                             codeSpecialization;
7923                 map<string, string>                                                             fragments;
7924                 codeSpecialization["condition"]                                 = tests[idx].condition;
7925                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7926                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7927                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7928         }
7929
7930         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7931         {
7932                 map<string, string>                                                             codeSpecialization;
7933                 map<string, string>                                                             fragments;
7934                 SpecConstants                                                                   passConstants;
7935
7936                 codeSpecialization["condition"]                                 = tests[idx].condition;
7937                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7938                 fragments["decoration"]                                                 = specDecorations;
7939                 fragments["pre_main"]                                                   = specConstants;
7940
7941                 passConstants.append<float>(tests[idx].valueAsFloat);
7942
7943                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7944         }
7945 }
7946
7947 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7948 {
7949         RGBA inputColors[4] =  {
7950                 RGBA(0,         0,              0,              255),
7951                 RGBA(0,         0,              255,    255),
7952                 RGBA(0,         255,    0,              255),
7953                 RGBA(0,         255,    255,    255)
7954         };
7955
7956         RGBA expectedColors[4] =
7957         {
7958                 RGBA(255,        0,              0,              255),
7959                 RGBA(255,        0,              0,              255),
7960                 RGBA(255,        0,              0,              255),
7961                 RGBA(255,        0,              0,              255)
7962         };
7963
7964         struct DualFP16Possibility
7965         {
7966                 const char* name;
7967                 const char* input;
7968                 float           inputAsFloat;
7969                 const char* possibleOutput1;
7970                 const char* possibleOutput2;
7971         } tests[] = {
7972                 {
7973                         "positive_round_up_or_round_down",
7974                         "0x1.3003p8",
7975                         constructNormalizedFloat(8, 0x300300),
7976                         "0x1.304p8",
7977                         "0x1.3p8"
7978                 },
7979                 {
7980                         "negative_round_up_or_round_down",
7981                         "-0x1.6008p-7",
7982                         -constructNormalizedFloat(-7, 0x600800),
7983                         "-0x1.6p-7",
7984                         "-0x1.604p-7"
7985                 },
7986                 {
7987                         "carry_bit",
7988                         "0x1.01ep2",
7989                         constructNormalizedFloat(2, 0x01e000),
7990                         "0x1.01cp2",
7991                         "0x1.02p2"
7992                 },
7993                 {
7994                         "carry_to_exponent",
7995                         "0x1.ffep1",
7996                         constructNormalizedFloat(1, 0xffe000),
7997                         "0x1.ffcp1",
7998                         "0x1.0p2"
7999                 },
8000         };
8001         StringTemplate constants (
8002                 "%input_const = OpConstant %f32 ${input}\n"
8003                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8004                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8005                 );
8006
8007         StringTemplate specConstants (
8008                 "%input_const = OpSpecConstant %f32 0.\n"
8009                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8010                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8011         );
8012
8013         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8014
8015         const char* function  =
8016                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8017                 "%param1        = OpFunctionParameter %v4f32\n"
8018                 "%label_testfun = OpLabel\n"
8019                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8020                 // For the purposes of this test we assume that 0.f will always get
8021                 // faithfully passed through the pipeline stages.
8022                 "%b             = OpFAdd %f32 %input_const %a\n"
8023                 "%c             = OpQuantizeToF16 %f32 %b\n"
8024                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8025                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8026                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8027                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8028                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8029                 "                 OpReturnValue %retval\n"
8030                 "OpFunctionEnd\n";
8031
8032         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8033                 map<string, string>                                                                     fragments;
8034                 map<string, string>                                                                     constantSpecialization;
8035
8036                 constantSpecialization["input"]                                         = tests[idx].input;
8037                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8038                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8039                 fragments["testfun"]                                                            = function;
8040                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8041                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8042         }
8043
8044         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8045                 map<string, string>                                                                     fragments;
8046                 map<string, string>                                                                     constantSpecialization;
8047                 SpecConstants                                                                           passConstants;
8048
8049                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8050                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8051                 fragments["testfun"]                                                            = function;
8052                 fragments["decoration"]                                                         = specDecorations;
8053                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8054
8055                 passConstants.append<float>(tests[idx].inputAsFloat);
8056
8057                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8058         }
8059 }
8060
8061 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8062 {
8063         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8064         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8065         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8066         return opQuantizeTests.release();
8067 }
8068
8069 struct ShaderPermutation
8070 {
8071         deUint8 vertexPermutation;
8072         deUint8 geometryPermutation;
8073         deUint8 tesscPermutation;
8074         deUint8 tessePermutation;
8075         deUint8 fragmentPermutation;
8076 };
8077
8078 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8079 {
8080         ShaderPermutation       permutation =
8081         {
8082                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8083                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8084                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8085                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8086                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8087         };
8088         return permutation;
8089 }
8090
8091 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8092 {
8093         RGBA                                                            defaultColors[4];
8094         RGBA                                                            invertedColors[4];
8095         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8096
8097         getDefaultColors(defaultColors);
8098         getInvertedDefaultColors(invertedColors);
8099
8100         // Combined module tests
8101         {
8102                 // Shader stages: vertex and fragment
8103                 {
8104                         const ShaderElement combinedPipeline[]  =
8105                         {
8106                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8107                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8108                         };
8109
8110                         addFunctionCaseWithPrograms<InstanceContext>(
8111                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8112                                 createInstanceContext(combinedPipeline, map<string, string>()));
8113                 }
8114
8115                 // Shader stages: vertex, geometry and fragment
8116                 {
8117                         const ShaderElement combinedPipeline[]  =
8118                         {
8119                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8120                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8121                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8122                         };
8123
8124                         addFunctionCaseWithPrograms<InstanceContext>(
8125                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8126                                 createInstanceContext(combinedPipeline, map<string, string>()));
8127                 }
8128
8129                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8130                 {
8131                         const ShaderElement combinedPipeline[]  =
8132                         {
8133                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8134                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8135                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8136                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8137                         };
8138
8139                         addFunctionCaseWithPrograms<InstanceContext>(
8140                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8141                                 createInstanceContext(combinedPipeline, map<string, string>()));
8142                 }
8143
8144                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8145                 {
8146                         const ShaderElement combinedPipeline[]  =
8147                         {
8148                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8149                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8150                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8151                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8152                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8153                         };
8154
8155                         addFunctionCaseWithPrograms<InstanceContext>(
8156                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8157                                 createInstanceContext(combinedPipeline, map<string, string>()));
8158                 }
8159         }
8160
8161         const char* numbers[] =
8162         {
8163                 "1", "2"
8164         };
8165
8166         for (deInt8 idx = 0; idx < 32; ++idx)
8167         {
8168                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8169                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8170                 const ShaderElement                     pipeline[]              =
8171                 {
8172                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8173                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8174                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8175                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8176                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8177                 };
8178
8179                 // If there are an even number of swaps, then it should be no-op.
8180                 // If there are an odd number, the color should be flipped.
8181                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8182                 {
8183                         addFunctionCaseWithPrograms<InstanceContext>(
8184                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8185                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8186                 }
8187                 else
8188                 {
8189                         addFunctionCaseWithPrograms<InstanceContext>(
8190                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8191                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8192                 }
8193         }
8194         return moduleTests.release();
8195 }
8196
8197 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8198 {
8199         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8200         RGBA defaultColors[4];
8201         getDefaultColors(defaultColors);
8202         map<string, string> fragments;
8203         fragments["pre_main"] =
8204                 "%c_f32_5 = OpConstant %f32 5.\n";
8205
8206         // A loop with a single block. The Continue Target is the loop block
8207         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8208         // -- the "continue construct" forms the entire loop.
8209         fragments["testfun"] =
8210                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8211                 "%param1 = OpFunctionParameter %v4f32\n"
8212
8213                 "%entry = OpLabel\n"
8214                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8215                 "OpBranch %loop\n"
8216
8217                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8218                 "%loop = OpLabel\n"
8219                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8220                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8221                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8222                 "%val = OpFAdd %f32 %val1 %delta\n"
8223                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8224                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8225                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8226                 "OpLoopMerge %exit %loop None\n"
8227                 "OpBranchConditional %again %loop %exit\n"
8228
8229                 "%exit = OpLabel\n"
8230                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8231                 "OpReturnValue %result\n"
8232
8233                 "OpFunctionEnd\n";
8234
8235         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8236
8237         // Body comprised of multiple basic blocks.
8238         const StringTemplate multiBlock(
8239                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8240                 "%param1 = OpFunctionParameter %v4f32\n"
8241
8242                 "%entry = OpLabel\n"
8243                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8244                 "OpBranch %loop\n"
8245
8246                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8247                 "%loop = OpLabel\n"
8248                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8249                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8250                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8251                 // There are several possibilities for the Continue Target below.  Each
8252                 // will be specialized into a separate test case.
8253                 "OpLoopMerge %exit ${continue_target} None\n"
8254                 "OpBranch %if\n"
8255
8256                 "%if = OpLabel\n"
8257                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8258                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8259                 "OpSelectionMerge %gather DontFlatten\n"
8260                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8261
8262                 "%odd = OpLabel\n"
8263                 "OpBranch %gather\n"
8264
8265                 "%even = OpLabel\n"
8266                 "OpBranch %gather\n"
8267
8268                 "%gather = OpLabel\n"
8269                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8270                 "%val = OpFAdd %f32 %val1 %delta\n"
8271                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8272                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8273                 "OpBranchConditional %again %loop %exit\n"
8274
8275                 "%exit = OpLabel\n"
8276                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8277                 "OpReturnValue %result\n"
8278
8279                 "OpFunctionEnd\n");
8280
8281         map<string, string> continue_target;
8282
8283         // The Continue Target is the loop block itself.
8284         continue_target["continue_target"] = "%loop";
8285         fragments["testfun"] = multiBlock.specialize(continue_target);
8286         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8287
8288         // The Continue Target is at the end of the loop.
8289         continue_target["continue_target"] = "%gather";
8290         fragments["testfun"] = multiBlock.specialize(continue_target);
8291         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8292
8293         // A loop with continue statement.
8294         fragments["testfun"] =
8295                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8296                 "%param1 = OpFunctionParameter %v4f32\n"
8297
8298                 "%entry = OpLabel\n"
8299                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8300                 "OpBranch %loop\n"
8301
8302                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8303                 "%loop = OpLabel\n"
8304                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8305                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8306                 "OpLoopMerge %exit %continue None\n"
8307                 "OpBranch %if\n"
8308
8309                 "%if = OpLabel\n"
8310                 ";skip if %count==2\n"
8311                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8312                 "OpSelectionMerge %continue DontFlatten\n"
8313                 "OpBranchConditional %eq2 %continue %body\n"
8314
8315                 "%body = OpLabel\n"
8316                 "%fcount = OpConvertSToF %f32 %count\n"
8317                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8318                 "OpBranch %continue\n"
8319
8320                 "%continue = OpLabel\n"
8321                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8322                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8323                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8324                 "OpBranchConditional %again %loop %exit\n"
8325
8326                 "%exit = OpLabel\n"
8327                 "%same = OpFSub %f32 %val %c_f32_8\n"
8328                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8329                 "OpReturnValue %result\n"
8330                 "OpFunctionEnd\n";
8331         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8332
8333         // A loop with break.
8334         fragments["testfun"] =
8335                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8336                 "%param1 = OpFunctionParameter %v4f32\n"
8337
8338                 "%entry = OpLabel\n"
8339                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8340                 "%dot = OpDot %f32 %param1 %param1\n"
8341                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8342                 "%zero = OpConvertFToU %u32 %div\n"
8343                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8344                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8345                 "OpBranch %loop\n"
8346
8347                 ";adds 4 and 3 to %val0 (exits early)\n"
8348                 "%loop = OpLabel\n"
8349                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8350                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8351                 "OpLoopMerge %exit %continue None\n"
8352                 "OpBranch %if\n"
8353
8354                 "%if = OpLabel\n"
8355                 ";end loop if %count==%two\n"
8356                 "%above2 = OpSGreaterThan %bool %count %two\n"
8357                 "OpSelectionMerge %continue DontFlatten\n"
8358                 "OpBranchConditional %above2 %body %exit\n"
8359
8360                 "%body = OpLabel\n"
8361                 "%fcount = OpConvertSToF %f32 %count\n"
8362                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8363                 "OpBranch %continue\n"
8364
8365                 "%continue = OpLabel\n"
8366                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8367                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8368                 "OpBranchConditional %again %loop %exit\n"
8369
8370                 "%exit = OpLabel\n"
8371                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8372                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8373                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8374                 "OpReturnValue %result\n"
8375                 "OpFunctionEnd\n";
8376         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8377
8378         // A loop with return.
8379         fragments["testfun"] =
8380                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8381                 "%param1 = OpFunctionParameter %v4f32\n"
8382
8383                 "%entry = OpLabel\n"
8384                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8385                 "%dot = OpDot %f32 %param1 %param1\n"
8386                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8387                 "%zero = OpConvertFToU %u32 %div\n"
8388                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8389                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8390                 "OpBranch %loop\n"
8391
8392                 ";returns early without modifying %param1\n"
8393                 "%loop = OpLabel\n"
8394                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8395                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8396                 "OpLoopMerge %exit %continue None\n"
8397                 "OpBranch %if\n"
8398
8399                 "%if = OpLabel\n"
8400                 ";return if %count==%two\n"
8401                 "%above2 = OpSGreaterThan %bool %count %two\n"
8402                 "OpSelectionMerge %continue DontFlatten\n"
8403                 "OpBranchConditional %above2 %body %early_exit\n"
8404
8405                 "%early_exit = OpLabel\n"
8406                 "OpReturnValue %param1\n"
8407
8408                 "%body = OpLabel\n"
8409                 "%fcount = OpConvertSToF %f32 %count\n"
8410                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8411                 "OpBranch %continue\n"
8412
8413                 "%continue = OpLabel\n"
8414                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8415                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8416                 "OpBranchConditional %again %loop %exit\n"
8417
8418                 "%exit = OpLabel\n"
8419                 ";should never get here, so return an incorrect result\n"
8420                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8421                 "OpReturnValue %result\n"
8422                 "OpFunctionEnd\n";
8423         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8424
8425         // Continue inside a switch block to break to enclosing loop's merge block.
8426         // Matches roughly the following GLSL code:
8427         // for (; keep_going; keep_going = false)
8428         // {
8429         //     switch (int(param1.x))
8430         //     {
8431         //         case 0: continue;
8432         //         case 1: continue;
8433         //         default: continue;
8434         //     }
8435         //     dead code: modify return value to invalid result.
8436         // }
8437         fragments["pre_main"] =
8438                 "%fp_bool = OpTypePointer Function %bool\n"
8439                 "%true = OpConstantTrue %bool\n"
8440                 "%false = OpConstantFalse %bool\n";
8441
8442         fragments["testfun"] =
8443                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8444                 "%param1 = OpFunctionParameter %v4f32\n"
8445
8446                 "%entry = OpLabel\n"
8447                 "%keep_going = OpVariable %fp_bool Function\n"
8448                 "%val_ptr = OpVariable %fp_f32 Function\n"
8449                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8450                 "OpStore %keep_going %true\n"
8451                 "OpBranch %forloop_begin\n"
8452
8453                 "%forloop_begin = OpLabel\n"
8454                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8455                 "OpBranch %forloop\n"
8456
8457                 "%forloop = OpLabel\n"
8458                 "%for_condition = OpLoad %bool %keep_going\n"
8459                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8460
8461                 "%forloop_body = OpLabel\n"
8462                 "OpStore %val_ptr %param1_x\n"
8463                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8464
8465                 "OpSelectionMerge %switch_merge None\n"
8466                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8467                 "%case_0 = OpLabel\n"
8468                 "OpBranch %forloop_continue\n"
8469                 "%case_1 = OpLabel\n"
8470                 "OpBranch %forloop_continue\n"
8471                 "%default = OpLabel\n"
8472                 "OpBranch %forloop_continue\n"
8473                 "%switch_merge = OpLabel\n"
8474                 ";should never get here, so change the return value to invalid result\n"
8475                 "OpStore %val_ptr %c_f32_1\n"
8476                 "OpBranch %forloop_continue\n"
8477
8478                 "%forloop_continue = OpLabel\n"
8479                 "OpStore %keep_going %false\n"
8480                 "OpBranch %forloop_begin\n"
8481                 "%forloop_merge = OpLabel\n"
8482
8483                 "%val = OpLoad %f32 %val_ptr\n"
8484                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8485                 "OpReturnValue %result\n"
8486                 "OpFunctionEnd\n";
8487         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8488
8489         return testGroup.release();
8490 }
8491
8492 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8493 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8494 {
8495         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8496         map<string, string> fragments;
8497
8498         // A barrier inside a function body.
8499         fragments["pre_main"] =
8500                 "%Workgroup = OpConstant %i32 2\n"
8501                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8502         fragments["testfun"] =
8503                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8504                 "%param1 = OpFunctionParameter %v4f32\n"
8505                 "%label_testfun = OpLabel\n"
8506                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8507                 "OpReturnValue %param1\n"
8508                 "OpFunctionEnd\n";
8509         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8510
8511         // Common setup code for the following tests.
8512         fragments["pre_main"] =
8513                 "%Workgroup = OpConstant %i32 2\n"
8514                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8515                 "%c_f32_5 = OpConstant %f32 5.\n";
8516         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8517                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8518                 "%param1 = OpFunctionParameter %v4f32\n"
8519                 "%entry = OpLabel\n"
8520                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8521                 "%dot = OpDot %f32 %param1 %param1\n"
8522                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8523                 "%zero = OpConvertFToU %u32 %div\n";
8524
8525         // Barriers inside OpSwitch branches.
8526         fragments["testfun"] =
8527                 setupPercentZero +
8528                 "OpSelectionMerge %switch_exit None\n"
8529                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8530
8531                 "%case1 = OpLabel\n"
8532                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8533                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8534                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8535                 "OpBranch %switch_exit\n"
8536
8537                 "%switch_default = OpLabel\n"
8538                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8539                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8540                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8541                 "OpBranch %switch_exit\n"
8542
8543                 "%case0 = OpLabel\n"
8544                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8545                 "OpBranch %switch_exit\n"
8546
8547                 "%switch_exit = OpLabel\n"
8548                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8549                 "OpReturnValue %ret\n"
8550                 "OpFunctionEnd\n";
8551         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8552
8553         // Barriers inside if-then-else.
8554         fragments["testfun"] =
8555                 setupPercentZero +
8556                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8557                 "OpSelectionMerge %exit DontFlatten\n"
8558                 "OpBranchConditional %eq0 %then %else\n"
8559
8560                 "%else = OpLabel\n"
8561                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8562                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8563                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8564                 "OpBranch %exit\n"
8565
8566                 "%then = OpLabel\n"
8567                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8568                 "OpBranch %exit\n"
8569                 "%exit = OpLabel\n"
8570                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8571                 "OpReturnValue %ret\n"
8572                 "OpFunctionEnd\n";
8573         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8574
8575         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8576         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8577         fragments["testfun"] =
8578                 setupPercentZero +
8579                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8580                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8581                 "OpSelectionMerge %exit DontFlatten\n"
8582                 "OpBranchConditional %thread0 %then %else\n"
8583
8584                 "%else = OpLabel\n"
8585                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8586                 "OpBranch %exit\n"
8587
8588                 "%then = OpLabel\n"
8589                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8590                 "OpBranch %exit\n"
8591
8592                 "%exit = OpLabel\n"
8593                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8594                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8595                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8596                 "OpReturnValue %ret\n"
8597                 "OpFunctionEnd\n";
8598         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8599
8600         // A barrier inside a loop.
8601         fragments["pre_main"] =
8602                 "%Workgroup = OpConstant %i32 2\n"
8603                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8604                 "%c_f32_10 = OpConstant %f32 10.\n";
8605         fragments["testfun"] =
8606                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8607                 "%param1 = OpFunctionParameter %v4f32\n"
8608                 "%entry = OpLabel\n"
8609                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8610                 "OpBranch %loop\n"
8611
8612                 ";adds 4, 3, 2, and 1 to %val0\n"
8613                 "%loop = OpLabel\n"
8614                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8615                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8616                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8617                 "%fcount = OpConvertSToF %f32 %count\n"
8618                 "%val = OpFAdd %f32 %val1 %fcount\n"
8619                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8620                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8621                 "OpLoopMerge %exit %loop None\n"
8622                 "OpBranchConditional %again %loop %exit\n"
8623
8624                 "%exit = OpLabel\n"
8625                 "%same = OpFSub %f32 %val %c_f32_10\n"
8626                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8627                 "OpReturnValue %ret\n"
8628                 "OpFunctionEnd\n";
8629         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8630
8631         return testGroup.release();
8632 }
8633
8634 // Test for the OpFRem instruction.
8635 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8636 {
8637         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8638         map<string, string>                                     fragments;
8639         RGBA                                                            inputColors[4];
8640         RGBA                                                            outputColors[4];
8641
8642         fragments["pre_main"]                            =
8643                 "%c_f32_3 = OpConstant %f32 3.0\n"
8644                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8645                 "%c_f32_4 = OpConstant %f32 4.0\n"
8646                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8647                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8648                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8649                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8650
8651         // The test does the following.
8652         // vec4 result = (param1 * 8.0) - 4.0;
8653         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8654         fragments["testfun"]                             =
8655                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8656                 "%param1 = OpFunctionParameter %v4f32\n"
8657                 "%label_testfun = OpLabel\n"
8658                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8659                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8660                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8661                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8662                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8663                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8664                 "OpReturnValue %xy_0_1\n"
8665                 "OpFunctionEnd\n";
8666
8667
8668         inputColors[0]          = RGBA(16,      16,             0, 255);
8669         inputColors[1]          = RGBA(232, 232,        0, 255);
8670         inputColors[2]          = RGBA(232, 16,         0, 255);
8671         inputColors[3]          = RGBA(16,      232,    0, 255);
8672
8673         outputColors[0]         = RGBA(64,      64,             0, 255);
8674         outputColors[1]         = RGBA(255, 255,        0, 255);
8675         outputColors[2]         = RGBA(255, 64,         0, 255);
8676         outputColors[3]         = RGBA(64,      255,    0, 255);
8677
8678         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8679         return testGroup.release();
8680 }
8681
8682 // Test for the OpSRem instruction.
8683 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8684 {
8685         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8686         map<string, string>                                     fragments;
8687
8688         fragments["pre_main"]                            =
8689                 "%c_f32_255 = OpConstant %f32 255.0\n"
8690                 "%c_i32_128 = OpConstant %i32 128\n"
8691                 "%c_i32_255 = OpConstant %i32 255\n"
8692                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8693                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8694                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8695
8696         // The test does the following.
8697         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8698         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8699         // return float(result + 128) / 255.0;
8700         fragments["testfun"]                             =
8701                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8702                 "%param1 = OpFunctionParameter %v4f32\n"
8703                 "%label_testfun = OpLabel\n"
8704                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8705                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8706                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8707                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8708                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8709                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8710                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8711                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8712                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8713                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8714                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8715                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8716                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8717                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8718                 "OpReturnValue %float_out\n"
8719                 "OpFunctionEnd\n";
8720
8721         const struct CaseParams
8722         {
8723                 const char*             name;
8724                 const char*             failMessageTemplate;    // customized status message
8725                 qpTestResult    failResult;                             // override status on failure
8726                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8727                 int                             results[4][3];                  // four (x, y, z) vectors of results
8728         } cases[] =
8729         {
8730                 {
8731                         "positive",
8732                         "${reason}",
8733                         QP_TEST_RESULT_FAIL,
8734                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8735                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8736                 },
8737                 {
8738                         "all",
8739                         "Inconsistent results, but within specification: ${reason}",
8740                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8741                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8742                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8743                 },
8744         };
8745         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8746
8747         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8748         {
8749                 const CaseParams&       params                  = cases[caseNdx];
8750                 RGBA                            inputColors[4];
8751                 RGBA                            outputColors[4];
8752
8753                 for (int i = 0; i < 4; ++i)
8754                 {
8755                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8756                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8757                 }
8758
8759                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8760         }
8761
8762         return testGroup.release();
8763 }
8764
8765 // Test for the OpSMod instruction.
8766 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8767 {
8768         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8769         map<string, string>                                     fragments;
8770
8771         fragments["pre_main"]                            =
8772                 "%c_f32_255 = OpConstant %f32 255.0\n"
8773                 "%c_i32_128 = OpConstant %i32 128\n"
8774                 "%c_i32_255 = OpConstant %i32 255\n"
8775                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8776                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8777                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8778
8779         // The test does the following.
8780         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8781         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8782         // return float(result + 128) / 255.0;
8783         fragments["testfun"]                             =
8784                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8785                 "%param1 = OpFunctionParameter %v4f32\n"
8786                 "%label_testfun = OpLabel\n"
8787                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8788                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8789                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8790                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8791                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8792                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8793                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8794                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8795                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8796                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8797                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8798                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8799                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8800                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8801                 "OpReturnValue %float_out\n"
8802                 "OpFunctionEnd\n";
8803
8804         const struct CaseParams
8805         {
8806                 const char*             name;
8807                 const char*             failMessageTemplate;    // customized status message
8808                 qpTestResult    failResult;                             // override status on failure
8809                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8810                 int                             results[4][3];                  // four (x, y, z) vectors of results
8811         } cases[] =
8812         {
8813                 {
8814                         "positive",
8815                         "${reason}",
8816                         QP_TEST_RESULT_FAIL,
8817                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8818                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8819                 },
8820                 {
8821                         "all",
8822                         "Inconsistent results, but within specification: ${reason}",
8823                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8824                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8825                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8826                 },
8827         };
8828         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8829
8830         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8831         {
8832                 const CaseParams&       params                  = cases[caseNdx];
8833                 RGBA                            inputColors[4];
8834                 RGBA                            outputColors[4];
8835
8836                 for (int i = 0; i < 4; ++i)
8837                 {
8838                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8839                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8840                 }
8841
8842                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8843         }
8844         return testGroup.release();
8845 }
8846
8847 enum ConversionDataType
8848 {
8849         DATA_TYPE_SIGNED_8,
8850         DATA_TYPE_SIGNED_16,
8851         DATA_TYPE_SIGNED_32,
8852         DATA_TYPE_SIGNED_64,
8853         DATA_TYPE_UNSIGNED_8,
8854         DATA_TYPE_UNSIGNED_16,
8855         DATA_TYPE_UNSIGNED_32,
8856         DATA_TYPE_UNSIGNED_64,
8857         DATA_TYPE_FLOAT_16,
8858         DATA_TYPE_FLOAT_32,
8859         DATA_TYPE_FLOAT_64,
8860         DATA_TYPE_VEC2_SIGNED_16,
8861         DATA_TYPE_VEC2_SIGNED_32
8862 };
8863
8864 const string getBitWidthStr (ConversionDataType type)
8865 {
8866         switch (type)
8867         {
8868                 case DATA_TYPE_SIGNED_8:
8869                 case DATA_TYPE_UNSIGNED_8:
8870                         return "8";
8871
8872                 case DATA_TYPE_SIGNED_16:
8873                 case DATA_TYPE_UNSIGNED_16:
8874                 case DATA_TYPE_FLOAT_16:
8875                         return "16";
8876
8877                 case DATA_TYPE_SIGNED_32:
8878                 case DATA_TYPE_UNSIGNED_32:
8879                 case DATA_TYPE_FLOAT_32:
8880                 case DATA_TYPE_VEC2_SIGNED_16:
8881                         return "32";
8882
8883                 case DATA_TYPE_SIGNED_64:
8884                 case DATA_TYPE_UNSIGNED_64:
8885                 case DATA_TYPE_FLOAT_64:
8886                 case DATA_TYPE_VEC2_SIGNED_32:
8887                         return "64";
8888
8889                 default:
8890                         DE_ASSERT(false);
8891         }
8892         return "";
8893 }
8894
8895 const string getByteWidthStr (ConversionDataType type)
8896 {
8897         switch (type)
8898         {
8899                 case DATA_TYPE_SIGNED_8:
8900                 case DATA_TYPE_UNSIGNED_8:
8901                         return "1";
8902
8903                 case DATA_TYPE_SIGNED_16:
8904                 case DATA_TYPE_UNSIGNED_16:
8905                 case DATA_TYPE_FLOAT_16:
8906                         return "2";
8907
8908                 case DATA_TYPE_SIGNED_32:
8909                 case DATA_TYPE_UNSIGNED_32:
8910                 case DATA_TYPE_FLOAT_32:
8911                 case DATA_TYPE_VEC2_SIGNED_16:
8912                         return "4";
8913
8914                 case DATA_TYPE_SIGNED_64:
8915                 case DATA_TYPE_UNSIGNED_64:
8916                 case DATA_TYPE_FLOAT_64:
8917                 case DATA_TYPE_VEC2_SIGNED_32:
8918                         return "8";
8919
8920                 default:
8921                         DE_ASSERT(false);
8922         }
8923         return "";
8924 }
8925
8926 bool isSigned (ConversionDataType type)
8927 {
8928         switch (type)
8929         {
8930                 case DATA_TYPE_SIGNED_8:
8931                 case DATA_TYPE_SIGNED_16:
8932                 case DATA_TYPE_SIGNED_32:
8933                 case DATA_TYPE_SIGNED_64:
8934                 case DATA_TYPE_FLOAT_16:
8935                 case DATA_TYPE_FLOAT_32:
8936                 case DATA_TYPE_FLOAT_64:
8937                 case DATA_TYPE_VEC2_SIGNED_16:
8938                 case DATA_TYPE_VEC2_SIGNED_32:
8939                         return true;
8940
8941                 case DATA_TYPE_UNSIGNED_8:
8942                 case DATA_TYPE_UNSIGNED_16:
8943                 case DATA_TYPE_UNSIGNED_32:
8944                 case DATA_TYPE_UNSIGNED_64:
8945                         return false;
8946
8947                 default:
8948                         DE_ASSERT(false);
8949         }
8950         return false;
8951 }
8952
8953 bool isInt (ConversionDataType type)
8954 {
8955         switch (type)
8956         {
8957                 case DATA_TYPE_SIGNED_8:
8958                 case DATA_TYPE_SIGNED_16:
8959                 case DATA_TYPE_SIGNED_32:
8960                 case DATA_TYPE_SIGNED_64:
8961                 case DATA_TYPE_UNSIGNED_8:
8962                 case DATA_TYPE_UNSIGNED_16:
8963                 case DATA_TYPE_UNSIGNED_32:
8964                 case DATA_TYPE_UNSIGNED_64:
8965                         return true;
8966
8967                 case DATA_TYPE_FLOAT_16:
8968                 case DATA_TYPE_FLOAT_32:
8969                 case DATA_TYPE_FLOAT_64:
8970                 case DATA_TYPE_VEC2_SIGNED_16:
8971                 case DATA_TYPE_VEC2_SIGNED_32:
8972                         return false;
8973
8974                 default:
8975                         DE_ASSERT(false);
8976         }
8977         return false;
8978 }
8979
8980 bool isFloat (ConversionDataType type)
8981 {
8982         switch (type)
8983         {
8984                 case DATA_TYPE_SIGNED_8:
8985                 case DATA_TYPE_SIGNED_16:
8986                 case DATA_TYPE_SIGNED_32:
8987                 case DATA_TYPE_SIGNED_64:
8988                 case DATA_TYPE_UNSIGNED_8:
8989                 case DATA_TYPE_UNSIGNED_16:
8990                 case DATA_TYPE_UNSIGNED_32:
8991                 case DATA_TYPE_UNSIGNED_64:
8992                 case DATA_TYPE_VEC2_SIGNED_16:
8993                 case DATA_TYPE_VEC2_SIGNED_32:
8994                         return false;
8995
8996                 case DATA_TYPE_FLOAT_16:
8997                 case DATA_TYPE_FLOAT_32:
8998                 case DATA_TYPE_FLOAT_64:
8999                         return true;
9000
9001                 default:
9002                         DE_ASSERT(false);
9003         }
9004         return false;
9005 }
9006
9007 const string getTypeName (ConversionDataType type)
9008 {
9009         string prefix = isSigned(type) ? "" : "u";
9010
9011         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9012         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9013         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9014         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9015         else                                                                            DE_ASSERT(false);
9016
9017         return "";
9018 }
9019
9020 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9021 {
9022         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9023
9024         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9025 }
9026
9027 const string getAsmTypeName (ConversionDataType type)
9028 {
9029         string prefix;
9030
9031         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9032         else if (isFloat(type))                                         prefix = "f";
9033         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9034         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9035         else                                                                            DE_ASSERT(false);
9036
9037         return prefix + getBitWidthStr(type);
9038 }
9039
9040 template<typename T>
9041 BufferSp getSpecializedBuffer (deInt64 number)
9042 {
9043         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9044 }
9045
9046 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9047 {
9048         switch (type)
9049         {
9050                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9051                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9052                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9053                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9054                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9055                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9056                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9057                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9058                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9059                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9060                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9061                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9062                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9063
9064                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9065         }
9066 }
9067
9068 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9069 {
9070         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9071                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9072 }
9073
9074 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9075 {
9076         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9077                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9078                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9079 }
9080
9081 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9082 {
9083         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9084                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9085                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9086 }
9087
9088 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9089 {
9090         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9091                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9092 }
9093
9094 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9095 {
9096         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9097 }
9098
9099 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9100 {
9101         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9102 }
9103
9104 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9105 {
9106         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9107 }
9108
9109 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9110 {
9111         if (usesInt16(from, to) && !usesInt32(from, to))
9112                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9113
9114         if (usesInt64(from, to))
9115                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9116
9117         if (usesFloat64(from, to))
9118                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9119
9120         if (usesInt16(from, to) || usesFloat16(from, to))
9121         {
9122                 extensions.push_back("VK_KHR_16bit_storage");
9123                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9124         }
9125
9126         if (usesFloat16(from, to) || usesInt8(from, to))
9127         {
9128                 extensions.push_back("VK_KHR_shader_float16_int8");
9129
9130                 if (usesFloat16(from, to))
9131                 {
9132                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9133                 }
9134
9135                 if (usesInt8(from, to))
9136                 {
9137                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9138
9139                         extensions.push_back("VK_KHR_8bit_storage");
9140                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9141                 }
9142         }
9143 }
9144
9145 struct ConvertCase
9146 {
9147         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9148         : m_fromType            (from)
9149         , m_toType                      (to)
9150         , m_name                        (getTestName(from, to, suffix))
9151         , m_inputBuffer         (getBuffer(from, number))
9152         {
9153                 string caps;
9154                 string decl;
9155                 string exts;
9156
9157                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9158                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9159
9160                 if (separateOutput)
9161                         m_outputBuffer = getBuffer(to, outputNumber);
9162                 else
9163                         m_outputBuffer = getBuffer(to, number);
9164
9165                 if (usesInt8(from, to))
9166                 {
9167                         bool requiresInt8Capability = true;
9168                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9169                         {
9170                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9171                                 if (usesInt32(from, to))
9172                                         requiresInt8Capability = false;
9173                         }
9174
9175                         caps += "OpCapability StorageBuffer8BitAccess\n";
9176                         if (requiresInt8Capability)
9177                                 caps += "OpCapability Int8\n";
9178
9179                         decl += "%i8         = OpTypeInt 8 1\n"
9180                                         "%u8         = OpTypeInt 8 0\n";
9181                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9182                 }
9183
9184                 if (usesInt16(from, to))
9185                 {
9186                         bool requiresInt16Capability = true;
9187
9188                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9189                         {
9190                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9191                                 if (usesInt32(from, to) || usesFloat32(from, to))
9192                                         requiresInt16Capability = false;
9193                         }
9194
9195                         decl += "%i16        = OpTypeInt 16 1\n"
9196                                         "%u16        = OpTypeInt 16 0\n"
9197                                         "%i16vec2    = OpTypeVector %i16 2\n";
9198
9199                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9200                         if (requiresInt16Capability)
9201                                 caps += "OpCapability Int16\n";
9202                 }
9203
9204                 if (usesFloat16(from, to))
9205                 {
9206                         decl += "%f16        = OpTypeFloat 16\n";
9207
9208                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9209                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9210                                 caps += "OpCapability Float16\n";
9211                 }
9212
9213                 if (usesInt16(from, to) || usesFloat16(from, to))
9214                 {
9215                         caps += "OpCapability StorageUniformBufferBlock16\n";
9216                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9217                 }
9218
9219                 if (usesInt64(from, to))
9220                 {
9221                         caps += "OpCapability Int64\n";
9222                         decl += "%i64        = OpTypeInt 64 1\n"
9223                                         "%u64        = OpTypeInt 64 0\n";
9224                 }
9225
9226                 if (usesFloat64(from, to))
9227                 {
9228                         caps += "OpCapability Float64\n";
9229                         decl += "%f64        = OpTypeFloat 64\n";
9230                 }
9231
9232                 m_asmTypes["datatype_capabilities"]             = caps;
9233                 m_asmTypes["datatype_additional_decl"]  = decl;
9234                 m_asmTypes["datatype_extensions"]               = exts;
9235         }
9236
9237         ConversionDataType              m_fromType;
9238         ConversionDataType              m_toType;
9239         string                                  m_name;
9240         map<string, string>             m_asmTypes;
9241         BufferSp                                m_inputBuffer;
9242         BufferSp                                m_outputBuffer;
9243 };
9244
9245 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9246 {
9247         map<string, string> params = convertCase.m_asmTypes;
9248
9249         params["instruction"]   = instruction;
9250         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9251         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9252
9253         const StringTemplate shader (
9254                 "OpCapability Shader\n"
9255                 "${datatype_capabilities}"
9256                 "${datatype_extensions:opt}"
9257                 "OpMemoryModel Logical GLSL450\n"
9258                 "OpEntryPoint GLCompute %main \"main\"\n"
9259                 "OpExecutionMode %main LocalSize 1 1 1\n"
9260                 "OpSource GLSL 430\n"
9261                 "OpName %main           \"main\"\n"
9262                 // Decorators
9263                 "OpDecorate %indata DescriptorSet 0\n"
9264                 "OpDecorate %indata Binding 0\n"
9265                 "OpDecorate %outdata DescriptorSet 0\n"
9266                 "OpDecorate %outdata Binding 1\n"
9267                 "OpDecorate %in_buf BufferBlock\n"
9268                 "OpDecorate %out_buf BufferBlock\n"
9269                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9270                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9271                 // Base types
9272                 "%void       = OpTypeVoid\n"
9273                 "%voidf      = OpTypeFunction %void\n"
9274                 "%u32        = OpTypeInt 32 0\n"
9275                 "%i32        = OpTypeInt 32 1\n"
9276                 "%f32        = OpTypeFloat 32\n"
9277                 "%v2i32      = OpTypeVector %i32 2\n"
9278                 "${datatype_additional_decl}"
9279                 "%uvec3      = OpTypeVector %u32 3\n"
9280                 // Derived types
9281                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9282                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9283                 "%in_buf     = OpTypeStruct %${inputType}\n"
9284                 "%out_buf    = OpTypeStruct %${outputType}\n"
9285                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9286                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9287                 "%indata     = OpVariable %in_bufptr Uniform\n"
9288                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9289                 // Constants
9290                 "%zero       = OpConstant %i32 0\n"
9291                 // Main function
9292                 "%main       = OpFunction %void None %voidf\n"
9293                 "%label      = OpLabel\n"
9294                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9295                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9296                 "%inval      = OpLoad %${inputType} %inloc\n"
9297                 "%conv       = ${instruction} %${outputType} %inval\n"
9298                 "              OpStore %outloc %conv\n"
9299                 "              OpReturn\n"
9300                 "              OpFunctionEnd\n"
9301         );
9302
9303         return shader.specialize(params);
9304 }
9305
9306 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9307 {
9308         if (instruction == "OpUConvert")
9309         {
9310                 // Convert unsigned int to unsigned int
9311                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9312                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9313                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9314
9315                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9316                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9317                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9318
9319                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9320                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9321                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9322
9323                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9324                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9325                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9326         }
9327         else if (instruction == "OpSConvert")
9328         {
9329                 // Sign extension int->int
9330                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9331                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9332                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9333                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9334                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9335                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9336
9337                 // Truncate for int->int
9338                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9339                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9340                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9341                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9342                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9343                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9344
9345                 // Sign extension for int->uint
9346                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9347                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9348                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9349                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9350                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9351                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9352
9353                 // Truncate for int->uint
9354                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9355                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9356                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9357                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9358                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9359                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9360
9361                 // Sign extension for uint->int
9362                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9363                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9364                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9365                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9366                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9367                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9368
9369                 // Truncate for uint->int
9370                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9371                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9372                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9373                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9374                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9375                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9376
9377                 // Convert i16vec2 to i32vec2 and vice versa
9378                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9379                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9380                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9381                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9382         }
9383         else if (instruction == "OpFConvert")
9384         {
9385                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9386                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9387                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9388
9389                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9390                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9391
9392                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9393                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9394         }
9395         else if (instruction == "OpConvertFToU")
9396         {
9397                 // Normal numbers from uint8 range
9398                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9399                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9400                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9401
9402                 // Maximum uint8 value
9403                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9404                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9405                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9406
9407                 // +0
9408                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9409                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9410                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9411
9412                 // -0
9413                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9414                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9415                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9416
9417                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9418                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9419                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9420                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9421
9422                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9423                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9424                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9425                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9426
9427                 // +0
9428                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9429                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9430                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9431
9432                 // -0
9433                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9434                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9435                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9436
9437                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9438                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9439                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9440                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9441                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9442                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9443         }
9444         else if (instruction == "OpConvertUToF")
9445         {
9446                 // Normal numbers from uint8 range
9447                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9448                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9449                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9450
9451                 // Maximum uint8 value
9452                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9453                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9454                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9455
9456                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9457                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9458                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9459                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9460
9461                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9462                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9463                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9464                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9465
9466                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9467                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9468                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9469                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9470                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9471                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9472         }
9473         else if (instruction == "OpConvertFToS")
9474         {
9475                 // Normal numbers from int8 range
9476                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9477                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9478                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9479
9480                 // Minimum int8 value
9481                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9482                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9483                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9484
9485                 // Maximum int8 value
9486                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9487                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9488                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9489
9490                 // +0
9491                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9492                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9493                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9494
9495                 // -0
9496                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9497                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9498                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9499
9500                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9501                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9502                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9503                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9504
9505                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9506                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9507                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9508                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9509
9510                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9511                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9512                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9513                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9514
9515                 // +0
9516                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9517                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9518                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9519
9520                 // -0
9521                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9522                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9523                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9524
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9526                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9527                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9533         }
9534         else if (instruction == "OpConvertSToF")
9535         {
9536                 // Normal numbers from int8 range
9537                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9538                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9539                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9540
9541                 // Minimum int8 value
9542                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9543                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9544                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9545
9546                 // Maximum int8 value
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9548                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9549                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9550
9551                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9552                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9555
9556                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9557                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9558                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9559                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9560
9561                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9564                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9565
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9567                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9572         }
9573         else
9574                 DE_FATAL("Unknown instruction");
9575 }
9576
9577 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9578 {
9579         map<string, string> params = convertCase.m_asmTypes;
9580         map<string, string> fragments;
9581
9582         params["instruction"] = instruction;
9583         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9584
9585         const StringTemplate decoration (
9586                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9587                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9588                 "      OpDecorate %SSBOi Binding 0\n"
9589                 "      OpDecorate %SSBOo Binding 1\n"
9590                 "      OpDecorate %s_SSBOi Block\n"
9591                 "      OpDecorate %s_SSBOo Block\n"
9592                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9593                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9594
9595         const StringTemplate pre_main (
9596                 "${datatype_additional_decl:opt}"
9597                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9598                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9599                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9600                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9601                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9602                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9603                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9604                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9605
9606         const StringTemplate testfun (
9607                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9608                 "%param     = OpFunctionParameter %v4f32\n"
9609                 "%label     = OpLabel\n"
9610                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9611                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9612                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9613                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9614                 "             OpStore %oLoc %valOut\n"
9615                 "             OpReturnValue %param\n"
9616                 "             OpFunctionEnd\n");
9617
9618         params["datatype_extensions"] =
9619                 params["datatype_extensions"] +
9620                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9621
9622         fragments["capability"] = params["datatype_capabilities"];
9623         fragments["extension"]  = params["datatype_extensions"];
9624         fragments["decoration"] = decoration.specialize(params);
9625         fragments["pre_main"]   = pre_main.specialize(params);
9626         fragments["testfun"]    = testfun.specialize(params);
9627
9628         return fragments;
9629 }
9630
9631 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9632 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9633 {
9634         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9635         vector<ConvertCase>                                     testCases;
9636         createConvertCases(testCases, instruction);
9637
9638         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9639         {
9640                 ComputeShaderSpec spec;
9641                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9642                 spec.numWorkGroups              = IVec3(1, 1, 1);
9643                 spec.inputs.push_back   (test->m_inputBuffer);
9644                 spec.outputs.push_back  (test->m_outputBuffer);
9645
9646                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9647
9648                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9649         }
9650         return group.release();
9651 }
9652
9653 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9654 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9655 {
9656         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9657         vector<ConvertCase>                                     testCases;
9658         createConvertCases(testCases, instruction);
9659
9660         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9661         {
9662                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9663                 VulkanFeatures          vulkanFeatures;
9664                 GraphicsResources       resources;
9665                 vector<string>          extensions;
9666                 SpecConstants           noSpecConstants;
9667                 PushConstants           noPushConstants;
9668                 GraphicsInterfaces      noInterfaces;
9669                 tcu::RGBA                       defaultColors[4];
9670
9671                 getDefaultColors                        (defaultColors);
9672                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9673                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9674                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9675
9676                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9677
9678                 createTestsForAllStages(
9679                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9680                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9681         }
9682         return group.release();
9683 }
9684
9685 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9686 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9687 {
9688         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9689         RGBA                                                    inputColors[4];
9690         RGBA                                                    outputColors[4];
9691         vector<string>                                  extensions;
9692         GraphicsResources                               resources;
9693         VulkanFeatures                                  features;
9694
9695         const char                                              functionStart[]  =
9696                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9697                 "%param1                = OpFunctionParameter %v4f32\n"
9698                 "%lbl                   = OpLabel\n";
9699
9700         const char                                              functionEnd[]           =
9701                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9702                 "                         OpReturnValue %transformed_param_32\n"
9703                 "                         OpFunctionEnd\n";
9704
9705         struct NameConstantsCode
9706         {
9707                 string name;
9708                 string constants;
9709                 string code;
9710         };
9711
9712 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9713                         "%f16                  = OpTypeFloat 16\n"                                                 \
9714                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9715                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9716                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9717                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9718                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9719                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9720                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9721                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9722
9723         NameConstantsCode                               tests[] =
9724         {
9725                 {
9726                         "vec4",
9727
9728                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9729                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9730                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9731                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9732                 },
9733                 {
9734                         "struct",
9735
9736                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9737                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9738                         "%fp_stype             = OpTypePointer Function %stype\n"
9739                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9740                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9741                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9742                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9743
9744                         "%v                    = OpVariable %fp_stype Function %cval\n"
9745                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9746                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9747                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9748                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9749                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9750                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9751                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9752                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9753                 },
9754                 {
9755                         // [1|0|0|0.5] [x] = x + 0.5
9756                         // [0|1|0|0.5] [y] = y + 0.5
9757                         // [0|0|1|0.5] [z] = z + 0.5
9758                         // [0|0|0|1  ] [1] = 1
9759                         "matrix",
9760
9761                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9762                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9763                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9764                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9765                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9766                         "%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"
9767                         "%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",
9768
9769                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9770                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9771                 },
9772                 {
9773                         "array",
9774
9775                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9776                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9777                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9778                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9779                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9780                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9781
9782                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9783                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9784                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9785                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9786                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9787                         "%f_val                = OpLoad %f16 %f\n"
9788                         "%f1_val               = OpLoad %f16 %f1\n"
9789                         "%f2_val               = OpLoad %f16 %f2\n"
9790                         "%f3_val               = OpLoad %f16 %f3\n"
9791                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9792                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9793                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9794                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9795                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9796                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9797                 },
9798                 {
9799                         //
9800                         // [
9801                         //   {
9802                         //      0.0,
9803                         //      [ 1.0, 1.0, 1.0, 1.0]
9804                         //   },
9805                         //   {
9806                         //      1.0,
9807                         //      [ 0.0, 0.5, 0.0, 0.0]
9808                         //   }, //     ^^^
9809                         //   {
9810                         //      0.0,
9811                         //      [ 1.0, 1.0, 1.0, 1.0]
9812                         //   }
9813                         // ]
9814                         "array_of_struct_of_array",
9815
9816                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9817                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9818                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9819                         "%stype                = OpTypeStruct %f16 %a4f16\n"
9820                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
9821                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
9822                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9823                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9824                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9825                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9826                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9827
9828                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
9829                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9830                         "%f_l                  = OpLoad %f16 %f\n"
9831                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9832                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9833                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9834                 }
9835         };
9836
9837         getHalfColorsFullAlpha(inputColors);
9838         outputColors[0] = RGBA(255, 255, 255, 255);
9839         outputColors[1] = RGBA(255, 127, 127, 255);
9840         outputColors[2] = RGBA(127, 255, 127, 255);
9841         outputColors[3] = RGBA(127, 127, 255, 255);
9842
9843         extensions.push_back("VK_KHR_16bit_storage");
9844         extensions.push_back("VK_KHR_shader_float16_int8");
9845         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9846
9847         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9848         {
9849                 map<string, string> fragments;
9850
9851                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
9852                 fragments["capability"] = "OpCapability Float16\n";
9853                 fragments["pre_main"]   = tests[testNdx].constants;
9854                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
9855
9856                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9857         }
9858         return opConstantCompositeTests.release();
9859 }
9860
9861 template<typename T>
9862 void finalizeTestsCreation (T&                                                  specResource,
9863                                                         const map<string, string>&      fragments,
9864                                                         tcu::TestContext&                       testCtx,
9865                                                         tcu::TestCaseGroup&                     testGroup,
9866                                                         const std::string&                      testName,
9867                                                         const VulkanFeatures&           vulkanFeatures,
9868                                                         const vector<string>&           extensions,
9869                                                         const IVec3&                            numWorkGroups);
9870
9871 template<>
9872 void finalizeTestsCreation (GraphicsResources&                  specResource,
9873                                                         const map<string, string>&      fragments,
9874                                                         tcu::TestContext&                       ,
9875                                                         tcu::TestCaseGroup&                     testGroup,
9876                                                         const std::string&                      testName,
9877                                                         const VulkanFeatures&           vulkanFeatures,
9878                                                         const vector<string>&           extensions,
9879                                                         const IVec3&                            )
9880 {
9881         RGBA defaultColors[4];
9882         getDefaultColors(defaultColors);
9883
9884         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9885 }
9886
9887 template<>
9888 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
9889                                                         const map<string, string>&      fragments,
9890                                                         tcu::TestContext&                       testCtx,
9891                                                         tcu::TestCaseGroup&                     testGroup,
9892                                                         const std::string&                      testName,
9893                                                         const VulkanFeatures&           vulkanFeatures,
9894                                                         const vector<string>&           extensions,
9895                                                         const IVec3&                            numWorkGroups)
9896 {
9897         specResource.numWorkGroups = numWorkGroups;
9898         specResource.requestedVulkanFeatures = vulkanFeatures;
9899         specResource.extensions = extensions;
9900
9901         specResource.assembly = makeComputeShaderAssembly(fragments);
9902
9903         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9904 }
9905
9906 template<class SpecResource>
9907 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9908 {
9909         const string                                            nan                                     = nanSupported ? "_nan" : "";
9910         const string                                            groupName                       = "logical" + nan;
9911         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9912
9913         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9914         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
9915         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
9916         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
9917         const deUint32                                          numDataPointsScalar     = 16;
9918         const deUint32                                          numDataPointsVector     = 14;
9919         const vector<deFloat16>                         float16DataScalar       = getFloat16s(rnd, numDataPointsScalar);
9920         const vector<deFloat16>                         float16DataVector       = getFloat16s(rnd, numDataPointsVector);
9921         const vector<deFloat16>                         float16Data1            = squarize(float16DataScalar, 0);                       // Total Size: square(sizeof(float16DataScalar))
9922         const vector<deFloat16>                         float16Data2            = squarize(float16DataScalar, 1);
9923         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16DataVector, 0);         // Total Size: 2 * (square(square(sizeof(float16DataVector))))
9924         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16DataVector, 1);
9925         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
9926         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
9927
9928         struct TestOp
9929         {
9930                 const char*             opCode;
9931                 VerifyIOFunc    verifyFuncNan;
9932                 VerifyIOFunc    verifyFuncNonNan;
9933                 const deUint32  argCount;
9934         };
9935
9936         const TestOp    testOps[]       =
9937         {
9938                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
9939                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
9940                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
9941                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
9942                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
9943                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
9944                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
9945                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
9946                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
9947                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
9948                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
9949                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
9950                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
9951                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
9952         };
9953
9954         { // scalar cases
9955                 const StringTemplate preMain
9956                 (
9957                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9958                         "      %f16 = OpTypeFloat 16\n"
9959                         "  %c_f16_0 = OpConstant %f16 0.0\n"
9960                         "  %c_f16_1 = OpConstant %f16 1.0\n"
9961                         "   %up_f16 = OpTypePointer Uniform %f16\n"
9962                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9963                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
9964                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9965                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9966                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9967                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9968                 );
9969
9970                 const StringTemplate decoration
9971                 (
9972                         "OpDecorate %ra_f16 ArrayStride 2\n"
9973                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9974                         "OpDecorate %SSBO16 BufferBlock\n"
9975                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9976                         "OpDecorate %ssbo_src0 Binding 0\n"
9977                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9978                         "OpDecorate %ssbo_src1 Binding 1\n"
9979                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9980                         "OpDecorate %ssbo_dst Binding 2\n"
9981                 );
9982
9983                 const StringTemplate testFun
9984                 (
9985                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9986                         "    %param = OpFunctionParameter %v4f32\n"
9987
9988                         "    %entry = OpLabel\n"
9989                         "        %i = OpVariable %fp_i32 Function\n"
9990                         "             OpStore %i %c_i32_0\n"
9991                         "             OpBranch %loop\n"
9992
9993                         "     %loop = OpLabel\n"
9994                         "    %i_cmp = OpLoad %i32 %i\n"
9995                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9996                         "             OpLoopMerge %merge %next None\n"
9997                         "             OpBranchConditional %lt %write %merge\n"
9998
9999                         "    %write = OpLabel\n"
10000                         "      %ndx = OpLoad %i32 %i\n"
10001
10002                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10003                         " %val_src0 = OpLoad %f16 %src0\n"
10004
10005                         "${op_arg1_calc}"
10006
10007                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10008                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10009                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10010                         "             OpStore %dst %val_dst\n"
10011                         "             OpBranch %next\n"
10012
10013                         "     %next = OpLabel\n"
10014                         "    %i_cur = OpLoad %i32 %i\n"
10015                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10016                         "             OpStore %i %i_new\n"
10017                         "             OpBranch %loop\n"
10018
10019                         "    %merge = OpLabel\n"
10020                         "             OpReturnValue %param\n"
10021
10022                         "             OpFunctionEnd\n"
10023                 );
10024
10025                 const StringTemplate arg1Calc
10026                 (
10027                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10028                         " %val_src1 = OpLoad %f16 %src1\n"
10029                 );
10030
10031                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10032                 {
10033                         const size_t            iterations              = float16Data1.size();
10034                         const TestOp&           testOp                  = testOps[testOpsIdx];
10035                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10036                         SpecResource            specResource;
10037                         map<string, string>     specs;
10038                         VulkanFeatures          features;
10039                         map<string, string>     fragments;
10040                         vector<string>          extensions;
10041
10042                         specs["num_data_points"]        = de::toString(iterations);
10043                         specs["op_code"]                        = testOp.opCode;
10044                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10045                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10046
10047                         fragments["extension"]          = spvExtensions;
10048                         fragments["capability"]         = spvCapabilities;
10049                         fragments["execution_mode"]     = spvExecutionMode;
10050                         fragments["decoration"]         = decoration.specialize(specs);
10051                         fragments["pre_main"]           = preMain.specialize(specs);
10052                         fragments["testfun"]            = testFun.specialize(specs);
10053
10054                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10055                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10056                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10057                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10058
10059                         extensions.push_back("VK_KHR_16bit_storage");
10060                         extensions.push_back("VK_KHR_shader_float16_int8");
10061
10062                         if (nanSupported)
10063                         {
10064                                 extensions.push_back("VK_KHR_shader_float_controls");
10065
10066                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10067                         }
10068
10069                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10070                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10071
10072                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10073                 }
10074         }
10075         { // vector cases
10076                 const StringTemplate preMain
10077                 (
10078                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10079                         "     %v2bool = OpTypeVector %bool 2\n"
10080                         "        %f16 = OpTypeFloat 16\n"
10081                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10082                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10083                         "      %v2f16 = OpTypeVector %f16 2\n"
10084                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10085                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10086                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10087                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10088                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10089                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10090                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10091                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10092                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10093                 );
10094
10095                 const StringTemplate decoration
10096                 (
10097                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10098                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10099                         "OpDecorate %SSBO16 BufferBlock\n"
10100                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10101                         "OpDecorate %ssbo_src0 Binding 0\n"
10102                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10103                         "OpDecorate %ssbo_src1 Binding 1\n"
10104                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10105                         "OpDecorate %ssbo_dst Binding 2\n"
10106                 );
10107
10108                 const StringTemplate testFun
10109                 (
10110                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10111                         "    %param = OpFunctionParameter %v4f32\n"
10112
10113                         "    %entry = OpLabel\n"
10114                         "        %i = OpVariable %fp_i32 Function\n"
10115                         "             OpStore %i %c_i32_0\n"
10116                         "             OpBranch %loop\n"
10117
10118                         "     %loop = OpLabel\n"
10119                         "    %i_cmp = OpLoad %i32 %i\n"
10120                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10121                         "             OpLoopMerge %merge %next None\n"
10122                         "             OpBranchConditional %lt %write %merge\n"
10123
10124                         "    %write = OpLabel\n"
10125                         "      %ndx = OpLoad %i32 %i\n"
10126
10127                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10128                         " %val_src0 = OpLoad %v2f16 %src0\n"
10129
10130                         "${op_arg1_calc}"
10131
10132                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10133                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10134                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10135                         "             OpStore %dst %val_dst\n"
10136                         "             OpBranch %next\n"
10137
10138                         "     %next = OpLabel\n"
10139                         "    %i_cur = OpLoad %i32 %i\n"
10140                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10141                         "             OpStore %i %i_new\n"
10142                         "             OpBranch %loop\n"
10143
10144                         "    %merge = OpLabel\n"
10145                         "             OpReturnValue %param\n"
10146
10147                         "             OpFunctionEnd\n"
10148                 );
10149
10150                 const StringTemplate arg1Calc
10151                 (
10152                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10153                         " %val_src1 = OpLoad %v2f16 %src1\n"
10154                 );
10155
10156                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10157                 {
10158                         const deUint32          itemsPerVec     = 2;
10159                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10160                         const TestOp&           testOp          = testOps[testOpsIdx];
10161                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10162                         SpecResource            specResource;
10163                         map<string, string>     specs;
10164                         vector<string>          extensions;
10165                         VulkanFeatures          features;
10166                         map<string, string>     fragments;
10167
10168                         specs["num_data_points"]        = de::toString(iterations);
10169                         specs["op_code"]                        = testOp.opCode;
10170                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10171                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10172
10173                         fragments["extension"]          = spvExtensions;
10174                         fragments["capability"]         = spvCapabilities;
10175                         fragments["execution_mode"]     = spvExecutionMode;
10176                         fragments["decoration"]         = decoration.specialize(specs);
10177                         fragments["pre_main"]           = preMain.specialize(specs);
10178                         fragments["testfun"]            = testFun.specialize(specs);
10179
10180                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10181                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10182                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10183                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10184
10185                         extensions.push_back("VK_KHR_16bit_storage");
10186                         extensions.push_back("VK_KHR_shader_float16_int8");
10187
10188                         if (nanSupported)
10189                         {
10190                                 extensions.push_back("VK_KHR_shader_float_controls");
10191
10192                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10193                         }
10194
10195                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10196                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10197
10198                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10199                 }
10200         }
10201
10202         return testGroup.release();
10203 }
10204
10205 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10206 {
10207         if (inputs.size() != 1 || outputAllocs.size() != 1)
10208                 return false;
10209
10210         vector<deUint8> input1Bytes;
10211
10212         inputs[0].getBytes(input1Bytes);
10213
10214         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10215         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10216         std::string                             error;
10217
10218         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10219         {
10220                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10221                 {
10222                         log << TestLog::Message << error << TestLog::EndMessage;
10223
10224                         return false;
10225                 }
10226         }
10227
10228         return true;
10229 }
10230
10231 template<class SpecResource>
10232 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10233 {
10234         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10235
10236         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10237         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10238         const deUint32                                          numDataPoints           = 256;
10239         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10240         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10241         map<string, string>                                     fragments;
10242
10243         struct TestType
10244         {
10245                 const deUint32  typeComponents;
10246                 const char*             typeName;
10247                 const char*             typeDecls;
10248         };
10249
10250         const TestType  testTypes[]     =
10251         {
10252                 {
10253                         1,
10254                         "f16",
10255                         ""
10256                 },
10257                 {
10258                         2,
10259                         "v2f16",
10260                         "      %v2f16 = OpTypeVector %f16 2\n"
10261                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10262                 },
10263                 {
10264                         4,
10265                         "v4f16",
10266                         "      %v4f16 = OpTypeVector %f16 4\n"
10267                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10268                 },
10269         };
10270
10271         const StringTemplate preMain
10272         (
10273                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10274                 "     %v2bool = OpTypeVector %bool 2\n"
10275                 "        %f16 = OpTypeFloat 16\n"
10276                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10277
10278                 "${type_decls}"
10279
10280                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10281                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10282                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10283                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10284                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10285                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10286                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10287         );
10288
10289         const StringTemplate decoration
10290         (
10291                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10292                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10293                 "OpDecorate %SSBO16 BufferBlock\n"
10294                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10295                 "OpDecorate %ssbo_src Binding 0\n"
10296                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10297                 "OpDecorate %ssbo_dst Binding 1\n"
10298         );
10299
10300         const StringTemplate testFun
10301         (
10302                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10303                 "    %param = OpFunctionParameter %v4f32\n"
10304                 "    %entry = OpLabel\n"
10305
10306                 "        %i = OpVariable %fp_i32 Function\n"
10307                 "             OpStore %i %c_i32_0\n"
10308                 "             OpBranch %loop\n"
10309
10310                 "     %loop = OpLabel\n"
10311                 "    %i_cmp = OpLoad %i32 %i\n"
10312                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10313                 "             OpLoopMerge %merge %next None\n"
10314                 "             OpBranchConditional %lt %write %merge\n"
10315
10316                 "    %write = OpLabel\n"
10317                 "      %ndx = OpLoad %i32 %i\n"
10318
10319                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10320                 "  %val_src = OpLoad %${tt} %src\n"
10321
10322                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10323                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10324                 "             OpStore %dst %val_dst\n"
10325                 "             OpBranch %next\n"
10326
10327                 "     %next = OpLabel\n"
10328                 "    %i_cur = OpLoad %i32 %i\n"
10329                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10330                 "             OpStore %i %i_new\n"
10331                 "             OpBranch %loop\n"
10332
10333                 "    %merge = OpLabel\n"
10334                 "             OpReturnValue %param\n"
10335
10336                 "             OpFunctionEnd\n"
10337
10338                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10339                 "   %param0 = OpFunctionParameter %${tt}\n"
10340                 " %entry_pf = OpLabel\n"
10341                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10342                 "             OpReturnValue %res0\n"
10343                 "             OpFunctionEnd\n"
10344         );
10345
10346         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10347         {
10348                 const TestType&         testType                = testTypes[testTypeIdx];
10349                 const string            testName                = testType.typeName;
10350                 const deUint32          itemsPerType    = testType.typeComponents;
10351                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10352                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10353                 SpecResource            specResource;
10354                 map<string, string>     specs;
10355                 VulkanFeatures          features;
10356                 vector<string>          extensions;
10357
10358                 specs["cap"]                            = "StorageUniformBufferBlock16";
10359                 specs["num_data_points"]        = de::toString(iterations);
10360                 specs["tt"]                                     = testType.typeName;
10361                 specs["tt_stride"]                      = de::toString(typeStride);
10362                 specs["type_decls"]                     = testType.typeDecls;
10363
10364                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10365                 fragments["capability"]         = capabilities.specialize(specs);
10366                 fragments["decoration"]         = decoration.specialize(specs);
10367                 fragments["pre_main"]           = preMain.specialize(specs);
10368                 fragments["testfun"]            = testFun.specialize(specs);
10369
10370                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10371                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10372                 specResource.verifyIO = compareFP16FunctionSetFunc;
10373
10374                 extensions.push_back("VK_KHR_16bit_storage");
10375                 extensions.push_back("VK_KHR_shader_float16_int8");
10376
10377                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10378                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10379
10380                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10381         }
10382
10383         return testGroup.release();
10384 }
10385
10386 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10387 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10388 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10389
10390 template<deUint32 R, deUint32 N>
10391 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10392 {
10393         return N * ((R * y) + x) + n;
10394 }
10395
10396 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10397 struct getFDelta
10398 {
10399         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10400         {
10401                 DE_STATIC_ASSERT(R%2 == 0);
10402                 DE_ASSERT(flavor == 0);
10403                 DE_UNREF(flavor);
10404
10405                 const X0                        x0;
10406                 const X1                        x1;
10407                 const Y0                        y0;
10408                 const Y1                        y1;
10409                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10410                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10411                 const tcu::Float16      f0      = tcu::Float16(v0);
10412                 const tcu::Float16      f1      = tcu::Float16(v1);
10413                 const float                     d0      = f0.asFloat();
10414                 const float                     d1      = f1.asFloat();
10415                 const float                     d       = d1 - d0;
10416
10417                 return d;
10418         }
10419
10420         getFDelta(){}
10421 };
10422
10423 template<deUint32 F, class Class0, class Class1>
10424 struct getFOneOf
10425 {
10426         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10427         {
10428                 DE_ASSERT(flavor < F);
10429
10430                 if (flavor == 0)
10431                 {
10432                         Class0 c;
10433
10434                         return c(data, x, y, n, flavor);
10435                 }
10436                 else
10437                 {
10438                         Class1 c;
10439
10440                         return c(data, x, y, n, flavor - 1);
10441                 }
10442         }
10443
10444         getFOneOf(){}
10445 };
10446
10447 template<class FineX0, class FineX1, class FineY0, class FineY1>
10448 struct calcWidthOf4
10449 {
10450         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10451         {
10452                 DE_ASSERT(flavor < 4);
10453
10454                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10455                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10456                 const getFOneOf<2, FineX0, FineX1>      cx;
10457                 const getFOneOf<2, FineY0, FineY1>      cy;
10458                 float                                                           v               = 0;
10459
10460                 v += fabsf(cx(data, x, y, n, flavorX));
10461                 v += fabsf(cy(data, x, y, n, flavorY));
10462
10463                 return v;
10464         }
10465
10466         calcWidthOf4(){}
10467 };
10468
10469 template<deUint32 R, deUint32 N, class Derivative>
10470 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10471 {
10472         const deUint32          numDataPointsByAxis     = R;
10473         const Derivative        derivativeFunc;
10474
10475         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10476         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10477         for (deUint32 n = 0; n < N; ++n)
10478         {
10479                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10480                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10481                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10482
10483                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10484
10485                 if (reportError)
10486                 {
10487                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10488                         reportError     = !compare16BitFloat(expected, output, error);
10489                 }
10490
10491                 if (reportError)
10492                 {
10493                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10494
10495                         return false;
10496                 }
10497         }
10498
10499         return true;
10500 }
10501
10502 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10503 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10504 {
10505         if (inputs.size() != 1 || outputAllocs.size() != 1)
10506                 return false;
10507
10508         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10509         std::string                     results[FLAVOUR_COUNT];
10510         vector<deUint8>         inputBytes;
10511
10512         inputs[0].getBytes(inputBytes);
10513
10514         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10515         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10516
10517         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10518
10519         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10520                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10521                 {
10522                         break;
10523                 }
10524                 else
10525                 {
10526                         successfulRuns--;
10527                 }
10528
10529         if (successfulRuns == 0)
10530                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10531                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10532
10533         return successfulRuns > 0;
10534 }
10535
10536 template<deUint32 R, deUint32 N>
10537 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10538 {
10539         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10540         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10541
10542         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10543         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10544         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10545         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10546         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10547         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10548
10549         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10550         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10551
10552         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10553         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10554         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10555
10556         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10557         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10558
10559         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10560         const deUint32                                          numDataPointsByAxis     = R;
10561         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10562         vector<deFloat16>                                       float16InputX;
10563         vector<deFloat16>                                       float16InputY;
10564         vector<deFloat16>                                       float16InputW;
10565         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10566         RGBA                                                            defaultColors[4];
10567
10568         getDefaultColors(defaultColors);
10569
10570         float16InputX.reserve(numDataPoints);
10571         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10572         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10573         for (deUint32 n = 0; n < N; ++n)
10574         {
10575                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10576
10577                 if (y%2 == 0)
10578                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10579                 else
10580                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10581         }
10582
10583         float16InputY.reserve(numDataPoints);
10584         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10585         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10586         for (deUint32 n = 0; n < N; ++n)
10587         {
10588                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10589
10590                 if (x%2 == 0)
10591                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10592                 else
10593                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10594         }
10595
10596         const deFloat16 testNumbers[]   =
10597         {
10598                 tcu::Float16( 2.0  ).bits(),
10599                 tcu::Float16( 4.0  ).bits(),
10600                 tcu::Float16( 8.0  ).bits(),
10601                 tcu::Float16( 16.0 ).bits(),
10602                 tcu::Float16( 32.0 ).bits(),
10603                 tcu::Float16( 64.0 ).bits(),
10604                 tcu::Float16( 128.0).bits(),
10605                 tcu::Float16( 256.0).bits(),
10606                 tcu::Float16( 512.0).bits(),
10607                 tcu::Float16(-2.0  ).bits(),
10608                 tcu::Float16(-4.0  ).bits(),
10609                 tcu::Float16(-8.0  ).bits(),
10610                 tcu::Float16(-16.0 ).bits(),
10611                 tcu::Float16(-32.0 ).bits(),
10612                 tcu::Float16(-64.0 ).bits(),
10613                 tcu::Float16(-128.0).bits(),
10614                 tcu::Float16(-256.0).bits(),
10615                 tcu::Float16(-512.0).bits(),
10616         };
10617
10618         float16InputW.reserve(numDataPoints);
10619         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10620         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10621         for (deUint32 n = 0; n < N; ++n)
10622                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10623
10624         struct TestOp
10625         {
10626                 const char*                     opCode;
10627                 vector<deFloat16>&      inputData;
10628                 VerifyIOFunc            verifyFunc;
10629         };
10630
10631         const TestOp    testOps[]       =
10632         {
10633                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10634                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10635                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10636                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10637                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10638                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10639                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10640                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10641                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10642         };
10643
10644         struct TestType
10645         {
10646                 const deUint32  typeComponents;
10647                 const char*             typeName;
10648                 const char*             typeDecls;
10649         };
10650
10651         const TestType  testTypes[]     =
10652         {
10653                 {
10654                         1,
10655                         "f16",
10656                         ""
10657                 },
10658                 {
10659                         2,
10660                         "v2f16",
10661                         "      %v2f16 = OpTypeVector %f16 2\n"
10662                 },
10663                 {
10664                         4,
10665                         "v4f16",
10666                         "      %v4f16 = OpTypeVector %f16 4\n"
10667                 },
10668         };
10669
10670         const deUint32  testTypeNdx     = (N == 1) ? 0
10671                                                                 : (N == 2) ? 1
10672                                                                 : (N == 4) ? 2
10673                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10674         const TestType& testType        =       testTypes[testTypeNdx];
10675
10676         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10677         DE_ASSERT(testType.typeComponents == N);
10678
10679         const StringTemplate preMain
10680         (
10681                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10682                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10683                 "      %f16 = OpTypeFloat 16\n"
10684                 "${type_decls}"
10685                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10686                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10687                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10688                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10689                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10690                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10691         );
10692
10693         const StringTemplate decoration
10694         (
10695                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10696                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10697                 "OpDecorate %SSBO16 BufferBlock\n"
10698                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10699                 "OpDecorate %ssbo_src Binding 0\n"
10700                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10701                 "OpDecorate %ssbo_dst Binding 1\n"
10702         );
10703
10704         const StringTemplate testFun
10705         (
10706                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10707                 "    %param = OpFunctionParameter %v4f32\n"
10708                 "    %entry = OpLabel\n"
10709
10710                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10711                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10712                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10713                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10714                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10715                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10716                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10717                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10718
10719                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10720                 "  %val_src = OpLoad %${tt} %src\n"
10721                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10722                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10723                 "             OpStore %dst %val_dst\n"
10724                 "             OpBranch %merge\n"
10725
10726                 "    %merge = OpLabel\n"
10727                 "             OpReturnValue %param\n"
10728
10729                 "             OpFunctionEnd\n"
10730         );
10731
10732         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10733         {
10734                 const TestOp&           testOp                  = testOps[testOpsIdx];
10735                 const string            testName                = de::toLower(string(testOp.opCode));
10736                 const size_t            typeStride              = N * sizeof(deFloat16);
10737                 GraphicsResources       specResource;
10738                 map<string, string>     specs;
10739                 VulkanFeatures          features;
10740                 vector<string>          extensions;
10741                 map<string, string>     fragments;
10742                 SpecConstants           noSpecConstants;
10743                 PushConstants           noPushConstants;
10744                 GraphicsInterfaces      noInterfaces;
10745
10746                 specs["op_code"]                        = testOp.opCode;
10747                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10748                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10749                 specs["tt"]                                     = testType.typeName;
10750                 specs["tt_stride"]                      = de::toString(typeStride);
10751                 specs["type_decls"]                     = testType.typeDecls;
10752
10753                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10754                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10755                 fragments["decoration"]         = decoration.specialize(specs);
10756                 fragments["pre_main"]           = preMain.specialize(specs);
10757                 fragments["testfun"]            = testFun.specialize(specs);
10758
10759                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10760                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10761                 specResource.verifyIO = testOp.verifyFunc;
10762
10763                 extensions.push_back("VK_KHR_16bit_storage");
10764                 extensions.push_back("VK_KHR_shader_float16_int8");
10765
10766                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10767                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10768
10769                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10770                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10771         }
10772
10773         return testGroup.release();
10774 }
10775
10776 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10777 {
10778         if (inputs.size() != 2 || outputAllocs.size() != 1)
10779                 return false;
10780
10781         vector<deUint8> input1Bytes;
10782         vector<deUint8> input2Bytes;
10783
10784         inputs[0].getBytes(input1Bytes);
10785         inputs[1].getBytes(input2Bytes);
10786
10787         DE_ASSERT(input1Bytes.size() > 0);
10788         DE_ASSERT(input2Bytes.size() > 0);
10789         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10790
10791         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10792         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10793         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10794         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10795         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10796         std::string                             error;
10797
10798         DE_ASSERT(components == 2 || components == 4);
10799         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10800
10801         for (size_t idx = 0; idx < iterations; ++idx)
10802         {
10803                 const deUint32  componentNdx    = inputIndices[idx];
10804
10805                 DE_ASSERT(componentNdx < components);
10806
10807                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10808
10809                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10810                 {
10811                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10812
10813                         return false;
10814                 }
10815         }
10816
10817         return true;
10818 }
10819
10820 template<class SpecResource>
10821 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10822 {
10823         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10824
10825         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10826         const deUint32                                          numDataPoints           = 256;
10827         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10828         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10829
10830         struct TestType
10831         {
10832                 const deUint32  typeComponents;
10833                 const size_t    typeStride;
10834                 const char*             typeName;
10835                 const char*             typeDecls;
10836         };
10837
10838         const TestType  testTypes[]     =
10839         {
10840                 {
10841                         2,
10842                         2 * sizeof(deFloat16),
10843                         "v2f16",
10844                         "      %v2f16 = OpTypeVector %f16 2\n"
10845                 },
10846                 {
10847                         3,
10848                         4 * sizeof(deFloat16),
10849                         "v3f16",
10850                         "      %v3f16 = OpTypeVector %f16 3\n"
10851                 },
10852                 {
10853                         4,
10854                         4 * sizeof(deFloat16),
10855                         "v4f16",
10856                         "      %v4f16 = OpTypeVector %f16 4\n"
10857                 },
10858         };
10859
10860         const StringTemplate preMain
10861         (
10862                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10863                 "        %f16 = OpTypeFloat 16\n"
10864
10865                 "${type_decl}"
10866
10867                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10868                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10869                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10870                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10871
10872                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10873                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10874                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10875                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10876
10877                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10878                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10879                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10880                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10881
10882                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10883                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10884                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10885         );
10886
10887         const StringTemplate decoration
10888         (
10889                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10890                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10891                 "OpDecorate %SSBO_SRC BufferBlock\n"
10892                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10893                 "OpDecorate %ssbo_src Binding 0\n"
10894
10895                 "OpDecorate %ra_u32 ArrayStride 4\n"
10896                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10897                 "OpDecorate %SSBO_IDX BufferBlock\n"
10898                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10899                 "OpDecorate %ssbo_idx Binding 1\n"
10900
10901                 "OpDecorate %ra_f16 ArrayStride 2\n"
10902                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10903                 "OpDecorate %SSBO_DST BufferBlock\n"
10904                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10905                 "OpDecorate %ssbo_dst Binding 2\n"
10906         );
10907
10908         const StringTemplate testFun
10909         (
10910                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10911                 "    %param = OpFunctionParameter %v4f32\n"
10912                 "    %entry = OpLabel\n"
10913
10914                 "        %i = OpVariable %fp_i32 Function\n"
10915                 "             OpStore %i %c_i32_0\n"
10916
10917                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10918                 "             OpSelectionMerge %end_if None\n"
10919                 "             OpBranchConditional %will_run %run_test %end_if\n"
10920
10921                 " %run_test = OpLabel\n"
10922                 "             OpBranch %loop\n"
10923
10924                 "     %loop = OpLabel\n"
10925                 "    %i_cmp = OpLoad %i32 %i\n"
10926                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10927                 "             OpLoopMerge %merge %next None\n"
10928                 "             OpBranchConditional %lt %write %merge\n"
10929
10930                 "    %write = OpLabel\n"
10931                 "      %ndx = OpLoad %i32 %i\n"
10932
10933                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10934                 "  %val_src = OpLoad %${tt} %src\n"
10935
10936                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10937                 "  %val_idx = OpLoad %u32 %src_idx\n"
10938
10939                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10940                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10941
10942                 "             OpStore %dst %val_dst\n"
10943                 "             OpBranch %next\n"
10944
10945                 "     %next = OpLabel\n"
10946                 "    %i_cur = OpLoad %i32 %i\n"
10947                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10948                 "             OpStore %i %i_new\n"
10949                 "             OpBranch %loop\n"
10950
10951                 "    %merge = OpLabel\n"
10952                 "             OpBranch %end_if\n"
10953                 "   %end_if = OpLabel\n"
10954                 "             OpReturnValue %param\n"
10955
10956                 "             OpFunctionEnd\n"
10957         );
10958
10959         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10960         {
10961                 const TestType&         testType                = testTypes[testTypeIdx];
10962                 const string            testName                = testType.typeName;
10963                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10964                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10965                 SpecResource            specResource;
10966                 map<string, string>     specs;
10967                 VulkanFeatures          features;
10968                 vector<deUint32>        inputDataNdx;
10969                 map<string, string>     fragments;
10970                 vector<string>          extensions;
10971
10972                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10973                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10974
10975                 specs["num_data_points"]        = de::toString(iterations);
10976                 specs["tt"]                                     = testType.typeName;
10977                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10978                 specs["type_decl"]                      = testType.typeDecls;
10979
10980                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10981                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10982                 fragments["decoration"]         = decoration.specialize(specs);
10983                 fragments["pre_main"]           = preMain.specialize(specs);
10984                 fragments["testfun"]            = testFun.specialize(specs);
10985
10986                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10987                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10988                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10989                 specResource.verifyIO = compareFP16VectorExtractFunc;
10990
10991                 extensions.push_back("VK_KHR_16bit_storage");
10992                 extensions.push_back("VK_KHR_shader_float16_int8");
10993
10994                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10995                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10996
10997                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10998         }
10999
11000         return testGroup.release();
11001 }
11002
11003 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11004 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11005 {
11006         if (inputs.size() != 2 || outputAllocs.size() != 1)
11007                 return false;
11008
11009         vector<deUint8> input1Bytes;
11010         vector<deUint8> input2Bytes;
11011
11012         inputs[0].getBytes(input1Bytes);
11013         inputs[1].getBytes(input2Bytes);
11014
11015         DE_ASSERT(input1Bytes.size() > 0);
11016         DE_ASSERT(input2Bytes.size() > 0);
11017         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11018
11019         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11020         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11021         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11022         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11023         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11024         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11025         std::string                             error;
11026
11027         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11028         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11029
11030         for (size_t idx = 0; idx < iterations; ++idx)
11031         {
11032                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11033                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11034                 const deUint32          replacedCompNdx = inputIndices[idx];
11035
11036                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11037
11038                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11039                 {
11040                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11041
11042                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11043                         {
11044                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11045
11046                                 return false;
11047                         }
11048                 }
11049         }
11050
11051         return true;
11052 }
11053
11054 template<class SpecResource>
11055 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11056 {
11057         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11058
11059         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11060         const deUint32                                          replacement                     = 42;
11061         const deUint32                                          numDataPoints           = 256;
11062         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11063         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11064
11065         struct TestType
11066         {
11067                 const deUint32  typeComponents;
11068                 const size_t    typeStride;
11069                 const char*             typeName;
11070                 const char*             typeDecls;
11071                 VerifyIOFunc    verifyIOFunc;
11072         };
11073
11074         const TestType  testTypes[]     =
11075         {
11076                 {
11077                         2,
11078                         2 * sizeof(deFloat16),
11079                         "v2f16",
11080                         "      %v2f16 = OpTypeVector %f16 2\n",
11081                         compareFP16VectorInsertFunc<2, replacement>
11082                 },
11083                 {
11084                         3,
11085                         4 * sizeof(deFloat16),
11086                         "v3f16",
11087                         "      %v3f16 = OpTypeVector %f16 3\n",
11088                         compareFP16VectorInsertFunc<3, replacement>
11089                 },
11090                 {
11091                         4,
11092                         4 * sizeof(deFloat16),
11093                         "v4f16",
11094                         "      %v4f16 = OpTypeVector %f16 4\n",
11095                         compareFP16VectorInsertFunc<4, replacement>
11096                 },
11097         };
11098
11099         const StringTemplate preMain
11100         (
11101                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11102                 "        %f16 = OpTypeFloat 16\n"
11103                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11104
11105                 "${type_decl}"
11106
11107                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11108                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11109                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11110                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11111
11112                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11113                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11114                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11115                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11116
11117                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11118                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11119
11120                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11121                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11122                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11123         );
11124
11125         const StringTemplate decoration
11126         (
11127                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11128                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11129                 "OpDecorate %SSBO_SRC BufferBlock\n"
11130                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11131                 "OpDecorate %ssbo_src Binding 0\n"
11132
11133                 "OpDecorate %ra_u32 ArrayStride 4\n"
11134                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11135                 "OpDecorate %SSBO_IDX BufferBlock\n"
11136                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11137                 "OpDecorate %ssbo_idx Binding 1\n"
11138
11139                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11140                 "OpDecorate %SSBO_DST BufferBlock\n"
11141                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11142                 "OpDecorate %ssbo_dst Binding 2\n"
11143         );
11144
11145         const StringTemplate testFun
11146         (
11147                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11148                 "    %param = OpFunctionParameter %v4f32\n"
11149                 "    %entry = OpLabel\n"
11150
11151                 "        %i = OpVariable %fp_i32 Function\n"
11152                 "             OpStore %i %c_i32_0\n"
11153
11154                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11155                 "             OpSelectionMerge %end_if None\n"
11156                 "             OpBranchConditional %will_run %run_test %end_if\n"
11157
11158                 " %run_test = OpLabel\n"
11159                 "             OpBranch %loop\n"
11160
11161                 "     %loop = OpLabel\n"
11162                 "    %i_cmp = OpLoad %i32 %i\n"
11163                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11164                 "             OpLoopMerge %merge %next None\n"
11165                 "             OpBranchConditional %lt %write %merge\n"
11166
11167                 "    %write = OpLabel\n"
11168                 "      %ndx = OpLoad %i32 %i\n"
11169
11170                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11171                 "  %val_src = OpLoad %${tt} %src\n"
11172
11173                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11174                 "  %val_idx = OpLoad %u32 %src_idx\n"
11175
11176                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11177                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11178
11179                 "             OpStore %dst %val_dst\n"
11180                 "             OpBranch %next\n"
11181
11182                 "     %next = OpLabel\n"
11183                 "    %i_cur = OpLoad %i32 %i\n"
11184                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11185                 "             OpStore %i %i_new\n"
11186                 "             OpBranch %loop\n"
11187
11188                 "    %merge = OpLabel\n"
11189                 "             OpBranch %end_if\n"
11190                 "   %end_if = OpLabel\n"
11191                 "             OpReturnValue %param\n"
11192
11193                 "             OpFunctionEnd\n"
11194         );
11195
11196         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11197         {
11198                 const TestType&         testType                = testTypes[testTypeIdx];
11199                 const string            testName                = testType.typeName;
11200                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11201                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11202                 SpecResource            specResource;
11203                 map<string, string>     specs;
11204                 VulkanFeatures          features;
11205                 vector<deUint32>        inputDataNdx;
11206                 map<string, string>     fragments;
11207                 vector<string>          extensions;
11208
11209                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11210                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11211
11212                 specs["num_data_points"]        = de::toString(iterations);
11213                 specs["tt"]                                     = testType.typeName;
11214                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11215                 specs["type_decl"]                      = testType.typeDecls;
11216                 specs["replacement"]            = de::toString(replacement);
11217
11218                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11219                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11220                 fragments["decoration"]         = decoration.specialize(specs);
11221                 fragments["pre_main"]           = preMain.specialize(specs);
11222                 fragments["testfun"]            = testFun.specialize(specs);
11223
11224                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11225                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11226                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11227                 specResource.verifyIO = testType.verifyIOFunc;
11228
11229                 extensions.push_back("VK_KHR_16bit_storage");
11230                 extensions.push_back("VK_KHR_shader_float16_int8");
11231
11232                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11233                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11234
11235                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11236         }
11237
11238         return testGroup.release();
11239 }
11240
11241 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)
11242 {
11243         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11244         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11245         size_t                  comp;
11246
11247         switch (componentNdx)
11248         {
11249                 case 0: comp = compNdxLimited / compNdxCount; break;
11250                 case 1: comp = compNdxLimited % compNdxCount; break;
11251                 case 2: comp = 0; break;
11252                 case 3: comp = 1; break;
11253                 default: TCU_THROW(InternalError, "Impossible");
11254         }
11255
11256         if (comp >= vec1Len + vec2Len)
11257         {
11258                 validate = false;
11259                 return 0;
11260         }
11261         else
11262         {
11263                 validate = true;
11264                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11265         }
11266 }
11267
11268 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11269 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11270 {
11271         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11272         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11273         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11274
11275         if (inputs.size() != 2 || outputAllocs.size() != 1)
11276                 return false;
11277
11278         vector<deUint8> input1Bytes;
11279         vector<deUint8> input2Bytes;
11280
11281         inputs[0].getBytes(input1Bytes);
11282         inputs[1].getBytes(input2Bytes);
11283
11284         DE_ASSERT(input1Bytes.size() > 0);
11285         DE_ASSERT(input2Bytes.size() > 0);
11286         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11287
11288         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11289         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11290         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11291         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11292         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11293         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11294         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11295         std::string                             error;
11296
11297         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11298         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11299
11300         for (size_t idx = 0; idx < iterations; ++idx)
11301         {
11302                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11303                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11304                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11305
11306                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11307                 {
11308                         bool            validate        = true;
11309                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11310
11311                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11312                         {
11313                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11314
11315                                 return false;
11316                         }
11317                 }
11318         }
11319
11320         return true;
11321 }
11322
11323 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11324 {
11325         DE_ASSERT(dstComponentsCount <= 4);
11326         DE_ASSERT(src0ComponentsCount <= 4);
11327         DE_ASSERT(src1ComponentsCount <= 4);
11328         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11329
11330         switch (funcCode)
11331         {
11332                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11333                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11334                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11335                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11336                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11337                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11338                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11339                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11340                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11341                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11342                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11343                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11344                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11345                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11346                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11347                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11348                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11349                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11350                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11351                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11352                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11353                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11354                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11355                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11356                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11357                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11358                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11359                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11360         }
11361 }
11362
11363 template<class SpecResource>
11364 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11365 {
11366         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11367         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11368         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11369         de::Random                                                      rnd                                     (seed);
11370         const deUint32                                          numDataPoints           = 128;
11371         map<string, string>                                     fragments;
11372
11373         struct TestType
11374         {
11375                 const deUint32  typeComponents;
11376                 const char*             typeName;
11377         };
11378
11379         const TestType  testTypes[]     =
11380         {
11381                 {
11382                         2,
11383                         "v2f16",
11384                 },
11385                 {
11386                         3,
11387                         "v3f16",
11388                 },
11389                 {
11390                         4,
11391                         "v4f16",
11392                 },
11393         };
11394
11395         const StringTemplate preMain
11396         (
11397                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11398                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11399                 "          %f16 = OpTypeFloat 16\n"
11400                 "        %v2f16 = OpTypeVector %f16 2\n"
11401                 "        %v3f16 = OpTypeVector %f16 3\n"
11402                 "        %v4f16 = OpTypeVector %f16 4\n"
11403
11404                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11405                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11406                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11407                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11408
11409                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11410                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11411                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11412                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11413
11414                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11415                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11416                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11417                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11418
11419                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11420
11421                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11422                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11423                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11424         );
11425
11426         const StringTemplate decoration
11427         (
11428                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11429                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11430                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11431
11432                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11433                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11434
11435                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11436                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11437
11438                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11439                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11440
11441                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11442                 "OpDecorate %ssbo_src0 Binding 0\n"
11443                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11444                 "OpDecorate %ssbo_src1 Binding 1\n"
11445                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11446                 "OpDecorate %ssbo_dst Binding 2\n"
11447         );
11448
11449         const StringTemplate testFun
11450         (
11451                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11452                 "    %param = OpFunctionParameter %v4f32\n"
11453                 "    %entry = OpLabel\n"
11454
11455                 "        %i = OpVariable %fp_i32 Function\n"
11456                 "             OpStore %i %c_i32_0\n"
11457
11458                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11459                 "             OpSelectionMerge %end_if None\n"
11460                 "             OpBranchConditional %will_run %run_test %end_if\n"
11461
11462                 " %run_test = OpLabel\n"
11463                 "             OpBranch %loop\n"
11464
11465                 "     %loop = OpLabel\n"
11466                 "    %i_cmp = OpLoad %i32 %i\n"
11467                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11468                 "             OpLoopMerge %merge %next None\n"
11469                 "             OpBranchConditional %lt %write %merge\n"
11470
11471                 "    %write = OpLabel\n"
11472                 "      %ndx = OpLoad %i32 %i\n"
11473                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11474                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11475                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11476                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11477                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11478                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11479                 "             OpStore %dst %val_dst\n"
11480                 "             OpBranch %next\n"
11481
11482                 "     %next = OpLabel\n"
11483                 "    %i_cur = OpLoad %i32 %i\n"
11484                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11485                 "             OpStore %i %i_new\n"
11486                 "             OpBranch %loop\n"
11487
11488                 "    %merge = OpLabel\n"
11489                 "             OpBranch %end_if\n"
11490                 "   %end_if = OpLabel\n"
11491                 "             OpReturnValue %param\n"
11492                 "             OpFunctionEnd\n"
11493                 "\n"
11494
11495                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11496                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11497                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11498                 "%sw_paramn = OpFunctionParameter %i32\n"
11499                 " %sw_entry = OpLabel\n"
11500                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11501                 "             OpSelectionMerge %switch_e None\n"
11502                 "             OpSwitch %modulo %default ${case_list}\n"
11503                 "${case_bodies}"
11504                 "%default   = OpLabel\n"
11505                 "             OpUnreachable\n" // Unreachable default case for switch statement
11506                 "%switch_e  = OpLabel\n"
11507                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11508                 "             OpFunctionEnd\n"
11509         );
11510
11511         const StringTemplate testCaseBody
11512         (
11513                 "%case_${case_ndx}    = OpLabel\n"
11514                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11515                 "             OpReturnValue %val_dst_${case_ndx}\n"
11516         );
11517
11518         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11519         {
11520                 const TestType& dstType                 = testTypes[dstTypeIdx];
11521
11522                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11523                 {
11524                         const TestType& src0Type        = testTypes[comp0Idx];
11525
11526                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11527                         {
11528                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11529                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11530                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11531                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11532                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11533                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11534                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11535                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11536                                 deUint32                                caseCount                       = 0;
11537                                 SpecResource                    specResource;
11538                                 map<string, string>             specs;
11539                                 vector<string>                  extensions;
11540                                 VulkanFeatures                  features;
11541                                 string                                  caseBodies;
11542                                 string                                  caseList;
11543
11544                                 // Generate case
11545                                 {
11546                                         vector<string>  componentList;
11547
11548                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11549                                         {
11550                                                 deUint32                caseNo          = 0;
11551
11552                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11553                                                         componentList.push_back(de::toString(caseNo++));
11554                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11555                                                         componentList.push_back(de::toString(caseNo++));
11556                                                 componentList.push_back("0xFFFFFFFF");
11557                                         }
11558
11559                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11560                                         {
11561                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11562                                                 {
11563                                                         map<string, string>     specCase;
11564                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11565
11566                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11567                                                                 shuffle += " " + de::toString(compIdx - 2);
11568
11569                                                         specCase["case_ndx"]    = de::toString(caseCount);
11570                                                         specCase["shuffle"]             = shuffle;
11571                                                         specCase["tt_dst"]              = dstType.typeName;
11572
11573                                                         caseBodies      += testCaseBody.specialize(specCase);
11574                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11575
11576                                                         caseCount++;
11577                                                 }
11578                                         }
11579                                 }
11580
11581                                 specs["num_data_points"]        = de::toString(numDataPoints);
11582                                 specs["tt_dst"]                         = dstType.typeName;
11583                                 specs["tt_src0"]                        = src0Type.typeName;
11584                                 specs["tt_src1"]                        = src1Type.typeName;
11585                                 specs["case_bodies"]            = caseBodies;
11586                                 specs["case_list"]                      = caseList;
11587                                 specs["case_count"]                     = de::toString(caseCount);
11588
11589                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11590                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11591                                 fragments["decoration"]         = decoration.specialize(specs);
11592                                 fragments["pre_main"]           = preMain.specialize(specs);
11593                                 fragments["testfun"]            = testFun.specialize(specs);
11594
11595                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11596                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11597                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11598                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11599
11600                                 extensions.push_back("VK_KHR_16bit_storage");
11601                                 extensions.push_back("VK_KHR_shader_float16_int8");
11602
11603                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11604                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11605
11606                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11607                         }
11608                 }
11609         }
11610
11611         return testGroup.release();
11612 }
11613
11614 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11615 {
11616         if (inputs.size() != 1 || outputAllocs.size() != 1)
11617                 return false;
11618
11619         vector<deUint8> input1Bytes;
11620
11621         inputs[0].getBytes(input1Bytes);
11622
11623         DE_ASSERT(input1Bytes.size() > 0);
11624         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11625
11626         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11627         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11628         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11629         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11630         std::string                             error;
11631
11632         for (size_t idx = 0; idx < iterations; ++idx)
11633         {
11634                 if (input1AsFP16[idx] == exceptionValue)
11635                         continue;
11636
11637                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11638                 {
11639                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11640
11641                         return false;
11642                 }
11643         }
11644
11645         return true;
11646 }
11647
11648 template<class SpecResource>
11649 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11650 {
11651         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11652         const deUint32                                          numElements                             = 8;
11653         const string                                            testName                                = "struct";
11654         const deUint32                                          structItemsCount                = 88;
11655         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11656         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11657         const deUint32                                          fieldModifier                   = 2;
11658         const deUint32                                          fieldModifiedMulIndex   = 60;
11659         const deUint32                                          fieldModifiedAddIndex   = 66;
11660
11661         const StringTemplate preMain
11662         (
11663                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11664                 "          %f16 = OpTypeFloat 16\n"
11665                 "        %v2f16 = OpTypeVector %f16 2\n"
11666                 "        %v3f16 = OpTypeVector %f16 3\n"
11667                 "        %v4f16 = OpTypeVector %f16 4\n"
11668                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11669
11670                 "${consts}"
11671
11672                 "      %c_u32_5 = OpConstant %u32 5\n"
11673
11674                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11675                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11676                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11677                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11678                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11679                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11680                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11681                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11682
11683                 "        %up_st = OpTypePointer Uniform %st_test\n"
11684                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11685                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11686                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11687
11688                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11689         );
11690
11691         const StringTemplate decoration
11692         (
11693                 "OpDecorate %SSBO_st BufferBlock\n"
11694                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11695                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11696                 "OpDecorate %ssbo_dst Binding 1\n"
11697
11698                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11699
11700                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11701                 "OpMemberDecorate %struct16 0 Offset 0\n"
11702                 "OpMemberDecorate %struct16 1 Offset 4\n"
11703                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11704                 "OpDecorate %f16arr3 ArrayStride 2\n"
11705                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11706                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11707                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11708
11709                 "OpMemberDecorate %st_test 0 Offset 0\n"
11710                 "OpMemberDecorate %st_test 1 Offset 4\n"
11711                 "OpMemberDecorate %st_test 2 Offset 8\n"
11712                 "OpMemberDecorate %st_test 3 Offset 16\n"
11713                 "OpMemberDecorate %st_test 4 Offset 24\n"
11714                 "OpMemberDecorate %st_test 5 Offset 32\n"
11715                 "OpMemberDecorate %st_test 6 Offset 80\n"
11716                 "OpMemberDecorate %st_test 7 Offset 100\n"
11717                 "OpMemberDecorate %st_test 8 Offset 104\n"
11718                 "OpMemberDecorate %st_test 9 Offset 144\n"
11719         );
11720
11721         const StringTemplate testFun
11722         (
11723                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11724                 "     %param = OpFunctionParameter %v4f32\n"
11725                 "     %entry = OpLabel\n"
11726
11727                 "         %i = OpVariable %fp_i32 Function\n"
11728                 "              OpStore %i %c_i32_0\n"
11729
11730                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11731                 "              OpSelectionMerge %end_if None\n"
11732                 "              OpBranchConditional %will_run %run_test %end_if\n"
11733
11734                 "  %run_test = OpLabel\n"
11735                 "              OpBranch %loop\n"
11736
11737                 "      %loop = OpLabel\n"
11738                 "     %i_cmp = OpLoad %i32 %i\n"
11739                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11740                 "              OpLoopMerge %merge %next None\n"
11741                 "              OpBranchConditional %lt %write %merge\n"
11742
11743                 "     %write = OpLabel\n"
11744                 "       %ndx = OpLoad %i32 %i\n"
11745
11746                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11747                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11748                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11749
11750                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11751
11752                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11753                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11754                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11755                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11756                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11757
11758                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11759                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11760                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11761                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11762                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11763
11764                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11765                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11766                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11767                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11768                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11769
11770                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11771
11772                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11773                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11774                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11775                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11776                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11777                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11778
11779                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11780                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11781                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11782
11783                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11784                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11785                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11786                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11787                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11788                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11789                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11790                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11791
11792                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11793                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11794                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11795                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11796
11797                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11798                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11799                 "              OpStore %dst %st_val\n"
11800
11801                 "              OpBranch %next\n"
11802
11803                 "      %next = OpLabel\n"
11804                 "     %i_cur = OpLoad %i32 %i\n"
11805                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11806                 "              OpStore %i %i_new\n"
11807                 "              OpBranch %loop\n"
11808
11809                 "     %merge = OpLabel\n"
11810                 "              OpBranch %end_if\n"
11811                 "    %end_if = OpLabel\n"
11812                 "              OpReturnValue %param\n"
11813                 "              OpFunctionEnd\n"
11814         );
11815
11816         {
11817                 SpecResource            specResource;
11818                 map<string, string>     specs;
11819                 VulkanFeatures          features;
11820                 map<string, string>     fragments;
11821                 vector<string>          extensions;
11822                 vector<deFloat16>       expectedOutput;
11823                 string                          consts;
11824
11825                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11826                 {
11827                         vector<deFloat16>       expectedIterationOutput;
11828
11829                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11830                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11831
11832                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11833                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11834
11835                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11836                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11837
11838                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11839                 }
11840
11841                 for (deUint32 i = 0; i < structItemsCount; ++i)
11842                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11843
11844                 specs["num_elements"]           = de::toString(numElements);
11845                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11846                 specs["field_modifier"]         = de::toString(fieldModifier);
11847                 specs["consts"]                         = consts;
11848
11849                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11850                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11851                 fragments["decoration"]         = decoration.specialize(specs);
11852                 fragments["pre_main"]           = preMain.specialize(specs);
11853                 fragments["testfun"]            = testFun.specialize(specs);
11854
11855                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11856                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11857                 specResource.verifyIO = compareFP16CompositeFunc;
11858
11859                 extensions.push_back("VK_KHR_16bit_storage");
11860                 extensions.push_back("VK_KHR_shader_float16_int8");
11861
11862                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11863                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11864
11865                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11866         }
11867
11868         return testGroup.release();
11869 }
11870
11871 template<class SpecResource>
11872 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11873 {
11874         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11875         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11876         const string                                            opName                  (op);
11877         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11878                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11879                                                                                                                 : -1;
11880
11881         const StringTemplate preMain
11882         (
11883                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11884                 "         %f16 = OpTypeFloat 16\n"
11885                 "       %v2f16 = OpTypeVector %f16 2\n"
11886                 "       %v3f16 = OpTypeVector %f16 3\n"
11887                 "       %v4f16 = OpTypeVector %f16 4\n"
11888                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11889                 "     %c_u32_5 = OpConstant %u32 5\n"
11890
11891                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11892                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11893                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11894                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11895                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11896                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11897                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11898                 "%st_test      = OpTypeStruct %${field_type}\n"
11899
11900                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11901                 "       %up_st = OpTypePointer Uniform %st_test\n"
11902                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11903                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11904
11905                 "${op_premain_decls}"
11906
11907                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11908                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11909
11910                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11911                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11912         );
11913
11914         const StringTemplate decoration
11915         (
11916                 "OpDecorate %SSBO_src BufferBlock\n"
11917                 "OpDecorate %SSBO_dst BufferBlock\n"
11918                 "OpDecorate %ra_f16 ArrayStride 2\n"
11919                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11920                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11921                 "OpDecorate %ssbo_src Binding 0\n"
11922                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11923                 "OpDecorate %ssbo_dst Binding 1\n"
11924
11925                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11926                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11927
11928                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11929                 "OpMemberDecorate %struct16 0 Offset 0\n"
11930                 "OpMemberDecorate %struct16 1 Offset 4\n"
11931                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11932                 "OpDecorate %f16arr3 ArrayStride 2\n"
11933                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11934                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11935                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11936
11937                 "OpMemberDecorate %st_test 0 Offset 0\n"
11938         );
11939
11940         const StringTemplate testFun
11941         (
11942                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11943                 "     %param = OpFunctionParameter %v4f32\n"
11944                 "     %entry = OpLabel\n"
11945
11946                 "         %i = OpVariable %fp_i32 Function\n"
11947                 "              OpStore %i %c_i32_0\n"
11948
11949                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11950                 "              OpSelectionMerge %end_if None\n"
11951                 "              OpBranchConditional %will_run %run_test %end_if\n"
11952
11953                 "  %run_test = OpLabel\n"
11954                 "              OpBranch %loop\n"
11955
11956                 "      %loop = OpLabel\n"
11957                 "     %i_cmp = OpLoad %i32 %i\n"
11958                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11959                 "              OpLoopMerge %merge %next None\n"
11960                 "              OpBranchConditional %lt %write %merge\n"
11961
11962                 "     %write = OpLabel\n"
11963                 "       %ndx = OpLoad %i32 %i\n"
11964
11965                 "${op_sw_fun_call}"
11966
11967                 "              OpStore %dst %val_dst\n"
11968                 "              OpBranch %next\n"
11969
11970                 "      %next = OpLabel\n"
11971                 "     %i_cur = OpLoad %i32 %i\n"
11972                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11973                 "              OpStore %i %i_new\n"
11974                 "              OpBranch %loop\n"
11975
11976                 "     %merge = OpLabel\n"
11977                 "              OpBranch %end_if\n"
11978                 "    %end_if = OpLabel\n"
11979                 "              OpReturnValue %param\n"
11980                 "              OpFunctionEnd\n"
11981
11982                 "${op_sw_fun_header}"
11983                 " %sw_param = OpFunctionParameter %st_test\n"
11984                 "%sw_paramn = OpFunctionParameter %i32\n"
11985                 " %sw_entry = OpLabel\n"
11986                 "             OpSelectionMerge %switch_e None\n"
11987                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11988
11989                 "${case_bodies}"
11990
11991                 "%default   = OpLabel\n"
11992                 "             OpReturnValue ${op_case_default_value}\n"
11993                 "%switch_e  = OpLabel\n"
11994                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11995                 "             OpFunctionEnd\n"
11996         );
11997
11998         const StringTemplate testCaseBody
11999         (
12000                 "%case_${case_ndx}    = OpLabel\n"
12001                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12002                 "             OpReturnValue %val_ret_${case_ndx}\n"
12003         );
12004
12005         struct OpParts
12006         {
12007                 const char*     premainDecls;
12008                 const char*     swFunCall;
12009                 const char*     swFunHeader;
12010                 const char*     caseDefaultValue;
12011                 const char*     argsPartial;
12012         };
12013
12014         OpParts                                                         opPartsArray[]                  =
12015         {
12016                 // OpCompositeInsert
12017                 {
12018                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12019                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12020                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12021
12022                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12023                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12024                         "   %val_new = OpLoad %f16 %src\n"
12025                         "   %val_old = OpLoad %st_test %dst\n"
12026                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12027
12028                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12029                         "%sw_paramv = OpFunctionParameter %f16\n",
12030
12031                         "%sw_param",
12032
12033                         "%st_test %sw_paramv %sw_param",
12034                 },
12035                 // OpCompositeExtract
12036                 {
12037                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12038                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12039                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12040
12041                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12042                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12043                         "   %val_src = OpLoad %st_test %src\n"
12044                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12045
12046                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12047
12048                         "%c_f16_na",
12049
12050                         "%f16 %sw_param",
12051                 },
12052         };
12053
12054         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12055
12056         const char*     accessPathF16[] =
12057         {
12058                 "0",                    // %f16
12059                 DE_NULL,
12060         };
12061         const char*     accessPathV2F16[] =
12062         {
12063                 "0 0",                  // %v2f16
12064                 "0 1",
12065         };
12066         const char*     accessPathV3F16[] =
12067         {
12068                 "0 0",                  // %v3f16
12069                 "0 1",
12070                 "0 2",
12071                 DE_NULL,
12072         };
12073         const char*     accessPathV4F16[] =
12074         {
12075                 "0 0",                  // %v4f16"
12076                 "0 1",
12077                 "0 2",
12078                 "0 3",
12079         };
12080         const char*     accessPathF16Arr3[] =
12081         {
12082                 "0 0",                  // %f16arr3
12083                 "0 1",
12084                 "0 2",
12085                 DE_NULL,
12086         };
12087         const char*     accessPathStruct16Arr3[] =
12088         {
12089                 "0 0 0",                // %struct16arr3
12090                 DE_NULL,
12091                 "0 0 1 0 0",
12092                 "0 0 1 0 1",
12093                 "0 0 1 1 0",
12094                 "0 0 1 1 1",
12095                 "0 0 1 2 0",
12096                 "0 0 1 2 1",
12097                 "0 1 0",
12098                 DE_NULL,
12099                 "0 1 1 0 0",
12100                 "0 1 1 0 1",
12101                 "0 1 1 1 0",
12102                 "0 1 1 1 1",
12103                 "0 1 1 2 0",
12104                 "0 1 1 2 1",
12105                 "0 2 0",
12106                 DE_NULL,
12107                 "0 2 1 0 0",
12108                 "0 2 1 0 1",
12109                 "0 2 1 1 0",
12110                 "0 2 1 1 1",
12111                 "0 2 1 2 0",
12112                 "0 2 1 2 1",
12113         };
12114         const char*     accessPathV2F16Arr5[] =
12115         {
12116                 "0 0 0",                // %v2f16arr5
12117                 "0 0 1",
12118                 "0 1 0",
12119                 "0 1 1",
12120                 "0 2 0",
12121                 "0 2 1",
12122                 "0 3 0",
12123                 "0 3 1",
12124                 "0 4 0",
12125                 "0 4 1",
12126         };
12127         const char*     accessPathV3F16Arr5[] =
12128         {
12129                 "0 0 0",                // %v3f16arr5
12130                 "0 0 1",
12131                 "0 0 2",
12132                 DE_NULL,
12133                 "0 1 0",
12134                 "0 1 1",
12135                 "0 1 2",
12136                 DE_NULL,
12137                 "0 2 0",
12138                 "0 2 1",
12139                 "0 2 2",
12140                 DE_NULL,
12141                 "0 3 0",
12142                 "0 3 1",
12143                 "0 3 2",
12144                 DE_NULL,
12145                 "0 4 0",
12146                 "0 4 1",
12147                 "0 4 2",
12148                 DE_NULL,
12149         };
12150         const char*     accessPathV4F16Arr3[] =
12151         {
12152                 "0 0 0",                // %v4f16arr3
12153                 "0 0 1",
12154                 "0 0 2",
12155                 "0 0 3",
12156                 "0 1 0",
12157                 "0 1 1",
12158                 "0 1 2",
12159                 "0 1 3",
12160                 "0 2 0",
12161                 "0 2 1",
12162                 "0 2 2",
12163                 "0 2 3",
12164                 DE_NULL,
12165                 DE_NULL,
12166                 DE_NULL,
12167                 DE_NULL,
12168         };
12169
12170         struct TypeTestParameters
12171         {
12172                 const char*             name;
12173                 size_t                  accessPathLength;
12174                 const char**    accessPath;
12175         };
12176
12177         const TypeTestParameters typeTestParameters[] =
12178         {
12179                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12180                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12181                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12182                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12183                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12184                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12185                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12186                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12187                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12188         };
12189
12190         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12191         {
12192                 const OpParts           opParts                         = opPartsArray[opIndex];
12193                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12194                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12195                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12196                 SpecResource            specResource;
12197                 map<string, string>     specs;
12198                 VulkanFeatures          features;
12199                 map<string, string>     fragments;
12200                 vector<string>          extensions;
12201                 vector<deFloat16>       inputFP16;
12202                 vector<deFloat16>       dummyFP16Output;
12203
12204                 // Generate values for input
12205                 inputFP16.reserve(structItemsCount);
12206                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12207                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12208
12209                 dummyFP16Output.resize(structItemsCount);
12210
12211                 // Generate cases for OpSwitch
12212                 {
12213                         string  caseBodies;
12214                         string  caseList;
12215
12216                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12217                                 if (accessPath[caseNdx] != DE_NULL)
12218                                 {
12219                                         map<string, string>     specCase;
12220
12221                                         specCase["case_ndx"]            = de::toString(caseNdx);
12222                                         specCase["access_path"]         = accessPath[caseNdx];
12223                                         specCase["op_args_part"]        = opParts.argsPartial;
12224                                         specCase["op_name"]                     = opName;
12225
12226                                         caseBodies      += testCaseBody.specialize(specCase);
12227                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12228                                 }
12229
12230                         specs["case_bodies"]    = caseBodies;
12231                         specs["case_list"]              = caseList;
12232                 }
12233
12234                 specs["num_elements"]                   = de::toString(structItemsCount);
12235                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12236                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12237                 specs["op_premain_decls"]               = opParts.premainDecls;
12238                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12239                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12240                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12241
12242                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12243                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12244                 fragments["decoration"]         = decoration.specialize(specs);
12245                 fragments["pre_main"]           = preMain.specialize(specs);
12246                 fragments["testfun"]            = testFun.specialize(specs);
12247
12248                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12249                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12250                 specResource.verifyIO = compareFP16CompositeFunc;
12251
12252                 extensions.push_back("VK_KHR_16bit_storage");
12253                 extensions.push_back("VK_KHR_shader_float16_int8");
12254
12255                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12256                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12257
12258                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12259         }
12260
12261         return testGroup.release();
12262 }
12263
12264 struct fp16PerComponent
12265 {
12266         fp16PerComponent()
12267                 : flavor(0)
12268                 , floatFormat16 (-14, 15, 10, true)
12269                 , outCompCount(0)
12270                 , argCompCount(3, 0)
12271         {
12272         }
12273
12274         bool                    callOncePerComponent    ()                                                                      { return true; }
12275         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12276
12277         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12278         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12279         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12280
12281         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12282         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12283         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12284         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12285
12286         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12287         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12288
12289         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12290         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12291
12292 protected:
12293         size_t                          flavor;
12294         tcu::FloatFormat        floatFormat16;
12295         size_t                          outCompCount;
12296         vector<size_t>          argCompCount;
12297         vector<string>          flavorNames;
12298 };
12299
12300 struct fp16OpFNegate : public fp16PerComponent
12301 {
12302         template <class fp16type>
12303         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12304         {
12305                 const fp16type  x               (*in[0]);
12306                 const double    d               (x.asDouble());
12307                 const double    result  (0.0 - d);
12308
12309                 out[0] = fp16type(result).bits();
12310                 min[0] = getMin(result, getULPs(in));
12311                 max[0] = getMax(result, getULPs(in));
12312
12313                 return true;
12314         }
12315 };
12316
12317 struct fp16Round : public fp16PerComponent
12318 {
12319         fp16Round() : fp16PerComponent()
12320         {
12321                 flavorNames.push_back("Floor(x+0.5)");
12322                 flavorNames.push_back("Floor(x-0.5)");
12323                 flavorNames.push_back("RoundEven");
12324         }
12325
12326         template<class fp16type>
12327         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12328         {
12329                 const fp16type  x               (*in[0]);
12330                 const double    d               (x.asDouble());
12331                 double                  result  (0.0);
12332
12333                 switch (flavor)
12334                 {
12335                         case 0:         result = deRound(d);            break;
12336                         case 1:         result = deFloor(d - 0.5);      break;
12337                         case 2:         result = deRoundEven(d);        break;
12338                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12339                 }
12340
12341                 out[0] = fp16type(result).bits();
12342                 min[0] = getMin(result, getULPs(in));
12343                 max[0] = getMax(result, getULPs(in));
12344
12345                 return true;
12346         }
12347 };
12348
12349 struct fp16RoundEven : public fp16PerComponent
12350 {
12351         template<class fp16type>
12352         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12353         {
12354                 const fp16type  x               (*in[0]);
12355                 const double    d               (x.asDouble());
12356                 const double    result  (deRoundEven(d));
12357
12358                 out[0] = fp16type(result).bits();
12359                 min[0] = getMin(result, getULPs(in));
12360                 max[0] = getMax(result, getULPs(in));
12361
12362                 return true;
12363         }
12364 };
12365
12366 struct fp16Trunc : public fp16PerComponent
12367 {
12368         template<class fp16type>
12369         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12370         {
12371                 const fp16type  x               (*in[0]);
12372                 const double    d               (x.asDouble());
12373                 const double    result  (deTrunc(d));
12374
12375                 out[0] = fp16type(result).bits();
12376                 min[0] = getMin(result, getULPs(in));
12377                 max[0] = getMax(result, getULPs(in));
12378
12379                 return true;
12380         }
12381 };
12382
12383 struct fp16FAbs : public fp16PerComponent
12384 {
12385         template<class fp16type>
12386         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12387         {
12388                 const fp16type  x               (*in[0]);
12389                 const double    d               (x.asDouble());
12390                 const double    result  (deAbs(d));
12391
12392                 out[0] = fp16type(result).bits();
12393                 min[0] = getMin(result, getULPs(in));
12394                 max[0] = getMax(result, getULPs(in));
12395
12396                 return true;
12397         }
12398 };
12399
12400 struct fp16FSign : public fp16PerComponent
12401 {
12402         template<class fp16type>
12403         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12404         {
12405                 const fp16type  x               (*in[0]);
12406                 const double    d               (x.asDouble());
12407                 const double    result  (deSign(d));
12408
12409                 if (x.isNaN())
12410                         return false;
12411
12412                 out[0] = fp16type(result).bits();
12413                 min[0] = getMin(result, getULPs(in));
12414                 max[0] = getMax(result, getULPs(in));
12415
12416                 return true;
12417         }
12418 };
12419
12420 struct fp16Floor : public fp16PerComponent
12421 {
12422         template<class fp16type>
12423         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12424         {
12425                 const fp16type  x               (*in[0]);
12426                 const double    d               (x.asDouble());
12427                 const double    result  (deFloor(d));
12428
12429                 out[0] = fp16type(result).bits();
12430                 min[0] = getMin(result, getULPs(in));
12431                 max[0] = getMax(result, getULPs(in));
12432
12433                 return true;
12434         }
12435 };
12436
12437 struct fp16Ceil : public fp16PerComponent
12438 {
12439         template<class fp16type>
12440         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12441         {
12442                 const fp16type  x               (*in[0]);
12443                 const double    d               (x.asDouble());
12444                 const double    result  (deCeil(d));
12445
12446                 out[0] = fp16type(result).bits();
12447                 min[0] = getMin(result, getULPs(in));
12448                 max[0] = getMax(result, getULPs(in));
12449
12450                 return true;
12451         }
12452 };
12453
12454 struct fp16Fract : public fp16PerComponent
12455 {
12456         template<class fp16type>
12457         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12458         {
12459                 const fp16type  x               (*in[0]);
12460                 const double    d               (x.asDouble());
12461                 const double    result  (deFrac(d));
12462
12463                 out[0] = fp16type(result).bits();
12464                 min[0] = getMin(result, getULPs(in));
12465                 max[0] = getMax(result, getULPs(in));
12466
12467                 return true;
12468         }
12469 };
12470
12471 struct fp16Radians : public fp16PerComponent
12472 {
12473         virtual double getULPs (vector<const deFloat16*>& in)
12474         {
12475                 DE_UNREF(in);
12476
12477                 return 2.5;
12478         }
12479
12480         template<class fp16type>
12481         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12482         {
12483                 const fp16type  x               (*in[0]);
12484                 const float             d               (x.asFloat());
12485                 const float             result  (deFloatRadians(d));
12486
12487                 out[0] = fp16type(result).bits();
12488                 min[0] = getMin(result, getULPs(in));
12489                 max[0] = getMax(result, getULPs(in));
12490
12491                 return true;
12492         }
12493 };
12494
12495 struct fp16Degrees : public fp16PerComponent
12496 {
12497         virtual double getULPs (vector<const deFloat16*>& in)
12498         {
12499                 DE_UNREF(in);
12500
12501                 return 2.5;
12502         }
12503
12504         template<class fp16type>
12505         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12506         {
12507                 const fp16type  x               (*in[0]);
12508                 const float             d               (x.asFloat());
12509                 const float             result  (deFloatDegrees(d));
12510
12511                 out[0] = fp16type(result).bits();
12512                 min[0] = getMin(result, getULPs(in));
12513                 max[0] = getMax(result, getULPs(in));
12514
12515                 return true;
12516         }
12517 };
12518
12519 struct fp16Sin : public fp16PerComponent
12520 {
12521         template<class fp16type>
12522         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12523         {
12524                 const fp16type  x                       (*in[0]);
12525                 const double    d                       (x.asDouble());
12526                 const double    result          (deSin(d));
12527                 const double    unspecUlp       (16.0);
12528                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12529
12530                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12531                         return false;
12532
12533                 out[0] = fp16type(result).bits();
12534                 min[0] = result - err;
12535                 max[0] = result + err;
12536
12537                 return true;
12538         }
12539 };
12540
12541 struct fp16Cos : public fp16PerComponent
12542 {
12543         template<class fp16type>
12544         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12545         {
12546                 const fp16type  x                       (*in[0]);
12547                 const double    d                       (x.asDouble());
12548                 const double    result          (deCos(d));
12549                 const double    unspecUlp       (16.0);
12550                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12551
12552                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12553                         return false;
12554
12555                 out[0] = fp16type(result).bits();
12556                 min[0] = result - err;
12557                 max[0] = result + err;
12558
12559                 return true;
12560         }
12561 };
12562
12563 struct fp16Tan : 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  (deTan(d));
12571
12572                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12573                         return false;
12574
12575                 out[0] = fp16type(result).bits();
12576                 {
12577                         const double    err                     = deLdExp(1.0, -7);
12578                         const double    s1                      = deSin(d) + err;
12579                         const double    s2                      = deSin(d) - err;
12580                         const double    c1                      = deCos(d) + err;
12581                         const double    c2                      = deCos(d) - err;
12582                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12583                         double                  edgeLeft        = out[0];
12584                         double                  edgeRight       = out[0];
12585
12586                         if (deSign(c1 * c2) < 0.0)
12587                         {
12588                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12589                                 edgeRight       = +std::numeric_limits<double>::infinity();
12590                         }
12591                         else
12592                         {
12593                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12594                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12595                         }
12596
12597                         min[0] = edgeLeft;
12598                         max[0] = edgeRight;
12599                 }
12600
12601                 return true;
12602         }
12603 };
12604
12605 struct fp16Asin : public fp16PerComponent
12606 {
12607         template<class fp16type>
12608         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12609         {
12610                 const fp16type  x               (*in[0]);
12611                 const double    d               (x.asDouble());
12612                 const double    result  (deAsin(d));
12613                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12614
12615                 if (!x.isNaN() && deAbs(d) > 1.0)
12616                         return false;
12617
12618                 out[0] = fp16type(result).bits();
12619                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12620                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12621
12622                 return true;
12623         }
12624 };
12625
12626 struct fp16Acos : public fp16PerComponent
12627 {
12628         template<class fp16type>
12629         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12630         {
12631                 const fp16type  x               (*in[0]);
12632                 const double    d               (x.asDouble());
12633                 const double    result  (deAcos(d));
12634                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12635
12636                 if (!x.isNaN() && deAbs(d) > 1.0)
12637                         return false;
12638
12639                 out[0] = fp16type(result).bits();
12640                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12641                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12642
12643                 return true;
12644         }
12645 };
12646
12647 struct fp16Atan : public fp16PerComponent
12648 {
12649         virtual double getULPs(vector<const deFloat16*>& in)
12650         {
12651                 DE_UNREF(in);
12652
12653                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12654         }
12655
12656         template<class fp16type>
12657         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12658         {
12659                 const fp16type  x               (*in[0]);
12660                 const double    d               (x.asDouble());
12661                 const double    result  (deAtanOver(d));
12662
12663                 out[0] = fp16type(result).bits();
12664                 min[0] = getMin(result, getULPs(in));
12665                 max[0] = getMax(result, getULPs(in));
12666
12667                 return true;
12668         }
12669 };
12670
12671 struct fp16Sinh : public fp16PerComponent
12672 {
12673         fp16Sinh() : fp16PerComponent()
12674         {
12675                 flavorNames.push_back("Double");
12676                 flavorNames.push_back("ExpFP16");
12677         }
12678
12679         template<class fp16type>
12680         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12681         {
12682                 const fp16type  x               (*in[0]);
12683                 const double    d               (x.asDouble());
12684                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12685                 double                  result  (0.0);
12686                 double                  error   (0.0);
12687
12688                 if (getFlavor() == 0)
12689                 {
12690                         result  = deSinh(d);
12691                         error   = floatFormat16.ulp(deAbs(result), ulps);
12692                 }
12693                 else if (getFlavor() == 1)
12694                 {
12695                         const fp16type  epx     (deExp(d));
12696                         const fp16type  enx     (deExp(-d));
12697                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12698                         const fp16type  sx2     (esx.asDouble() / 2.0);
12699
12700                         result  = sx2.asDouble();
12701                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12702                 }
12703                 else
12704                 {
12705                         TCU_THROW(InternalError, "Unknown flavor");
12706                 }
12707
12708                 out[0] = fp16type(result).bits();
12709                 min[0] = result - error;
12710                 max[0] = result + error;
12711
12712                 return true;
12713         }
12714 };
12715
12716 struct fp16Cosh : public fp16PerComponent
12717 {
12718         fp16Cosh() : fp16PerComponent()
12719         {
12720                 flavorNames.push_back("Double");
12721                 flavorNames.push_back("ExpFP16");
12722         }
12723
12724         template<class fp16type>
12725         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12726         {
12727                 const fp16type  x               (*in[0]);
12728                 const double    d               (x.asDouble());
12729                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12730                 double                  result  (0.0);
12731
12732                 if (getFlavor() == 0)
12733                 {
12734                         result = deCosh(d);
12735                 }
12736                 else if (getFlavor() == 1)
12737                 {
12738                         const fp16type  epx     (deExp(d));
12739                         const fp16type  enx     (deExp(-d));
12740                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12741                         const fp16type  sx2     (esx.asDouble() / 2.0);
12742
12743                         result = sx2.asDouble();
12744                 }
12745                 else
12746                 {
12747                         TCU_THROW(InternalError, "Unknown flavor");
12748                 }
12749
12750                 out[0] = fp16type(result).bits();
12751                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12752                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12753
12754                 return true;
12755         }
12756 };
12757
12758 struct fp16Tanh : public fp16PerComponent
12759 {
12760         fp16Tanh() : fp16PerComponent()
12761         {
12762                 flavorNames.push_back("Tanh");
12763                 flavorNames.push_back("SinhCosh");
12764                 flavorNames.push_back("SinhCoshFP16");
12765                 flavorNames.push_back("PolyFP16");
12766         }
12767
12768         virtual double getULPs (vector<const deFloat16*>& in)
12769         {
12770                 const tcu::Float16      x       (*in[0]);
12771                 const double            d       (x.asDouble());
12772
12773                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12774         }
12775
12776         template<class fp16type>
12777         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12778         {
12779                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12780                 const fp16type  sx2     (esx.asDouble() / 2.0);
12781                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12782                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12783                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12784                 const double    rez     (tg.asDouble());
12785
12786                 return rez;
12787         }
12788
12789         template<class fp16type>
12790         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12791         {
12792                 const fp16type  x               (*in[0]);
12793                 const double    d               (x.asDouble());
12794                 double                  result  (0.0);
12795
12796                 if (getFlavor() == 0)
12797                 {
12798                         result  = deTanh(d);
12799                         min[0]  = getMin(result, getULPs(in));
12800                         max[0]  = getMax(result, getULPs(in));
12801                 }
12802                 else if (getFlavor() == 1)
12803                 {
12804                         result  = deSinh(d) / deCosh(d);
12805                         min[0]  = getMin(result, getULPs(in));
12806                         max[0]  = getMax(result, getULPs(in));
12807                 }
12808                 else if (getFlavor() == 2)
12809                 {
12810                         const fp16type  s       (deSinh(d));
12811                         const fp16type  c       (deCosh(d));
12812
12813                         result  = s.asDouble() / c.asDouble();
12814                         min[0]  = getMin(result, getULPs(in));
12815                         max[0]  = getMax(result, getULPs(in));
12816                 }
12817                 else if (getFlavor() == 3)
12818                 {
12819                         const double    ulps    (getULPs(in));
12820                         const double    epxm    (deExp( d));
12821                         const double    enxm    (deExp(-d));
12822                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12823                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12824                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12825                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12826                         const fp16type  epxm16  (epxm);
12827                         const fp16type  enxm16  (enxm);
12828                         vector<double>  tgs;
12829
12830                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12831                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12832                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12833                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12834                         {
12835                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12836
12837                                 tgs.push_back(tgh);
12838                         }
12839
12840                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12841                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12842                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12843                 }
12844                 else
12845                 {
12846                         TCU_THROW(InternalError, "Unknown flavor");
12847                 }
12848
12849                 out[0] = fp16type(result).bits();
12850
12851                 return true;
12852         }
12853 };
12854
12855 struct fp16Asinh : public fp16PerComponent
12856 {
12857         fp16Asinh() : fp16PerComponent()
12858         {
12859                 flavorNames.push_back("Double");
12860                 flavorNames.push_back("PolyFP16Wiki");
12861                 flavorNames.push_back("PolyFP16Abs");
12862         }
12863
12864         virtual double getULPs (vector<const deFloat16*>& in)
12865         {
12866                 DE_UNREF(in);
12867
12868                 return 256.0; // This is not a precision test. Value is not from spec
12869         }
12870
12871         template<class fp16type>
12872         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12873         {
12874                 const fp16type  x               (*in[0]);
12875                 const double    d               (x.asDouble());
12876                 double                  result  (0.0);
12877
12878                 if (getFlavor() == 0)
12879                 {
12880                         result = deAsinh(d);
12881                 }
12882                 else if (getFlavor() == 1)
12883                 {
12884                         const fp16type  x2              (d * d);
12885                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12886                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12887                         const fp16type  sxsq    (d + sq.asDouble());
12888                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12889
12890                         if (lsxsq.isInf())
12891                                 return false;
12892
12893                         result = lsxsq.asDouble();
12894                 }
12895                 else if (getFlavor() == 2)
12896                 {
12897                         const fp16type  x2              (d * d);
12898                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12899                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12900                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12901                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12902
12903                         result = deSign(d) * lsxsq.asDouble();
12904                 }
12905                 else
12906                 {
12907                         TCU_THROW(InternalError, "Unknown flavor");
12908                 }
12909
12910                 out[0] = fp16type(result).bits();
12911                 min[0] = getMin(result, getULPs(in));
12912                 max[0] = getMax(result, getULPs(in));
12913
12914                 return true;
12915         }
12916 };
12917
12918 struct fp16Acosh : public fp16PerComponent
12919 {
12920         fp16Acosh() : fp16PerComponent()
12921         {
12922                 flavorNames.push_back("Double");
12923                 flavorNames.push_back("PolyFP16");
12924         }
12925
12926         virtual double getULPs (vector<const deFloat16*>& in)
12927         {
12928                 DE_UNREF(in);
12929
12930                 return 16.0; // This is not a precision test. Value is not from spec
12931         }
12932
12933         template<class fp16type>
12934         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12935         {
12936                 const fp16type  x               (*in[0]);
12937                 const double    d               (x.asDouble());
12938                 double                  result  (0.0);
12939
12940                 if (!x.isNaN() && d < 1.0)
12941                         return false;
12942
12943                 if (getFlavor() == 0)
12944                 {
12945                         result = deAcosh(d);
12946                 }
12947                 else if (getFlavor() == 1)
12948                 {
12949                         const fp16type  x2              (d * d);
12950                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12951                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12952                         const fp16type  sxsq    (d + sq.asDouble());
12953                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12954
12955                         result = lsxsq.asDouble();
12956                 }
12957                 else
12958                 {
12959                         TCU_THROW(InternalError, "Unknown flavor");
12960                 }
12961
12962                 out[0] = fp16type(result).bits();
12963                 min[0] = getMin(result, getULPs(in));
12964                 max[0] = getMax(result, getULPs(in));
12965
12966                 return true;
12967         }
12968 };
12969
12970 struct fp16Atanh : public fp16PerComponent
12971 {
12972         fp16Atanh() : fp16PerComponent()
12973         {
12974                 flavorNames.push_back("Double");
12975                 flavorNames.push_back("PolyFP16");
12976         }
12977
12978         template<class fp16type>
12979         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12980         {
12981                 const fp16type  x               (*in[0]);
12982                 const double    d               (x.asDouble());
12983                 double                  result  (0.0);
12984
12985                 if (deAbs(d) >= 1.0)
12986                         return false;
12987
12988                 if (getFlavor() == 0)
12989                 {
12990                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12991
12992                         result = deAtanh(d);
12993                         min[0] = getMin(result, ulps);
12994                         max[0] = getMax(result, ulps);
12995                 }
12996                 else if (getFlavor() == 1)
12997                 {
12998                         const fp16type  x1a             (1.0 + d);
12999                         const fp16type  x1b             (1.0 - d);
13000                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13001                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13002                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13003                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13004
13005                         result = lx1d2.asDouble();
13006                         min[0] = result - error;
13007                         max[0] = result + error;
13008                 }
13009                 else
13010                 {
13011                         TCU_THROW(InternalError, "Unknown flavor");
13012                 }
13013
13014                 out[0] = fp16type(result).bits();
13015
13016                 return true;
13017         }
13018 };
13019
13020 struct fp16Exp : public fp16PerComponent
13021 {
13022         template<class fp16type>
13023         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13024         {
13025                 const fp16type  x               (*in[0]);
13026                 const double    d               (x.asDouble());
13027                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13028                 const double    result  (deExp(d));
13029
13030                 out[0] = fp16type(result).bits();
13031                 min[0] = getMin(result, ulps);
13032                 max[0] = getMax(result, ulps);
13033
13034                 return true;
13035         }
13036 };
13037
13038 struct fp16Log : public fp16PerComponent
13039 {
13040         template<class fp16type>
13041         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13042         {
13043                 const fp16type  x               (*in[0]);
13044                 const double    d               (x.asDouble());
13045                 const double    result  (deLog(d));
13046                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13047
13048                 if (d <= 0.0)
13049                         return false;
13050
13051                 out[0] = fp16type(result).bits();
13052                 min[0] = result - error;
13053                 max[0] = result + error;
13054
13055                 return true;
13056         }
13057 };
13058
13059 struct fp16Exp2 : public fp16PerComponent
13060 {
13061         template<class fp16type>
13062         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13063         {
13064                 const fp16type  x               (*in[0]);
13065                 const double    d               (x.asDouble());
13066                 const double    result  (deExp2(d));
13067                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13068
13069                 out[0] = fp16type(result).bits();
13070                 min[0] = getMin(result, ulps);
13071                 max[0] = getMax(result, ulps);
13072
13073                 return true;
13074         }
13075 };
13076
13077 struct fp16Log2 : public fp16PerComponent
13078 {
13079         template<class fp16type>
13080         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13081         {
13082                 const fp16type  x               (*in[0]);
13083                 const double    d               (x.asDouble());
13084                 const double    result  (deLog2(d));
13085                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13086
13087                 if (d <= 0.0)
13088                         return false;
13089
13090                 out[0] = fp16type(result).bits();
13091                 min[0] = result - error;
13092                 max[0] = result + error;
13093
13094                 return true;
13095         }
13096 };
13097
13098 struct fp16Sqrt : public fp16PerComponent
13099 {
13100         virtual double getULPs (vector<const deFloat16*>& in)
13101         {
13102                 DE_UNREF(in);
13103
13104                 return 6.0;
13105         }
13106
13107         template<class fp16type>
13108         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13109         {
13110                 const fp16type  x               (*in[0]);
13111                 const double    d               (x.asDouble());
13112                 const double    result  (deSqrt(d));
13113
13114                 if (!x.isNaN() && d < 0.0)
13115                         return false;
13116
13117                 out[0] = fp16type(result).bits();
13118                 min[0] = getMin(result, getULPs(in));
13119                 max[0] = getMax(result, getULPs(in));
13120
13121                 return true;
13122         }
13123 };
13124
13125 struct fp16InverseSqrt : public fp16PerComponent
13126 {
13127         virtual double getULPs (vector<const deFloat16*>& in)
13128         {
13129                 DE_UNREF(in);
13130
13131                 return 2.0;
13132         }
13133
13134         template<class fp16type>
13135         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13136         {
13137                 const fp16type  x               (*in[0]);
13138                 const double    d               (x.asDouble());
13139                 const double    result  (1.0/deSqrt(d));
13140
13141                 if (!x.isNaN() && d <= 0.0)
13142                         return false;
13143
13144                 out[0] = fp16type(result).bits();
13145                 min[0] = getMin(result, getULPs(in));
13146                 max[0] = getMax(result, getULPs(in));
13147
13148                 return true;
13149         }
13150 };
13151
13152 struct fp16ModfFrac : public fp16PerComponent
13153 {
13154         template<class fp16type>
13155         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13156         {
13157                 const fp16type  x               (*in[0]);
13158                 const double    d               (x.asDouble());
13159                 double                  i               (0.0);
13160                 const double    result  (deModf(d, &i));
13161
13162                 if (x.isInf() || x.isNaN())
13163                         return false;
13164
13165                 out[0] = fp16type(result).bits();
13166                 min[0] = getMin(result, getULPs(in));
13167                 max[0] = getMax(result, getULPs(in));
13168
13169                 return true;
13170         }
13171 };
13172
13173 struct fp16ModfInt : public fp16PerComponent
13174 {
13175         template<class fp16type>
13176         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13177         {
13178                 const fp16type  x               (*in[0]);
13179                 const double    d               (x.asDouble());
13180                 double                  i               (0.0);
13181                 const double    dummy   (deModf(d, &i));
13182                 const double    result  (i);
13183
13184                 DE_UNREF(dummy);
13185
13186                 if (x.isInf() || x.isNaN())
13187                         return false;
13188
13189                 out[0] = fp16type(result).bits();
13190                 min[0] = getMin(result, getULPs(in));
13191                 max[0] = getMax(result, getULPs(in));
13192
13193                 return true;
13194         }
13195 };
13196
13197 struct fp16FrexpS : public fp16PerComponent
13198 {
13199         template<class fp16type>
13200         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13201         {
13202                 const fp16type  x               (*in[0]);
13203                 const double    d               (x.asDouble());
13204                 int                             e               (0);
13205                 const double    result  (deFrExp(d, &e));
13206
13207                 if (x.isNaN() || x.isInf())
13208                         return false;
13209
13210                 out[0] = fp16type(result).bits();
13211                 min[0] = getMin(result, getULPs(in));
13212                 max[0] = getMax(result, getULPs(in));
13213
13214                 return true;
13215         }
13216 };
13217
13218 struct fp16FrexpE : public fp16PerComponent
13219 {
13220         template<class fp16type>
13221         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13222         {
13223                 const fp16type  x               (*in[0]);
13224                 const double    d               (x.asDouble());
13225                 int                             e               (0);
13226                 const double    dummy   (deFrExp(d, &e));
13227                 const double    result  (static_cast<double>(e));
13228
13229                 DE_UNREF(dummy);
13230
13231                 if (x.isNaN() || x.isInf())
13232                         return false;
13233
13234                 out[0] = fp16type(result).bits();
13235                 min[0] = getMin(result, getULPs(in));
13236                 max[0] = getMax(result, getULPs(in));
13237
13238                 return true;
13239         }
13240 };
13241
13242 struct fp16OpFAdd : public fp16PerComponent
13243 {
13244         template<class fp16type>
13245         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13246         {
13247                 const fp16type  x               (*in[0]);
13248                 const fp16type  y               (*in[1]);
13249                 const double    xd              (x.asDouble());
13250                 const double    yd              (y.asDouble());
13251                 const double    result  (xd + yd);
13252
13253                 out[0] = fp16type(result).bits();
13254                 min[0] = getMin(result, getULPs(in));
13255                 max[0] = getMax(result, getULPs(in));
13256
13257                 return true;
13258         }
13259 };
13260
13261 struct fp16OpFSub : public fp16PerComponent
13262 {
13263         template<class fp16type>
13264         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13265         {
13266                 const fp16type  x               (*in[0]);
13267                 const fp16type  y               (*in[1]);
13268                 const double    xd              (x.asDouble());
13269                 const double    yd              (y.asDouble());
13270                 const double    result  (xd - yd);
13271
13272                 out[0] = fp16type(result).bits();
13273                 min[0] = getMin(result, getULPs(in));
13274                 max[0] = getMax(result, getULPs(in));
13275
13276                 return true;
13277         }
13278 };
13279
13280 struct fp16OpFMul : public fp16PerComponent
13281 {
13282         template<class fp16type>
13283         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13284         {
13285                 const fp16type  x               (*in[0]);
13286                 const fp16type  y               (*in[1]);
13287                 const double    xd              (x.asDouble());
13288                 const double    yd              (y.asDouble());
13289                 const double    result  (xd * yd);
13290
13291                 out[0] = fp16type(result).bits();
13292                 min[0] = getMin(result, getULPs(in));
13293                 max[0] = getMax(result, getULPs(in));
13294
13295                 return true;
13296         }
13297 };
13298
13299 struct fp16OpFDiv : public fp16PerComponent
13300 {
13301         fp16OpFDiv() : fp16PerComponent()
13302         {
13303                 flavorNames.push_back("DirectDiv");
13304                 flavorNames.push_back("InverseDiv");
13305         }
13306
13307         template<class fp16type>
13308         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13309         {
13310                 const fp16type  x                       (*in[0]);
13311                 const fp16type  y                       (*in[1]);
13312                 const double    xd                      (x.asDouble());
13313                 const double    yd                      (y.asDouble());
13314                 const double    unspecUlp       (16.0);
13315                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13316                 double                  result          (0.0);
13317
13318                 if (y.isZero())
13319                         return false;
13320
13321                 if (getFlavor() == 0)
13322                 {
13323                         result = (xd / yd);
13324                 }
13325                 else if (getFlavor() == 1)
13326                 {
13327                         const double    invyd   (1.0 / yd);
13328                         const fp16type  invy    (invyd);
13329
13330                         result = (xd * invy.asDouble());
13331                 }
13332                 else
13333                 {
13334                         TCU_THROW(InternalError, "Unknown flavor");
13335                 }
13336
13337                 out[0] = fp16type(result).bits();
13338                 min[0] = getMin(result, ulpCnt);
13339                 max[0] = getMax(result, ulpCnt);
13340
13341                 return true;
13342         }
13343 };
13344
13345 struct fp16Atan2 : public fp16PerComponent
13346 {
13347         fp16Atan2() : fp16PerComponent()
13348         {
13349                 flavorNames.push_back("DoubleCalc");
13350                 flavorNames.push_back("DoubleCalc_PI");
13351         }
13352
13353         virtual double getULPs(vector<const deFloat16*>& in)
13354         {
13355                 DE_UNREF(in);
13356
13357                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13358         }
13359
13360         template<class fp16type>
13361         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13362         {
13363                 const fp16type  x               (*in[0]);
13364                 const fp16type  y               (*in[1]);
13365                 const double    xd              (x.asDouble());
13366                 const double    yd              (y.asDouble());
13367                 double                  result  (0.0);
13368
13369                 if (x.isZero() && y.isZero())
13370                         return false;
13371
13372                 if (getFlavor() == 0)
13373                 {
13374                         result  = deAtan2(xd, yd);
13375                 }
13376                 else if (getFlavor() == 1)
13377                 {
13378                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13379                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13380
13381                         result  = deAtan2(xd, yd);
13382
13383                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13384                                 result  = -result;
13385                 }
13386                 else
13387                 {
13388                         TCU_THROW(InternalError, "Unknown flavor");
13389                 }
13390
13391                 out[0] = fp16type(result).bits();
13392                 min[0] = getMin(result, getULPs(in));
13393                 max[0] = getMax(result, getULPs(in));
13394
13395                 return true;
13396         }
13397 };
13398
13399 struct fp16Pow : public fp16PerComponent
13400 {
13401         fp16Pow() : fp16PerComponent()
13402         {
13403                 flavorNames.push_back("Pow");
13404                 flavorNames.push_back("PowLog2");
13405                 flavorNames.push_back("PowLog2FP16");
13406         }
13407
13408         template<class fp16type>
13409         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13410         {
13411                 const fp16type  x               (*in[0]);
13412                 const fp16type  y               (*in[1]);
13413                 const double    xd              (x.asDouble());
13414                 const double    yd              (y.asDouble());
13415                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13416                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13417                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13418                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13419                 double                  result  (0.0);
13420
13421                 if (xd < 0.0)
13422                         return false;
13423
13424                 if (x.isZero() && yd <= 0.0)
13425                         return false;
13426
13427                 if (getFlavor() == 0)
13428                 {
13429                         result = dePow(xd, yd);
13430                 }
13431                 else if (getFlavor() == 1)
13432                 {
13433                         const double    l2d     (deLog2(xd));
13434                         const double    e2d     (deExp2(yd * l2d));
13435
13436                         result = e2d;
13437                 }
13438                 else if (getFlavor() == 2)
13439                 {
13440                         const double    l2d     (deLog2(xd));
13441                         const fp16type  l2      (l2d);
13442                         const double    e2d     (deExp2(yd * l2.asDouble()));
13443                         const fp16type  e2      (e2d);
13444
13445                         result = e2.asDouble();
13446                 }
13447                 else
13448                 {
13449                         TCU_THROW(InternalError, "Unknown flavor");
13450                 }
13451
13452                 out[0] = fp16type(result).bits();
13453                 min[0] = getMin(result, ulps);
13454                 max[0] = getMax(result, ulps);
13455
13456                 return true;
13457         }
13458 };
13459
13460 struct fp16FMin : public fp16PerComponent
13461 {
13462         template<class fp16type>
13463         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13464         {
13465                 const fp16type  x               (*in[0]);
13466                 const fp16type  y               (*in[1]);
13467                 const double    xd              (x.asDouble());
13468                 const double    yd              (y.asDouble());
13469                 const double    result  (deMin(xd, yd));
13470
13471                 if (x.isNaN() || y.isNaN())
13472                         return false;
13473
13474                 out[0] = fp16type(result).bits();
13475                 min[0] = getMin(result, getULPs(in));
13476                 max[0] = getMax(result, getULPs(in));
13477
13478                 return true;
13479         }
13480 };
13481
13482 struct fp16FMax : public fp16PerComponent
13483 {
13484         template<class fp16type>
13485         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13486         {
13487                 const fp16type  x               (*in[0]);
13488                 const fp16type  y               (*in[1]);
13489                 const double    xd              (x.asDouble());
13490                 const double    yd              (y.asDouble());
13491                 const double    result  (deMax(xd, yd));
13492
13493                 if (x.isNaN() || y.isNaN())
13494                         return false;
13495
13496                 out[0] = fp16type(result).bits();
13497                 min[0] = getMin(result, getULPs(in));
13498                 max[0] = getMax(result, getULPs(in));
13499
13500                 return true;
13501         }
13502 };
13503
13504 struct fp16Step : public fp16PerComponent
13505 {
13506         template<class fp16type>
13507         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13508         {
13509                 const fp16type  edge    (*in[0]);
13510                 const fp16type  x               (*in[1]);
13511                 const double    edged   (edge.asDouble());
13512                 const double    xd              (x.asDouble());
13513                 const double    result  (deStep(edged, xd));
13514
13515                 out[0] = fp16type(result).bits();
13516                 min[0] = getMin(result, getULPs(in));
13517                 max[0] = getMax(result, getULPs(in));
13518
13519                 return true;
13520         }
13521 };
13522
13523 struct fp16Ldexp : public fp16PerComponent
13524 {
13525         template<class fp16type>
13526         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13527         {
13528                 const fp16type  x               (*in[0]);
13529                 const fp16type  y               (*in[1]);
13530                 const double    xd              (x.asDouble());
13531                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13532                 const double    result  (deLdExp(xd, yd));
13533
13534                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13535                         return false;
13536
13537                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13538                 if (fp16type(result).isInf())
13539                         return false;
13540
13541                 out[0] = fp16type(result).bits();
13542                 min[0] = getMin(result, getULPs(in));
13543                 max[0] = getMax(result, getULPs(in));
13544
13545                 return true;
13546         }
13547 };
13548
13549 struct fp16FClamp : public fp16PerComponent
13550 {
13551         template<class fp16type>
13552         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13553         {
13554                 const fp16type  x               (*in[0]);
13555                 const fp16type  minVal  (*in[1]);
13556                 const fp16type  maxVal  (*in[2]);
13557                 const double    xd              (x.asDouble());
13558                 const double    minVald (minVal.asDouble());
13559                 const double    maxVald (maxVal.asDouble());
13560                 const double    result  (deClamp(xd, minVald, maxVald));
13561
13562                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13563                         return false;
13564
13565                 out[0] = fp16type(result).bits();
13566                 min[0] = getMin(result, getULPs(in));
13567                 max[0] = getMax(result, getULPs(in));
13568
13569                 return true;
13570         }
13571 };
13572
13573 struct fp16FMix : public fp16PerComponent
13574 {
13575         fp16FMix() : fp16PerComponent()
13576         {
13577                 flavorNames.push_back("DoubleCalc");
13578                 flavorNames.push_back("EmulatingFP16");
13579                 flavorNames.push_back("EmulatingFP16YminusX");
13580         }
13581
13582         template<class fp16type>
13583         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13584         {
13585                 const fp16type  x               (*in[0]);
13586                 const fp16type  y               (*in[1]);
13587                 const fp16type  a               (*in[2]);
13588                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13589                 double                  result  (0.0);
13590
13591                 if (getFlavor() == 0)
13592                 {
13593                         const double    xd              (x.asDouble());
13594                         const double    yd              (y.asDouble());
13595                         const double    ad              (a.asDouble());
13596                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13597                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13598                         const double    eps             (xeps + yeps);
13599
13600                         result = deMix(xd, yd, ad);
13601                         min[0] = result - eps;
13602                         max[0] = result + eps;
13603                 }
13604                 else if (getFlavor() == 1)
13605                 {
13606                         const double    xd              (x.asDouble());
13607                         const double    yd              (y.asDouble());
13608                         const double    ad              (a.asDouble());
13609                         const fp16type  am              (1.0 - ad);
13610                         const double    amd             (am.asDouble());
13611                         const fp16type  xam             (xd * amd);
13612                         const double    xamd    (xam.asDouble());
13613                         const fp16type  ya              (yd * ad);
13614                         const double    yad             (ya.asDouble());
13615                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13616                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13617                         const double    eps             (xeps + yeps);
13618
13619                         result = xamd + yad;
13620                         min[0] = result - eps;
13621                         max[0] = result + eps;
13622                 }
13623                 else if (getFlavor() == 2)
13624                 {
13625                         const double    xd              (x.asDouble());
13626                         const double    yd              (y.asDouble());
13627                         const double    ad              (a.asDouble());
13628                         const fp16type  ymx             (yd - xd);
13629                         const double    ymxd    (ymx.asDouble());
13630                         const fp16type  ymxa    (ymxd * ad);
13631                         const double    ymxad   (ymxa.asDouble());
13632                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13633                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13634                         const double    eps             (xeps + yeps);
13635
13636                         result = xd + ymxad;
13637                         min[0] = result - eps;
13638                         max[0] = result + eps;
13639                 }
13640                 else
13641                 {
13642                         TCU_THROW(InternalError, "Unknown flavor");
13643                 }
13644
13645                 out[0] = fp16type(result).bits();
13646
13647                 return true;
13648         }
13649 };
13650
13651 struct fp16SmoothStep : public fp16PerComponent
13652 {
13653         fp16SmoothStep() : fp16PerComponent()
13654         {
13655                 flavorNames.push_back("FloatCalc");
13656                 flavorNames.push_back("EmulatingFP16");
13657                 flavorNames.push_back("EmulatingFP16WClamp");
13658         }
13659
13660         virtual double getULPs(vector<const deFloat16*>& in)
13661         {
13662                 DE_UNREF(in);
13663
13664                 return 4.0; // This is not a precision test. Value is not from spec
13665         }
13666
13667         template<class fp16type>
13668         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13669         {
13670                 const fp16type  edge0   (*in[0]);
13671                 const fp16type  edge1   (*in[1]);
13672                 const fp16type  x               (*in[2]);
13673                 double                  result  (0.0);
13674
13675                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13676                         return false;
13677
13678                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13679                         return false;
13680
13681                 if (getFlavor() == 0)
13682                 {
13683                         const float     edge0d  (edge0.asFloat());
13684                         const float     edge1d  (edge1.asFloat());
13685                         const float     xd              (x.asFloat());
13686                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13687
13688                         result = sstep;
13689                 }
13690                 else if (getFlavor() == 1)
13691                 {
13692                         const double    edge0d  (edge0.asDouble());
13693                         const double    edge1d  (edge1.asDouble());
13694                         const double    xd              (x.asDouble());
13695
13696                         if (xd <= edge0d)
13697                                 result = 0.0;
13698                         else if (xd >= edge1d)
13699                                 result = 1.0;
13700                         else
13701                         {
13702                                 const fp16type  a       (xd - edge0d);
13703                                 const fp16type  b       (edge1d - edge0d);
13704                                 const fp16type  t       (a.asDouble() / b.asDouble());
13705                                 const fp16type  t2      (2.0 * t.asDouble());
13706                                 const fp16type  t3      (3.0 - t2.asDouble());
13707                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13708                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13709
13710                                 result = t5.asDouble();
13711                         }
13712                 }
13713                 else if (getFlavor() == 2)
13714                 {
13715                         const double    edge0d  (edge0.asDouble());
13716                         const double    edge1d  (edge1.asDouble());
13717                         const double    xd              (x.asDouble());
13718                         const fp16type  a       (xd - edge0d);
13719                         const fp16type  b       (edge1d - edge0d);
13720                         const fp16type  bi      (1.0 / b.asDouble());
13721                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13722                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13723                         const fp16type  t       (tc);
13724                         const fp16type  t2      (2.0 * t.asDouble());
13725                         const fp16type  t3      (3.0 - t2.asDouble());
13726                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13727                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13728
13729                         result = t5.asDouble();
13730                 }
13731                 else
13732                 {
13733                         TCU_THROW(InternalError, "Unknown flavor");
13734                 }
13735
13736                 out[0] = fp16type(result).bits();
13737                 min[0] = getMin(result, getULPs(in));
13738                 max[0] = getMax(result, getULPs(in));
13739
13740                 return true;
13741         }
13742 };
13743
13744 struct fp16Fma : public fp16PerComponent
13745 {
13746         fp16Fma()
13747         {
13748                 flavorNames.push_back("DoubleCalc");
13749                 flavorNames.push_back("EmulatingFP16");
13750         }
13751
13752         virtual double getULPs(vector<const deFloat16*>& in)
13753         {
13754                 DE_UNREF(in);
13755
13756                 return 16.0;
13757         }
13758
13759         template<class fp16type>
13760         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13761         {
13762                 DE_ASSERT(in.size() == 3);
13763                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13764                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13765                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13766                 DE_ASSERT(getOutCompCount() > 0);
13767
13768                 const fp16type  a               (*in[0]);
13769                 const fp16type  b               (*in[1]);
13770                 const fp16type  c               (*in[2]);
13771                 double                  result  (0.0);
13772
13773                 if (getFlavor() == 0)
13774                 {
13775                         const double    ad      (a.asDouble());
13776                         const double    bd      (b.asDouble());
13777                         const double    cd      (c.asDouble());
13778
13779                         result  = deMadd(ad, bd, cd);
13780                 }
13781                 else if (getFlavor() == 1)
13782                 {
13783                         const double    ad      (a.asDouble());
13784                         const double    bd      (b.asDouble());
13785                         const double    cd      (c.asDouble());
13786                         const fp16type  ab      (ad * bd);
13787                         const fp16type  r       (ab.asDouble() + cd);
13788
13789                         result  = r.asDouble();
13790                 }
13791                 else
13792                 {
13793                         TCU_THROW(InternalError, "Unknown flavor");
13794                 }
13795
13796                 out[0] = fp16type(result).bits();
13797                 min[0] = getMin(result, getULPs(in));
13798                 max[0] = getMax(result, getULPs(in));
13799
13800                 return true;
13801         }
13802 };
13803
13804
13805 struct fp16AllComponents : public fp16PerComponent
13806 {
13807         bool            callOncePerComponent    ()      { return false; }
13808 };
13809
13810 struct fp16Length : public fp16AllComponents
13811 {
13812         fp16Length() : fp16AllComponents()
13813         {
13814                 flavorNames.push_back("EmulatingFP16");
13815                 flavorNames.push_back("DoubleCalc");
13816         }
13817
13818         virtual double getULPs(vector<const deFloat16*>& in)
13819         {
13820                 DE_UNREF(in);
13821
13822                 return 4.0;
13823         }
13824
13825         template<class fp16type>
13826         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13827         {
13828                 DE_ASSERT(getOutCompCount() == 1);
13829                 DE_ASSERT(in.size() == 1);
13830
13831                 double  result  (0.0);
13832
13833                 if (getFlavor() == 0)
13834                 {
13835                         fp16type        r       (0.0);
13836
13837                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13838                         {
13839                                 const fp16type  x       (in[0][componentNdx]);
13840                                 const fp16type  q       (x.asDouble() * x.asDouble());
13841
13842                                 r = fp16type(r.asDouble() + q.asDouble());
13843                         }
13844
13845                         result = deSqrt(r.asDouble());
13846
13847                         out[0] = fp16type(result).bits();
13848                 }
13849                 else if (getFlavor() == 1)
13850                 {
13851                         double  r       (0.0);
13852
13853                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13854                         {
13855                                 const fp16type  x       (in[0][componentNdx]);
13856                                 const double    q       (x.asDouble() * x.asDouble());
13857
13858                                 r += q;
13859                         }
13860
13861                         result = deSqrt(r);
13862
13863                         out[0] = fp16type(result).bits();
13864                 }
13865                 else
13866                 {
13867                         TCU_THROW(InternalError, "Unknown flavor");
13868                 }
13869
13870                 min[0] = getMin(result, getULPs(in));
13871                 max[0] = getMax(result, getULPs(in));
13872
13873                 return true;
13874         }
13875 };
13876
13877 struct fp16Distance : public fp16AllComponents
13878 {
13879         fp16Distance() : fp16AllComponents()
13880         {
13881                 flavorNames.push_back("EmulatingFP16");
13882                 flavorNames.push_back("DoubleCalc");
13883         }
13884
13885         virtual double getULPs(vector<const deFloat16*>& in)
13886         {
13887                 DE_UNREF(in);
13888
13889                 return 4.0;
13890         }
13891
13892         template<class fp16type>
13893         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13894         {
13895                 DE_ASSERT(getOutCompCount() == 1);
13896                 DE_ASSERT(in.size() == 2);
13897                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13898
13899                 double  result  (0.0);
13900
13901                 if (getFlavor() == 0)
13902                 {
13903                         fp16type        r       (0.0);
13904
13905                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13906                         {
13907                                 const fp16type  x       (in[0][componentNdx]);
13908                                 const fp16type  y       (in[1][componentNdx]);
13909                                 const fp16type  d       (x.asDouble() - y.asDouble());
13910                                 const fp16type  q       (d.asDouble() * d.asDouble());
13911
13912                                 r = fp16type(r.asDouble() + q.asDouble());
13913                         }
13914
13915                         result = deSqrt(r.asDouble());
13916                 }
13917                 else if (getFlavor() == 1)
13918                 {
13919                         double  r       (0.0);
13920
13921                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13922                         {
13923                                 const fp16type  x       (in[0][componentNdx]);
13924                                 const fp16type  y       (in[1][componentNdx]);
13925                                 const double    d       (x.asDouble() - y.asDouble());
13926                                 const double    q       (d * d);
13927
13928                                 r += q;
13929                         }
13930
13931                         result = deSqrt(r);
13932                 }
13933                 else
13934                 {
13935                         TCU_THROW(InternalError, "Unknown flavor");
13936                 }
13937
13938                 out[0] = fp16type(result).bits();
13939                 min[0] = getMin(result, getULPs(in));
13940                 max[0] = getMax(result, getULPs(in));
13941
13942                 return true;
13943         }
13944 };
13945
13946 struct fp16Cross : public fp16AllComponents
13947 {
13948         fp16Cross() : fp16AllComponents()
13949         {
13950                 flavorNames.push_back("EmulatingFP16");
13951                 flavorNames.push_back("DoubleCalc");
13952         }
13953
13954         virtual double getULPs(vector<const deFloat16*>& in)
13955         {
13956                 DE_UNREF(in);
13957
13958                 return 4.0;
13959         }
13960
13961         template<class fp16type>
13962         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13963         {
13964                 DE_ASSERT(getOutCompCount() == 3);
13965                 DE_ASSERT(in.size() == 2);
13966                 DE_ASSERT(getArgCompCount(0) == 3);
13967                 DE_ASSERT(getArgCompCount(1) == 3);
13968
13969                 if (getFlavor() == 0)
13970                 {
13971                         const fp16type  x0              (in[0][0]);
13972                         const fp16type  x1              (in[0][1]);
13973                         const fp16type  x2              (in[0][2]);
13974                         const fp16type  y0              (in[1][0]);
13975                         const fp16type  y1              (in[1][1]);
13976                         const fp16type  y2              (in[1][2]);
13977                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13978                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13979                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13980                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13981                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13982                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13983
13984                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13985                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13986                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13987                 }
13988                 else if (getFlavor() == 1)
13989                 {
13990                         const fp16type  x0              (in[0][0]);
13991                         const fp16type  x1              (in[0][1]);
13992                         const fp16type  x2              (in[0][2]);
13993                         const fp16type  y0              (in[1][0]);
13994                         const fp16type  y1              (in[1][1]);
13995                         const fp16type  y2              (in[1][2]);
13996                         const double    x1y2    (x1.asDouble() * y2.asDouble());
13997                         const double    y1x2    (y1.asDouble() * x2.asDouble());
13998                         const double    x2y0    (x2.asDouble() * y0.asDouble());
13999                         const double    y2x0    (y2.asDouble() * x0.asDouble());
14000                         const double    x0y1    (x0.asDouble() * y1.asDouble());
14001                         const double    y0x1    (y0.asDouble() * x1.asDouble());
14002
14003                         out[0] = fp16type(x1y2 - y1x2).bits();
14004                         out[1] = fp16type(x2y0 - y2x0).bits();
14005                         out[2] = fp16type(x0y1 - y0x1).bits();
14006                 }
14007                 else
14008                 {
14009                         TCU_THROW(InternalError, "Unknown flavor");
14010                 }
14011
14012                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14013                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14014                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14015                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14016
14017                 return true;
14018         }
14019 };
14020
14021 struct fp16Normalize : public fp16AllComponents
14022 {
14023         fp16Normalize() : fp16AllComponents()
14024         {
14025                 flavorNames.push_back("EmulatingFP16");
14026                 flavorNames.push_back("DoubleCalc");
14027
14028                 // flavorNames will be extended later
14029         }
14030
14031         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14032         {
14033                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14034
14035                 if (argNo == 0 && argCompCount[argNo] == 0)
14036                 {
14037                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14038                         std::vector<int>        indices;
14039
14040                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14041                                 indices.push_back(static_cast<int>(componentNdx));
14042
14043                         m_permutations.reserve(maxPermutationsCount);
14044
14045                         permutationsFlavorStart = flavorNames.size();
14046
14047                         do
14048                         {
14049                                 tcu::UVec4      permutation;
14050                                 std::string     name            = "Permutted_";
14051
14052                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14053                                 {
14054                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14055                                         name += de::toString(indices[componentNdx]);
14056                                 }
14057
14058                                 m_permutations.push_back(permutation);
14059                                 flavorNames.push_back(name);
14060
14061                         } while(std::next_permutation(indices.begin(), indices.end()));
14062
14063                         permutationsFlavorEnd = flavorNames.size();
14064                 }
14065
14066                 fp16AllComponents::setArgCompCount(argNo, compCount);
14067         }
14068         virtual double getULPs(vector<const deFloat16*>& in)
14069         {
14070                 DE_UNREF(in);
14071
14072                 return 8.0;
14073         }
14074
14075         template<class fp16type>
14076         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14077         {
14078                 DE_ASSERT(in.size() == 1);
14079                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14080
14081                 if (getFlavor() == 0)
14082                 {
14083                         fp16type        r(0.0);
14084
14085                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14086                         {
14087                                 const fp16type  x       (in[0][componentNdx]);
14088                                 const fp16type  q       (x.asDouble() * x.asDouble());
14089
14090                                 r = fp16type(r.asDouble() + q.asDouble());
14091                         }
14092
14093                         r = fp16type(deSqrt(r.asDouble()));
14094
14095                         if (r.isZero())
14096                                 return false;
14097
14098                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14099                         {
14100                                 const fp16type  x       (in[0][componentNdx]);
14101
14102                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14103                         }
14104                 }
14105                 else if (getFlavor() == 1)
14106                 {
14107                         double  r(0.0);
14108
14109                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14110                         {
14111                                 const fp16type  x       (in[0][componentNdx]);
14112                                 const double    q       (x.asDouble() * x.asDouble());
14113
14114                                 r += q;
14115                         }
14116
14117                         r = deSqrt(r);
14118
14119                         if (r == 0)
14120                                 return false;
14121
14122                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14123                         {
14124                                 const fp16type  x       (in[0][componentNdx]);
14125
14126                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14127                         }
14128                 }
14129                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14130                 {
14131                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14132                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14133                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14134                         fp16type                        r                               (0.0);
14135
14136                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14137                         {
14138                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14139                                 const fp16type  x                               (in[0][componentNdx]);
14140                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14141
14142                                 r = fp16type(r.asDouble() + q.asDouble());
14143                         }
14144
14145                         r = fp16type(deSqrt(r.asDouble()));
14146
14147                         if (r.isZero())
14148                                 return false;
14149
14150                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14151                         {
14152                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14153                                 const fp16type  x                               (in[0][componentNdx]);
14154
14155                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14156                         }
14157                 }
14158                 else
14159                 {
14160                         TCU_THROW(InternalError, "Unknown flavor");
14161                 }
14162
14163                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14164                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14165                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14166                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14167
14168                 return true;
14169         }
14170
14171 private:
14172         std::vector<tcu::UVec4> m_permutations;
14173         size_t                                  permutationsFlavorStart;
14174         size_t                                  permutationsFlavorEnd;
14175 };
14176
14177 struct fp16FaceForward : public fp16AllComponents
14178 {
14179         virtual double getULPs(vector<const deFloat16*>& in)
14180         {
14181                 DE_UNREF(in);
14182
14183                 return 4.0;
14184         }
14185
14186         template<class fp16type>
14187         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14188         {
14189                 DE_ASSERT(in.size() == 3);
14190                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14191                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14192                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14193
14194                 fp16type        dp(0.0);
14195
14196                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14197                 {
14198                         const fp16type  x       (in[1][componentNdx]);
14199                         const fp16type  y       (in[2][componentNdx]);
14200                         const double    xd      (x.asDouble());
14201                         const double    yd      (y.asDouble());
14202                         const fp16type  q       (xd * yd);
14203
14204                         dp = fp16type(dp.asDouble() + q.asDouble());
14205                 }
14206
14207                 if (dp.isNaN() || dp.isZero())
14208                         return false;
14209
14210                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14211                 {
14212                         const fp16type  n       (in[0][componentNdx]);
14213
14214                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14215                 }
14216
14217                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14218                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14219                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14220                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14221
14222                 return true;
14223         }
14224 };
14225
14226 struct fp16Reflect : public fp16AllComponents
14227 {
14228         fp16Reflect() : fp16AllComponents()
14229         {
14230                 flavorNames.push_back("EmulatingFP16");
14231                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14232                 flavorNames.push_back("FloatCalc");
14233                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14234                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14235                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14236         }
14237
14238         virtual double getULPs(vector<const deFloat16*>& in)
14239         {
14240                 DE_UNREF(in);
14241
14242                 return 256.0; // This is not a precision test. Value is not from spec
14243         }
14244
14245         template<class fp16type>
14246         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14247         {
14248                 DE_ASSERT(in.size() == 2);
14249                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14250                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14251
14252                 if (getFlavor() < 4)
14253                 {
14254                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14255                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14256
14257                         if (floatCalc)
14258                         {
14259                                 float   dp(0.0f);
14260
14261                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14262                                 {
14263                                         const fp16type  i       (in[0][componentNdx]);
14264                                         const fp16type  n       (in[1][componentNdx]);
14265                                         const float             id      (i.asFloat());
14266                                         const float             nd      (n.asFloat());
14267                                         const float             qd      (id * nd);
14268
14269                                         if (keepZeroSign)
14270                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14271                                         else
14272                                                 dp = dp + qd;
14273                                 }
14274
14275                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14276                                 {
14277                                         const fp16type  i               (in[0][componentNdx]);
14278                                         const fp16type  n               (in[1][componentNdx]);
14279                                         const float             dpnd    (dp * n.asFloat());
14280                                         const float             dpn2d   (2.0f * dpnd);
14281                                         const float             idpn2d  (i.asFloat() - dpn2d);
14282                                         const fp16type  result  (idpn2d);
14283
14284                                         out[componentNdx] = result.bits();
14285                                 }
14286                         }
14287                         else
14288                         {
14289                                 fp16type        dp(0.0);
14290
14291                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14292                                 {
14293                                         const fp16type  i       (in[0][componentNdx]);
14294                                         const fp16type  n       (in[1][componentNdx]);
14295                                         const double    id      (i.asDouble());
14296                                         const double    nd      (n.asDouble());
14297                                         const fp16type  q       (id * nd);
14298
14299                                         if (keepZeroSign)
14300                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14301                                         else
14302                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14303                                 }
14304
14305                                 if (dp.isNaN())
14306                                         return false;
14307
14308                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14309                                 {
14310                                         const fp16type  i               (in[0][componentNdx]);
14311                                         const fp16type  n               (in[1][componentNdx]);
14312                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14313                                         const fp16type  dpn2    (2 * dpn.asDouble());
14314                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14315
14316                                         out[componentNdx] = idpn2.bits();
14317                                 }
14318                         }
14319                 }
14320                 else if (getFlavor() == 4)
14321                 {
14322                         fp16type        dp(0.0);
14323
14324                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14325                         {
14326                                 const fp16type  i       (in[0][componentNdx]);
14327                                 const fp16type  n       (in[1][componentNdx]);
14328                                 const double    id      (i.asDouble());
14329                                 const double    nd      (n.asDouble());
14330                                 const fp16type  q       (id * nd);
14331
14332                                 dp = fp16type(dp.asDouble() + q.asDouble());
14333                         }
14334
14335                         if (dp.isNaN())
14336                                 return false;
14337
14338                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14339                         {
14340                                 const fp16type  i               (in[0][componentNdx]);
14341                                 const fp16type  n               (in[1][componentNdx]);
14342                                 const fp16type  n2              (2 * n.asDouble());
14343                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14344                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14345
14346                                 out[componentNdx] = idpn2.bits();
14347                         }
14348                 }
14349                 else if (getFlavor() == 5)
14350                 {
14351                         fp16type        dp2(0.0);
14352
14353                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14354                         {
14355                                 const fp16type  i       (in[0][componentNdx]);
14356                                 const fp16type  n       (in[1][componentNdx]);
14357                                 const fp16type  i2      (2.0 * i.asDouble());
14358                                 const double    i2d     (i2.asDouble());
14359                                 const double    nd      (n.asDouble());
14360                                 const fp16type  q       (i2d * nd);
14361
14362                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14363                         }
14364
14365                         if (dp2.isNaN())
14366                                 return false;
14367
14368                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14369                         {
14370                                 const fp16type  i               (in[0][componentNdx]);
14371                                 const fp16type  n               (in[1][componentNdx]);
14372                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14373                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14374
14375                                 out[componentNdx] = idpn2.bits();
14376                         }
14377                 }
14378                 else
14379                 {
14380                         TCU_THROW(InternalError, "Unknown flavor");
14381                 }
14382
14383                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14384                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14385                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14386                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14387
14388                 return true;
14389         }
14390 };
14391
14392 struct fp16Refract : public fp16AllComponents
14393 {
14394         fp16Refract() : fp16AllComponents()
14395         {
14396                 flavorNames.push_back("EmulatingFP16");
14397                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14398                 flavorNames.push_back("FloatCalc");
14399                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14400         }
14401
14402         virtual double getULPs(vector<const deFloat16*>& in)
14403         {
14404                 DE_UNREF(in);
14405
14406                 return 8192.0; // This is not a precision test. Value is not from spec
14407         }
14408
14409         template<class fp16type>
14410         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14411         {
14412                 DE_ASSERT(in.size() == 3);
14413                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14414                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14415                 DE_ASSERT(getArgCompCount(2) == 1);
14416
14417                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14418                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14419                 const fp16type  eta                             (*in[2]);
14420
14421                 if (doubleCalc)
14422                 {
14423                         double  dp      (0.0);
14424
14425                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14426                         {
14427                                 const fp16type  i       (in[0][componentNdx]);
14428                                 const fp16type  n       (in[1][componentNdx]);
14429                                 const double    id      (i.asDouble());
14430                                 const double    nd      (n.asDouble());
14431                                 const double    qd      (id * nd);
14432
14433                                 if (keepZeroSign)
14434                                         dp = (componentNdx == 0) ? qd : dp + qd;
14435                                 else
14436                                         dp = dp + qd;
14437                         }
14438
14439                         const double    eta2    (eta.asDouble() * eta.asDouble());
14440                         const double    dp2             (dp * dp);
14441                         const double    dp1             (1.0 - dp2);
14442                         const double    dpe             (eta2 * dp1);
14443                         const double    k               (1.0 - dpe);
14444
14445                         if (k < 0.0)
14446                         {
14447                                 const fp16type  zero    (0.0);
14448
14449                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14450                                         out[componentNdx] = zero.bits();
14451                         }
14452                         else
14453                         {
14454                                 const double    sk      (deSqrt(k));
14455
14456                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14457                                 {
14458                                         const fp16type  i               (in[0][componentNdx]);
14459                                         const fp16type  n               (in[1][componentNdx]);
14460                                         const double    etai    (i.asDouble() * eta.asDouble());
14461                                         const double    etadp   (eta.asDouble() * dp);
14462                                         const double    etadpk  (etadp + sk);
14463                                         const double    etadpkn (etadpk * n.asDouble());
14464                                         const double    full    (etai - etadpkn);
14465                                         const fp16type  result  (full);
14466
14467                                         if (result.isInf())
14468                                                 return false;
14469
14470                                         out[componentNdx] = result.bits();
14471                                 }
14472                         }
14473                 }
14474                 else
14475                 {
14476                         fp16type        dp      (0.0);
14477
14478                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14479                         {
14480                                 const fp16type  i       (in[0][componentNdx]);
14481                                 const fp16type  n       (in[1][componentNdx]);
14482                                 const double    id      (i.asDouble());
14483                                 const double    nd      (n.asDouble());
14484                                 const fp16type  q       (id * nd);
14485
14486                                 if (keepZeroSign)
14487                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14488                                 else
14489                                         dp = fp16type(dp.asDouble() + q.asDouble());
14490                         }
14491
14492                         if (dp.isNaN())
14493                                 return false;
14494
14495                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14496                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14497                         const fp16type  dp1     (1.0 - dp2.asDouble());
14498                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14499                         const fp16type  k       (1.0 - dpe.asDouble());
14500
14501                         if (k.asDouble() < 0.0)
14502                         {
14503                                 const fp16type  zero    (0.0);
14504
14505                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14506                                         out[componentNdx] = zero.bits();
14507                         }
14508                         else
14509                         {
14510                                 const fp16type  sk      (deSqrt(k.asDouble()));
14511
14512                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14513                                 {
14514                                         const fp16type  i               (in[0][componentNdx]);
14515                                         const fp16type  n               (in[1][componentNdx]);
14516                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14517                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14518                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14519                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14520                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14521
14522                                         if (full.isNaN() || full.isInf())
14523                                                 return false;
14524
14525                                         out[componentNdx] = full.bits();
14526                                 }
14527                         }
14528                 }
14529
14530                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14531                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14532                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14533                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14534
14535                 return true;
14536         }
14537 };
14538
14539 struct fp16Dot : public fp16AllComponents
14540 {
14541         fp16Dot() : fp16AllComponents()
14542         {
14543                 flavorNames.push_back("EmulatingFP16");
14544                 flavorNames.push_back("FloatCalc");
14545                 flavorNames.push_back("DoubleCalc");
14546
14547                 // flavorNames will be extended later
14548         }
14549
14550         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14551         {
14552                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14553
14554                 if (argNo == 0 && argCompCount[argNo] == 0)
14555                 {
14556                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14557                         std::vector<int>        indices;
14558
14559                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14560                                 indices.push_back(static_cast<int>(componentNdx));
14561
14562                         m_permutations.reserve(maxPermutationsCount);
14563
14564                         permutationsFlavorStart = flavorNames.size();
14565
14566                         do
14567                         {
14568                                 tcu::UVec4      permutation;
14569                                 std::string     name            = "Permutted_";
14570
14571                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14572                                 {
14573                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14574                                         name += de::toString(indices[componentNdx]);
14575                                 }
14576
14577                                 m_permutations.push_back(permutation);
14578                                 flavorNames.push_back(name);
14579
14580                         } while(std::next_permutation(indices.begin(), indices.end()));
14581
14582                         permutationsFlavorEnd = flavorNames.size();
14583                 }
14584
14585                 fp16AllComponents::setArgCompCount(argNo, compCount);
14586         }
14587
14588         virtual double  getULPs(vector<const deFloat16*>& in)
14589         {
14590                 DE_UNREF(in);
14591
14592                 return 16.0; // This is not a precision test. Value is not from spec
14593         }
14594
14595         template<class fp16type>
14596         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14597         {
14598                 DE_ASSERT(in.size() == 2);
14599                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14600                 DE_ASSERT(getOutCompCount() == 1);
14601
14602                 double  result  (0.0);
14603                 double  eps             (0.0);
14604
14605                 if (getFlavor() == 0)
14606                 {
14607                         fp16type        dp      (0.0);
14608
14609                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14610                         {
14611                                 const fp16type  x       (in[0][componentNdx]);
14612                                 const fp16type  y       (in[1][componentNdx]);
14613                                 const fp16type  q       (x.asDouble() * y.asDouble());
14614
14615                                 dp = fp16type(dp.asDouble() + q.asDouble());
14616                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14617                         }
14618
14619                         result = dp.asDouble();
14620                 }
14621                 else if (getFlavor() == 1)
14622                 {
14623                         float   dp      (0.0);
14624
14625                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14626                         {
14627                                 const fp16type  x       (in[0][componentNdx]);
14628                                 const fp16type  y       (in[1][componentNdx]);
14629                                 const float             q       (x.asFloat() * y.asFloat());
14630
14631                                 dp += q;
14632                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14633                         }
14634
14635                         result = dp;
14636                 }
14637                 else if (getFlavor() == 2)
14638                 {
14639                         double  dp      (0.0);
14640
14641                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14642                         {
14643                                 const fp16type  x       (in[0][componentNdx]);
14644                                 const fp16type  y       (in[1][componentNdx]);
14645                                 const double    q       (x.asDouble() * y.asDouble());
14646
14647                                 dp += q;
14648                                 eps += floatFormat16.ulp(q, 2.0);
14649                         }
14650
14651                         result = dp;
14652                 }
14653                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14654                 {
14655                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14656                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14657                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14658                         fp16type                        dp                              (0.0);
14659
14660                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14661                         {
14662                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14663                                 const fp16type          x                               (in[0][componentNdx]);
14664                                 const fp16type          y                               (in[1][componentNdx]);
14665                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14666
14667                                 dp = fp16type(dp.asDouble() + q.asDouble());
14668                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14669                         }
14670
14671                         result = dp.asDouble();
14672                 }
14673                 else
14674                 {
14675                         TCU_THROW(InternalError, "Unknown flavor");
14676                 }
14677
14678                 out[0] = fp16type(result).bits();
14679                 min[0] = result - eps;
14680                 max[0] = result + eps;
14681
14682                 return true;
14683         }
14684
14685 private:
14686         std::vector<tcu::UVec4> m_permutations;
14687         size_t                                  permutationsFlavorStart;
14688         size_t                                  permutationsFlavorEnd;
14689 };
14690
14691 struct fp16VectorTimesScalar : public fp16AllComponents
14692 {
14693         virtual double getULPs(vector<const deFloat16*>& in)
14694         {
14695                 DE_UNREF(in);
14696
14697                 return 2.0;
14698         }
14699
14700         template<class fp16type>
14701         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14702         {
14703                 DE_ASSERT(in.size() == 2);
14704                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14705                 DE_ASSERT(getArgCompCount(1) == 1);
14706
14707                 fp16type        s       (*in[1]);
14708
14709                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14710                 {
14711                         const fp16type  x          (in[0][componentNdx]);
14712                         const double    result (s.asDouble() * x.asDouble());
14713                         const fp16type  m          (result);
14714
14715                         out[componentNdx] = m.bits();
14716                         min[componentNdx] = getMin(result, getULPs(in));
14717                         max[componentNdx] = getMax(result, getULPs(in));
14718                 }
14719
14720                 return true;
14721         }
14722 };
14723
14724 struct fp16MatrixBase : public fp16AllComponents
14725 {
14726         deUint32                getComponentValidity                    ()
14727         {
14728                 return static_cast<deUint32>(-1);
14729         }
14730
14731         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14732         {
14733                 const size_t minComponentCount  = 0;
14734                 const size_t maxComponentCount  = 3;
14735                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14736
14737                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14738                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14739                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14740                 DE_UNREF(minComponentCount);
14741                 DE_UNREF(maxComponentCount);
14742
14743                 return col * alignedRowsCount + row;
14744         }
14745
14746         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14747         {
14748                 deUint32        result  = 0u;
14749
14750                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14751                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14752                         {
14753                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14754
14755                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14756
14757                                 result |= (1<<bitNdx);
14758                         }
14759
14760                 return result;
14761         }
14762 };
14763
14764 template<size_t cols, size_t rows>
14765 struct fp16Transpose : public fp16MatrixBase
14766 {
14767         virtual double getULPs(vector<const deFloat16*>& in)
14768         {
14769                 DE_UNREF(in);
14770
14771                 return 1.0;
14772         }
14773
14774         deUint32        getComponentValidity    ()
14775         {
14776                 return getComponentMatrixValidityMask(rows, cols);
14777         }
14778
14779         template<class fp16type>
14780         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14781         {
14782                 DE_ASSERT(in.size() == 1);
14783
14784                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14785                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14786                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14787
14788                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14789
14790                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14791                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14792                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14793
14794                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14795                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14796                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14797
14798                 return true;
14799         }
14800 };
14801
14802 template<size_t cols, size_t rows>
14803 struct fp16MatrixTimesScalar : public fp16MatrixBase
14804 {
14805         virtual double getULPs(vector<const deFloat16*>& in)
14806         {
14807                 DE_UNREF(in);
14808
14809                 return 4.0;
14810         }
14811
14812         deUint32        getComponentValidity    ()
14813         {
14814                 return getComponentMatrixValidityMask(cols, rows);
14815         }
14816
14817         template<class fp16type>
14818         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14819         {
14820                 DE_ASSERT(in.size() == 2);
14821                 DE_ASSERT(getArgCompCount(1) == 1);
14822
14823                 const fp16type  y                       (in[1][0]);
14824                 const float             scalar          (y.asFloat());
14825                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14826                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14827
14828                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14829                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14830                 DE_UNREF(alignedCols);
14831
14832                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14833                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14834                         {
14835                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14836                                 const fp16type  x       (in[0][ndx]);
14837                                 const double    result  (scalar * x.asFloat());
14838
14839                                 out[ndx] = fp16type(result).bits();
14840                                 min[ndx] = getMin(result, getULPs(in));
14841                                 max[ndx] = getMax(result, getULPs(in));
14842                         }
14843
14844                 return true;
14845         }
14846 };
14847
14848 template<size_t cols, size_t rows>
14849 struct fp16VectorTimesMatrix : public fp16MatrixBase
14850 {
14851         fp16VectorTimesMatrix() : fp16MatrixBase()
14852         {
14853                 flavorNames.push_back("EmulatingFP16");
14854                 flavorNames.push_back("FloatCalc");
14855         }
14856
14857         virtual double getULPs (vector<const deFloat16*>& in)
14858         {
14859                 DE_UNREF(in);
14860
14861                 return (8.0 * cols);
14862         }
14863
14864         deUint32 getComponentValidity ()
14865         {
14866                 return getComponentMatrixValidityMask(cols, 1);
14867         }
14868
14869         template<class fp16type>
14870         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14871         {
14872                 DE_ASSERT(in.size() == 2);
14873
14874                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14875                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14876
14877                 DE_ASSERT(getOutCompCount() == cols);
14878                 DE_ASSERT(getArgCompCount(0) == rows);
14879                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14880                 DE_UNREF(alignedCols);
14881
14882                 if (getFlavor() == 0)
14883                 {
14884                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14885                         {
14886                                 fp16type        s       (fp16type::zero(1));
14887
14888                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14889                                 {
14890                                         const fp16type  v       (in[0][rowNdx]);
14891                                         const float             vf      (v.asFloat());
14892                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14893                                         const fp16type  x       (in[1][ndx]);
14894                                         const float             xf      (x.asFloat());
14895                                         const fp16type  m       (vf * xf);
14896
14897                                         s = fp16type(s.asFloat() + m.asFloat());
14898                                 }
14899
14900                                 out[colNdx] = s.bits();
14901                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14902                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14903                         }
14904                 }
14905                 else if (getFlavor() == 1)
14906                 {
14907                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14908                         {
14909                                 float   s       (0.0f);
14910
14911                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14912                                 {
14913                                         const fp16type  v       (in[0][rowNdx]);
14914                                         const float             vf      (v.asFloat());
14915                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14916                                         const fp16type  x       (in[1][ndx]);
14917                                         const float             xf      (x.asFloat());
14918                                         const float             m       (vf * xf);
14919
14920                                         s += m;
14921                                 }
14922
14923                                 out[colNdx] = fp16type(s).bits();
14924                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14925                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14926                         }
14927                 }
14928                 else
14929                 {
14930                         TCU_THROW(InternalError, "Unknown flavor");
14931                 }
14932
14933                 return true;
14934         }
14935 };
14936
14937 template<size_t cols, size_t rows>
14938 struct fp16MatrixTimesVector : public fp16MatrixBase
14939 {
14940         fp16MatrixTimesVector() : fp16MatrixBase()
14941         {
14942                 flavorNames.push_back("EmulatingFP16");
14943                 flavorNames.push_back("FloatCalc");
14944         }
14945
14946         virtual double getULPs (vector<const deFloat16*>& in)
14947         {
14948                 DE_UNREF(in);
14949
14950                 return (8.0 * rows);
14951         }
14952
14953         deUint32 getComponentValidity ()
14954         {
14955                 return getComponentMatrixValidityMask(rows, 1);
14956         }
14957
14958         template<class fp16type>
14959         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14960         {
14961                 DE_ASSERT(in.size() == 2);
14962
14963                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14964                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14965
14966                 DE_ASSERT(getOutCompCount() == rows);
14967                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14968                 DE_ASSERT(getArgCompCount(1) == cols);
14969                 DE_UNREF(alignedCols);
14970
14971                 if (getFlavor() == 0)
14972                 {
14973                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14974                         {
14975                                 fp16type        s       (fp16type::zero(1));
14976
14977                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14978                                 {
14979                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14980                                         const fp16type  x       (in[0][ndx]);
14981                                         const float             xf      (x.asFloat());
14982                                         const fp16type  v       (in[1][colNdx]);
14983                                         const float             vf      (v.asFloat());
14984                                         const fp16type  m       (vf * xf);
14985
14986                                         s = fp16type(s.asFloat() + m.asFloat());
14987                                 }
14988
14989                                 out[rowNdx] = s.bits();
14990                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14991                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14992                         }
14993                 }
14994                 else if (getFlavor() == 1)
14995                 {
14996                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14997                         {
14998                                 float   s       (0.0f);
14999
15000                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15001                                 {
15002                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15003                                         const fp16type  x       (in[0][ndx]);
15004                                         const float             xf      (x.asFloat());
15005                                         const fp16type  v       (in[1][colNdx]);
15006                                         const float             vf      (v.asFloat());
15007                                         const float             m       (vf * xf);
15008
15009                                         s += m;
15010                                 }
15011
15012                                 out[rowNdx] = fp16type(s).bits();
15013                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
15014                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
15015                         }
15016                 }
15017                 else
15018                 {
15019                         TCU_THROW(InternalError, "Unknown flavor");
15020                 }
15021
15022                 return true;
15023         }
15024 };
15025
15026 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15027 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15028 {
15029         fp16MatrixTimesMatrix() : fp16MatrixBase()
15030         {
15031                 flavorNames.push_back("EmulatingFP16");
15032                 flavorNames.push_back("FloatCalc");
15033         }
15034
15035         virtual double getULPs (vector<const deFloat16*>& in)
15036         {
15037                 DE_UNREF(in);
15038
15039                 return 32.0;
15040         }
15041
15042         deUint32 getComponentValidity ()
15043         {
15044                 return getComponentMatrixValidityMask(colsR, rowsL);
15045         }
15046
15047         template<class fp16type>
15048         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15049         {
15050                 DE_STATIC_ASSERT(colsL == rowsR);
15051
15052                 DE_ASSERT(in.size() == 2);
15053
15054                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15055                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15056                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15057                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15058
15059                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15060                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15061                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15062                 DE_UNREF(alignedColsL);
15063                 DE_UNREF(alignedColsR);
15064
15065                 if (getFlavor() == 0)
15066                 {
15067                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15068                         {
15069                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15070                                 {
15071                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15072                                         fp16type                s       (fp16type::zero(1));
15073
15074                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15075                                         {
15076                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15077                                                 const fp16type  l               (in[0][ndxl]);
15078                                                 const float             lf              (l.asFloat());
15079                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15080                                                 const fp16type  r               (in[1][ndxr]);
15081                                                 const float             rf              (r.asFloat());
15082                                                 const fp16type  m               (lf * rf);
15083
15084                                                 s = fp16type(s.asFloat() + m.asFloat());
15085                                         }
15086
15087                                         out[ndx] = s.bits();
15088                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15089                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15090                                 }
15091                         }
15092                 }
15093                 else if (getFlavor() == 1)
15094                 {
15095                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15096                         {
15097                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15098                                 {
15099                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15100                                         float                   s       (0.0f);
15101
15102                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15103                                         {
15104                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15105                                                 const fp16type  l               (in[0][ndxl]);
15106                                                 const float             lf              (l.asFloat());
15107                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15108                                                 const fp16type  r               (in[1][ndxr]);
15109                                                 const float             rf              (r.asFloat());
15110                                                 const float             m               (lf * rf);
15111
15112                                                 s += m;
15113                                         }
15114
15115                                         out[ndx] = fp16type(s).bits();
15116                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15117                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15118                                 }
15119                         }
15120                 }
15121                 else
15122                 {
15123                         TCU_THROW(InternalError, "Unknown flavor");
15124                 }
15125
15126                 return true;
15127         }
15128 };
15129
15130 template<size_t cols, size_t rows>
15131 struct fp16OuterProduct : public fp16MatrixBase
15132 {
15133         virtual double getULPs (vector<const deFloat16*>& in)
15134         {
15135                 DE_UNREF(in);
15136
15137                 return 2.0;
15138         }
15139
15140         deUint32 getComponentValidity ()
15141         {
15142                 return getComponentMatrixValidityMask(cols, rows);
15143         }
15144
15145         template<class fp16type>
15146         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15147         {
15148                 DE_ASSERT(in.size() == 2);
15149
15150                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15151                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15152
15153                 DE_ASSERT(getArgCompCount(0) == rows);
15154                 DE_ASSERT(getArgCompCount(1) == cols);
15155                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15156                 DE_UNREF(alignedCols);
15157
15158                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15159                 {
15160                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15161                         {
15162                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15163                                 const fp16type  x       (in[0][rowNdx]);
15164                                 const float             xf      (x.asFloat());
15165                                 const fp16type  y       (in[1][colNdx]);
15166                                 const float             yf      (y.asFloat());
15167                                 const fp16type  m       (xf * yf);
15168
15169                                 out[ndx] = m.bits();
15170                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15171                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15172                         }
15173                 }
15174
15175                 return true;
15176         }
15177 };
15178
15179 template<size_t size>
15180 struct fp16Determinant;
15181
15182 template<>
15183 struct fp16Determinant<2> : public fp16MatrixBase
15184 {
15185         virtual double getULPs (vector<const deFloat16*>& in)
15186         {
15187                 DE_UNREF(in);
15188
15189                 return 128.0; // This is not a precision test. Value is not from spec
15190         }
15191
15192         deUint32 getComponentValidity ()
15193         {
15194                 return 1;
15195         }
15196
15197         template<class fp16type>
15198         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15199         {
15200                 const size_t    cols            = 2;
15201                 const size_t    rows            = 2;
15202                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15203                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15204
15205                 DE_ASSERT(in.size() == 1);
15206                 DE_ASSERT(getOutCompCount() == 1);
15207                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15208                 DE_UNREF(alignedCols);
15209                 DE_UNREF(alignedRows);
15210
15211                 // [ a b ]
15212                 // [ c d ]
15213                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15214                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15215                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15216                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15217                 const float             ad              (a * d);
15218                 const fp16type  adf16   (ad);
15219                 const float             bc              (b * c);
15220                 const fp16type  bcf16   (bc);
15221                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15222                 const fp16type  rf16    (r);
15223
15224                 out[0] = rf16.bits();
15225                 min[0] = getMin(r, getULPs(in));
15226                 max[0] = getMax(r, getULPs(in));
15227
15228                 return true;
15229         }
15230 };
15231
15232 template<>
15233 struct fp16Determinant<3> : public fp16MatrixBase
15234 {
15235         virtual double getULPs (vector<const deFloat16*>& in)
15236         {
15237                 DE_UNREF(in);
15238
15239                 return 128.0; // This is not a precision test. Value is not from spec
15240         }
15241
15242         deUint32 getComponentValidity ()
15243         {
15244                 return 1;
15245         }
15246
15247         template<class fp16type>
15248         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15249         {
15250                 const size_t    cols            = 3;
15251                 const size_t    rows            = 3;
15252                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15253                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15254
15255                 DE_ASSERT(in.size() == 1);
15256                 DE_ASSERT(getOutCompCount() == 1);
15257                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15258                 DE_UNREF(alignedCols);
15259                 DE_UNREF(alignedRows);
15260
15261                 // [ a b c ]
15262                 // [ d e f ]
15263                 // [ g h i ]
15264                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15265                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15266                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15267                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15268                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15269                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15270                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15271                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15272                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15273                 const fp16type  aei             (a * e * i);
15274                 const fp16type  bfg             (b * f * g);
15275                 const fp16type  cdh             (c * d * h);
15276                 const fp16type  ceg             (c * e * g);
15277                 const fp16type  bdi             (b * d * i);
15278                 const fp16type  afh             (a * f * h);
15279                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15280                 const fp16type  rf16    (r);
15281
15282                 out[0] = rf16.bits();
15283                 min[0] = getMin(r, getULPs(in));
15284                 max[0] = getMax(r, getULPs(in));
15285
15286                 return true;
15287         }
15288 };
15289
15290 template<>
15291 struct fp16Determinant<4> : public fp16MatrixBase
15292 {
15293         virtual double getULPs (vector<const deFloat16*>& in)
15294         {
15295                 DE_UNREF(in);
15296
15297                 return 128.0; // This is not a precision test. Value is not from spec
15298         }
15299
15300         deUint32 getComponentValidity ()
15301         {
15302                 return 1;
15303         }
15304
15305         template<class fp16type>
15306         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15307         {
15308                 const size_t    rows            = 4;
15309                 const size_t    cols            = 4;
15310                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15311                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15312
15313                 DE_ASSERT(in.size() == 1);
15314                 DE_ASSERT(getOutCompCount() == 1);
15315                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15316                 DE_UNREF(alignedCols);
15317                 DE_UNREF(alignedRows);
15318
15319                 // [ a b c d ]
15320                 // [ e f g h ]
15321                 // [ i j k l ]
15322                 // [ m n o p ]
15323                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15324                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15325                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15326                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15327                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15328                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15329                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15330                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15331                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15332                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15333                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15334                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15335                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15336                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15337                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15338                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15339
15340                 // [ f g h ]
15341                 // [ j k l ]
15342                 // [ n o p ]
15343                 const fp16type  fkp             (f * k * p);
15344                 const fp16type  gln             (g * l * n);
15345                 const fp16type  hjo             (h * j * o);
15346                 const fp16type  hkn             (h * k * n);
15347                 const fp16type  gjp             (g * j * p);
15348                 const fp16type  flo             (f * l * o);
15349                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15350
15351                 // [ e g h ]
15352                 // [ i k l ]
15353                 // [ m o p ]
15354                 const fp16type  ekp             (e * k * p);
15355                 const fp16type  glm             (g * l * m);
15356                 const fp16type  hio             (h * i * o);
15357                 const fp16type  hkm             (h * k * m);
15358                 const fp16type  gip             (g * i * p);
15359                 const fp16type  elo             (e * l * o);
15360                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15361
15362                 // [ e f h ]
15363                 // [ i j l ]
15364                 // [ m n p ]
15365                 const fp16type  ejp             (e * j * p);
15366                 const fp16type  flm             (f * l * m);
15367                 const fp16type  hin             (h * i * n);
15368                 const fp16type  hjm             (h * j * m);
15369                 const fp16type  fip             (f * i * p);
15370                 const fp16type  eln             (e * l * n);
15371                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15372
15373                 // [ e f g ]
15374                 // [ i j k ]
15375                 // [ m n o ]
15376                 const fp16type  ejo             (e * j * o);
15377                 const fp16type  fkm             (f * k * m);
15378                 const fp16type  gin             (g * i * n);
15379                 const fp16type  gjm             (g * j * m);
15380                 const fp16type  fio             (f * i * o);
15381                 const fp16type  ekn             (e * k * n);
15382                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15383
15384                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15385                 const fp16type  rf16    (r);
15386
15387                 out[0] = rf16.bits();
15388                 min[0] = getMin(r, getULPs(in));
15389                 max[0] = getMax(r, getULPs(in));
15390
15391                 return true;
15392         }
15393 };
15394
15395 template<size_t size>
15396 struct fp16Inverse;
15397
15398 template<>
15399 struct fp16Inverse<2> : public fp16MatrixBase
15400 {
15401         virtual double getULPs (vector<const deFloat16*>& in)
15402         {
15403                 DE_UNREF(in);
15404
15405                 return 128.0; // This is not a precision test. Value is not from spec
15406         }
15407
15408         deUint32 getComponentValidity ()
15409         {
15410                 return getComponentMatrixValidityMask(2, 2);
15411         }
15412
15413         template<class fp16type>
15414         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15415         {
15416                 const size_t    cols            = 2;
15417                 const size_t    rows            = 2;
15418                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15419                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15420
15421                 DE_ASSERT(in.size() == 1);
15422                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15423                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15424                 DE_UNREF(alignedCols);
15425
15426                 // [ a b ]
15427                 // [ c d ]
15428                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15429                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15430                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15431                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15432                 const float             ad              (a * d);
15433                 const fp16type  adf16   (ad);
15434                 const float             bc              (b * c);
15435                 const fp16type  bcf16   (bc);
15436                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15437                 const fp16type  det16   (det);
15438
15439                 out[0] = fp16type( d / det16.asFloat()).bits();
15440                 out[1] = fp16type(-c / det16.asFloat()).bits();
15441                 out[2] = fp16type(-b / det16.asFloat()).bits();
15442                 out[3] = fp16type( a / det16.asFloat()).bits();
15443
15444                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15445                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15446                         {
15447                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15448                                 const fp16type  s       (out[ndx]);
15449
15450                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15451                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15452                         }
15453
15454                 return true;
15455         }
15456 };
15457
15458 inline std::string fp16ToString(deFloat16 val)
15459 {
15460         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15461 }
15462
15463 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15464 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15465 {
15466         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15467                 return false;
15468
15469         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15470         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15471         const size_t    inputsSteps[3]          =
15472         {
15473                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15474                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15475                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15476         };
15477
15478         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15479         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15480
15481         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15482         {
15483                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15484                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15485         }
15486
15487         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15488         TestedArithmeticFunction        func;
15489
15490         func.setOutCompCount(RES_COMPONENTS);
15491         func.setArgCompCount(0, ARG0_COMPONENTS);
15492         func.setArgCompCount(1, ARG1_COMPONENTS);
15493         func.setArgCompCount(2, ARG2_COMPONENTS);
15494
15495         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15496         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15497         const size_t                            denormModesCount                                = 2;
15498         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15499         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15500         bool                                            success                                                 = true;
15501         size_t                                          validatedCount                                  = 0;
15502
15503         vector<deUint8> inputBytes[3];
15504
15505         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15506                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15507
15508         const deFloat16* const                  inputsAsFP16[3]                 =
15509         {
15510                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15511                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15512                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15513         };
15514
15515         for (size_t idx = 0; idx < iterationsCount; ++idx)
15516         {
15517                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15518                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15519                 bool                                            iterationValidated      (true);
15520
15521                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15522                 {
15523                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15524                         {
15525                                 func.setFlavor(flavorNdx);
15526
15527                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15528                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15529                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15530                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15531                                 vector<const deFloat16*>        arguments;
15532
15533                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15534                                 {
15535                                         std::string     error;
15536                                         bool            reportError = false;
15537
15538                                         if (callOncePerComponent || componentNdx == 0)
15539                                         {
15540                                                 bool funcCallResult;
15541
15542                                                 arguments.clear();
15543
15544                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15545                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15546
15547                                                 if (denormNdx == 0)
15548                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15549                                                 else
15550                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15551
15552                                                 if (!funcCallResult)
15553                                                 {
15554                                                         iterationValidated = false;
15555
15556                                                         if (callOncePerComponent)
15557                                                                 continue;
15558                                                         else
15559                                                                 break;
15560                                                 }
15561                                         }
15562
15563                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15564                                                 continue;
15565
15566                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15567
15568                                         if (reportError)
15569                                         {
15570                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15571                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15572
15573                                                 if (reportError && expected.isNaN())
15574                                                         reportError = false;
15575
15576                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15577                                                 {
15578                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15579                                                         {
15580                                                                 // Ignore rounding
15581                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15582                                                                         reportError = false;
15583                                                         }
15584
15585                                                         if (reportError && expected.isInf())
15586                                                         {
15587                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15588                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15589                                                                         reportError = false;
15590                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15591                                                                         reportError = false;
15592                                                         }
15593
15594                                                         if (reportError)
15595                                                         {
15596                                                                 const double    outputtedDouble = outputted.asDouble();
15597
15598                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15599
15600                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15601                                                                         reportError = false;
15602                                                         }
15603                                                 }
15604
15605                                                 if (reportError)
15606                                                 {
15607                                                         const size_t            inputsComps[3]  =
15608                                                         {
15609                                                                 ARG0_COMPONENTS,
15610                                                                 ARG1_COMPONENTS,
15611                                                                 ARG2_COMPONENTS,
15612                                                         };
15613                                                         string                          inputsValues    ("Inputs:");
15614                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15615                                                         std::stringstream       errStream;
15616
15617                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15618                                                         {
15619                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15620
15621                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15622
15623                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15624                                                                 {
15625                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15626
15627                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15628                                                                 }
15629                                                         }
15630
15631                                                         errStream       << "At"
15632                                                                                 << " iteration " << de::toString(idx)
15633                                                                                 << " component " << de::toString(componentNdx)
15634                                                                                 << " denormMode " << de::toString(denormNdx)
15635                                                                                 << " (" << denormModes[denormNdx] << ")"
15636                                                                                 << " " << flavorName
15637                                                                                 << " " << inputsValues
15638                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15639                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15640                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15641                                                                                 << " " << error << "."
15642                                                                                 << std::endl;
15643
15644                                                         errors[componentNdx] += errStream.str();
15645
15646                                                         successfulRuns[componentNdx]--;
15647                                                 }
15648                                         }
15649                                 }
15650                         }
15651                 }
15652
15653                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15654                 {
15655                         // Check if any component has total failure
15656                         if (successfulRuns[componentNdx] == 0)
15657                         {
15658                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15659                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15660
15661                                 success = false;
15662                         }
15663                 }
15664
15665                 if (iterationValidated)
15666                         validatedCount++;
15667         }
15668
15669         if (validatedCount < 16)
15670                 TCU_THROW(InternalError, "Too few samples has been validated.");
15671
15672         return success;
15673 }
15674
15675 // IEEE-754 floating point numbers:
15676 // +--------+------+----------+-------------+
15677 // | binary | sign | exponent | significand |
15678 // +--------+------+----------+-------------+
15679 // | 16-bit |  1   |    5     |     10      |
15680 // +--------+------+----------+-------------+
15681 // | 32-bit |  1   |    8     |     23      |
15682 // +--------+------+----------+-------------+
15683 //
15684 // 16-bit floats:
15685 //
15686 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15687 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15688 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15689 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15690 //
15691 // 0   000 00   00 0000 0000 (0x0000: +0)
15692 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15693 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15694 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15695 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15696 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15697 // Generate and return 16-bit floats and their corresponding 32-bit values.
15698 //
15699 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15700 // Expected count to be at least 14 (numPicks).
15701 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15702 {
15703         vector<deFloat16>       float16;
15704
15705         float16.reserve(count);
15706
15707         // Zero
15708         float16.push_back(deUint16(0x0000));
15709         float16.push_back(deUint16(0x8000));
15710         // Infinity
15711         float16.push_back(deUint16(0x7c00));
15712         float16.push_back(deUint16(0xfc00));
15713         // Normalized
15714         float16.push_back(deUint16(0x0401));
15715         float16.push_back(deUint16(0x8401));
15716         // Some normal number
15717         float16.push_back(deUint16(0x14cb));
15718         float16.push_back(deUint16(0x94cb));
15719         // Min/max positive normal
15720         float16.push_back(deUint16(0x0400));
15721         float16.push_back(deUint16(0x7bff));
15722         // Min/max negative normal
15723         float16.push_back(deUint16(0x8400));
15724         float16.push_back(deUint16(0xfbff));
15725         // PI
15726         float16.push_back(deUint16(0x4248)); // 3.140625
15727         float16.push_back(deUint16(0xb248)); // -3.140625
15728         // PI/2
15729         float16.push_back(deUint16(0x3e48)); // 1.5703125
15730         float16.push_back(deUint16(0xbe48)); // -1.5703125
15731         float16.push_back(deUint16(0x3c00)); // 1.0
15732         float16.push_back(deUint16(0x3800)); // 0.5
15733         // Some useful constants
15734         float16.push_back(tcu::Float16(-2.5f).bits());
15735         float16.push_back(tcu::Float16(-1.0f).bits());
15736         float16.push_back(tcu::Float16( 0.4f).bits());
15737         float16.push_back(tcu::Float16( 2.5f).bits());
15738
15739         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15740
15741         DE_ASSERT(count >= numPicks);
15742         count -= numPicks;
15743
15744         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15745         {
15746                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15747                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15748                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15749
15750                 // Exclude power of -14 to avoid denorms
15751                 DE_ASSERT(de::inRange(exponent, -13, 15));
15752
15753                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15754         }
15755
15756         return float16;
15757 }
15758
15759 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15760 {
15761         DE_UNREF(argNo);
15762
15763         de::Random      rnd(seed);
15764
15765         return getFloat16a(rnd, static_cast<deUint32>(count));
15766 }
15767
15768 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15769 {
15770         de::Random      rnd             (seed);
15771         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15772
15773         DE_ASSERT(newCount * newCount == count);
15774
15775         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15776
15777         return squarize(float16, static_cast<deUint32>(argNo));
15778 }
15779
15780 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15781 {
15782         if (argNo == 0 || argNo == 1)
15783                 return getInputData2(seed, count, argNo);
15784         else
15785                 return getInputData1(seed<<argNo, count, argNo);
15786 }
15787
15788 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15789 {
15790         DE_UNREF(stride);
15791
15792         vector<deFloat16>       result;
15793
15794         switch (argCount)
15795         {
15796                 case 1:result = getInputData1(seed, count, argNo); break;
15797                 case 2:result = getInputData2(seed, count, argNo); break;
15798                 case 3:result = getInputData3(seed, count, argNo); break;
15799                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15800         }
15801
15802         if (compCount == 3)
15803         {
15804                 const size_t            newCount = (3 * count) / 4;
15805                 vector<deFloat16>       newResult;
15806
15807                 newResult.reserve(result.size());
15808
15809                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15810                 {
15811                         newResult.push_back(result[ndx]);
15812
15813                         if (ndx % 3 == 2)
15814                                 newResult.push_back(0);
15815                 }
15816
15817                 result = newResult;
15818         }
15819
15820         DE_ASSERT(result.size() == count);
15821
15822         return result;
15823 }
15824
15825 // Generator for functions requiring data in range [1, inf]
15826 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15827 {
15828         vector<deFloat16>       result;
15829
15830         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15831
15832         // Filter out values below 1.0 from upper half of numbers
15833         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15834         {
15835                 const float f = tcu::Float16(result[idx]).asFloat();
15836
15837                 if (f < 1.0f)
15838                         result[idx] = tcu::Float16(1.0f - f).bits();
15839         }
15840
15841         return result;
15842 }
15843
15844 // Generator for functions requiring data in range [-1, 1]
15845 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15846 {
15847         vector<deFloat16>       result;
15848
15849         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15850
15851         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15852         {
15853                 const float f = tcu::Float16(result[idx]).asFloat();
15854
15855                 if (!de::inRange(f, -1.0f, 1.0f))
15856                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15857         }
15858
15859         return result;
15860 }
15861
15862 // Generator for functions requiring data in range [-pi, pi]
15863 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15864 {
15865         vector<deFloat16>       result;
15866
15867         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15868
15869         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15870         {
15871                 const float f = tcu::Float16(result[idx]).asFloat();
15872
15873                 if (!de::inRange(f, -DE_PI, DE_PI))
15874                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15875         }
15876
15877         return result;
15878 }
15879
15880 // Generator for functions requiring data in range [0, inf]
15881 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15882 {
15883         vector<deFloat16>       result;
15884
15885         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15886
15887         if (argNo == 0)
15888         {
15889                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15890                         result[idx] &= static_cast<deFloat16>(~0x8000);
15891         }
15892
15893         return result;
15894 }
15895
15896 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15897 {
15898         DE_UNREF(stride);
15899         DE_UNREF(argCount);
15900
15901         vector<deFloat16>       result;
15902
15903         if (argNo == 0)
15904                 result = getInputData2(seed, count, argNo);
15905         else
15906         {
15907                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15908                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15909                 const size_t            newCountY               = count / newCountX;
15910                 de::Random                      rnd                             (seed);
15911                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15912
15913                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15914
15915                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15916                 {
15917                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15918
15919                         result.insert(result.end(), tmp.begin(), tmp.end());
15920                 }
15921         }
15922
15923         DE_ASSERT(result.size() == count);
15924
15925         return result;
15926 }
15927
15928 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15929 {
15930         DE_UNREF(compCount);
15931         DE_UNREF(stride);
15932         DE_UNREF(argCount);
15933
15934         de::Random                      rnd             (seed << argNo);
15935         vector<deFloat16>       result;
15936
15937         result = getFloat16a(rnd, static_cast<deUint32>(count));
15938
15939         DE_ASSERT(result.size() == count);
15940
15941         return result;
15942 }
15943
15944 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15945 {
15946         DE_UNREF(compCount);
15947         DE_UNREF(argCount);
15948
15949         de::Random                      rnd             (seed << argNo);
15950         vector<deFloat16>       result;
15951
15952         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15953         {
15954                 int num = (rnd.getUint16() % 16) - 8;
15955
15956                 result.push_back(tcu::Float16(float(num)).bits());
15957         }
15958
15959         result[0 * stride] = deUint16(0x7c00); // +Inf
15960         result[1 * stride] = deUint16(0xfc00); // -Inf
15961
15962         DE_ASSERT(result.size() == count);
15963
15964         return result;
15965 }
15966
15967 // Generator for smoothstep function
15968 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15969 {
15970         vector<deFloat16>       result;
15971
15972         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15973
15974         if (argNo == 0)
15975         {
15976                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15977                 {
15978                         const float f = tcu::Float16(result[idx]).asFloat();
15979
15980                         if (f > 4.0f)
15981                                 result[idx] = tcu::Float16(-f).bits();
15982                 }
15983         }
15984
15985         if (argNo == 1)
15986         {
15987                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15988                 {
15989                         const float f = tcu::Float16(result[idx]).asFloat();
15990
15991                         if (f < 4.0f)
15992                                 result[idx] = tcu::Float16(-f).bits();
15993                 }
15994         }
15995
15996         return result;
15997 }
15998
15999 // Generates normalized vectors for arguments 0 and 1
16000 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16001 {
16002         DE_UNREF(compCount);
16003         DE_UNREF(argCount);
16004
16005         de::Random                      rnd             (seed << argNo);
16006         vector<deFloat16>       result;
16007
16008         if (argNo == 0 || argNo == 1)
16009         {
16010                 // The input parameters for the incident vector I and the surface normal N must already be normalized
16011                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
16012                 {
16013                         vector <float>  unnormolized;
16014                         float                   sum                             = 0;
16015
16016                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16017                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
16018
16019                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16020                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
16021
16022                         sum = deFloatSqrt(sum);
16023                         if (sum == 0.0f)
16024                                 unnormolized[0] = sum = 1.0f;
16025
16026                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16027                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16028
16029                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16030                                 result.push_back(0);
16031                 }
16032         }
16033         else
16034         {
16035                 // Input parameter eta
16036                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16037                 {
16038                         int num = (rnd.getUint16() % 16) - 8;
16039
16040                         result.push_back(tcu::Float16(float(num)).bits());
16041                 }
16042         }
16043
16044         DE_ASSERT(result.size() == count);
16045
16046         return result;
16047 }
16048
16049 // Data generator for complex matrix functions like determinant and inverse
16050 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16051 {
16052         DE_UNREF(compCount);
16053         DE_UNREF(stride);
16054         DE_UNREF(argCount);
16055
16056         de::Random                      rnd             (seed << argNo);
16057         vector<deFloat16>       result;
16058
16059         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16060         {
16061                 int num = (rnd.getUint16() % 16) - 8;
16062
16063                 result.push_back(tcu::Float16(float(num)).bits());
16064         }
16065
16066         DE_ASSERT(result.size() == count);
16067
16068         return result;
16069 }
16070
16071 struct Math16TestType
16072 {
16073         const char*             typePrefix;
16074         const size_t    typeComponents;
16075         const size_t    typeArrayStride;
16076         const size_t    typeStructStride;
16077 };
16078
16079 enum Math16DataTypes
16080 {
16081         NONE    = 0,
16082         SCALAR  = 1,
16083         VEC2    = 2,
16084         VEC3    = 3,
16085         VEC4    = 4,
16086         MAT2X2,
16087         MAT2X3,
16088         MAT2X4,
16089         MAT3X2,
16090         MAT3X3,
16091         MAT3X4,
16092         MAT4X2,
16093         MAT4X3,
16094         MAT4X4,
16095         MATH16_TYPE_LAST
16096 };
16097
16098 struct Math16ArgFragments
16099 {
16100         const char*     bodies;
16101         const char*     variables;
16102         const char*     decorations;
16103         const char*     funcVariables;
16104 };
16105
16106 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16107
16108 struct Math16TestFunc
16109 {
16110         const char*                                     funcName;
16111         const char*                                     funcSuffix;
16112         size_t                                          funcArgsCount;
16113         size_t                                          typeResult;
16114         size_t                                          typeArg0;
16115         size_t                                          typeArg1;
16116         size_t                                          typeArg2;
16117         Math16GetInputData*                     getInputDataFunc;
16118         VerifyIOFunc                            verifyFunc;
16119 };
16120
16121 template<class SpecResource>
16122 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16123 {
16124         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16125         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16126         const size_t                            numDataPointsByAxis                     = 32;
16127         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16128         const char*                                     componentType                           = "f16";
16129         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16130         {
16131                 { "",           0,       0,                                              0,                                             },
16132                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16133                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16134                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16135                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16136                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16137                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16138                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16139                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16140                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16141                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16142                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16143                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16144                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16145         };
16146
16147         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16148
16149
16150         const StringTemplate preMain
16151         (
16152                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16153
16154                 "        %f16     = OpTypeFloat 16\n"
16155                 "        %v2f16   = OpTypeVector %f16 2\n"
16156                 "        %v3f16   = OpTypeVector %f16 3\n"
16157                 "        %v4f16   = OpTypeVector %f16 4\n"
16158                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16159                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16160                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16161                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16162                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16163                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16164                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16165                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16166                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16167
16168                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16169                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16170                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16171                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16172                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16173                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16174                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16175                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16176                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16177                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16178                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16179                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16180                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16181
16182                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16183                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16184                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16185                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16186                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16187                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16188                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16189                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16190                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16191                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16192                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16193                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16194                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16195
16196                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16197                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16198                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16199                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16200                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16201                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16202                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16203                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16204                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16205                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16206                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16207                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16208                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16209
16210                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16211                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16212                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16213                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16214                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16215                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16216                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16217                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16218                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16219                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16220                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16221                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16222                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16223
16224                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16225                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16226                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16227                 "${arg_vars}"
16228         );
16229
16230         const StringTemplate decoration
16231         (
16232                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16233                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16234                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16235                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16236                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16237                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16238                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16239                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16240                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16241                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16242                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16243                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16244                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16245
16246                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16247                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16248                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16249                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16250                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16251                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16252                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16253                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16254                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16255                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16256                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16257                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16258                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16259
16260                 "OpDecorate %SSBO_f16     BufferBlock\n"
16261                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16262                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16263                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16264                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16265                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16266                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16267                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16268                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16269                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16270                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16271                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16272                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16273
16274                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16275                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16276                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16277                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16278                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16279                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16280                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16281                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16282                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16283
16284                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16285                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16286                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16287                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16288                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16289                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16290                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16291                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16292                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16293
16294                 "${arg_decorations}"
16295         );
16296
16297         const StringTemplate testFun
16298         (
16299                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16300                 "    %param = OpFunctionParameter %v4f32\n"
16301                 "    %entry = OpLabel\n"
16302
16303                 "        %i = OpVariable %fp_i32 Function\n"
16304                 "${arg_infunc_vars}"
16305                 "             OpStore %i %c_i32_0\n"
16306                 "             OpBranch %loop\n"
16307
16308                 "     %loop = OpLabel\n"
16309                 "    %i_cmp = OpLoad %i32 %i\n"
16310                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16311                 "             OpLoopMerge %merge %next None\n"
16312                 "             OpBranchConditional %lt %write %merge\n"
16313
16314                 "    %write = OpLabel\n"
16315                 "      %ndx = OpLoad %i32 %i\n"
16316
16317                 "${arg_func_call}"
16318
16319                 "             OpBranch %next\n"
16320
16321                 "     %next = OpLabel\n"
16322                 "    %i_cur = OpLoad %i32 %i\n"
16323                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16324                 "             OpStore %i %i_new\n"
16325                 "             OpBranch %loop\n"
16326
16327                 "    %merge = OpLabel\n"
16328                 "             OpReturnValue %param\n"
16329                 "             OpFunctionEnd\n"
16330         );
16331
16332         const Math16ArgFragments        argFragment1    =
16333         {
16334                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16335                 " %val_src0 = OpLoad %${t0} %src0\n"
16336                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16337                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16338                 "             OpStore %dst %val_dst\n",
16339                 "",
16340                 "",
16341                 "",
16342         };
16343
16344         const Math16ArgFragments        argFragment2    =
16345         {
16346                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16347                 " %val_src0 = OpLoad %${t0} %src0\n"
16348                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16349                 " %val_src1 = OpLoad %${t1} %src1\n"
16350                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16351                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16352                 "             OpStore %dst %val_dst\n",
16353                 "",
16354                 "",
16355                 "",
16356         };
16357
16358         const Math16ArgFragments        argFragment3    =
16359         {
16360                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16361                 " %val_src0 = OpLoad %${t0} %src0\n"
16362                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16363                 " %val_src1 = OpLoad %${t1} %src1\n"
16364                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16365                 " %val_src2 = OpLoad %${t2} %src2\n"
16366                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16367                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16368                 "             OpStore %dst %val_dst\n",
16369                 "",
16370                 "",
16371                 "",
16372         };
16373
16374         const Math16ArgFragments        argFragmentLdExp        =
16375         {
16376                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16377                 " %val_src0 = OpLoad %${t0} %src0\n"
16378                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16379                 " %val_src1 = OpLoad %${t1} %src1\n"
16380                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16381                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16382                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16383                 "             OpStore %dst %val_dst\n",
16384
16385                 "",
16386
16387                 "",
16388
16389                 "",
16390         };
16391
16392         const Math16ArgFragments        argFragmentModfFrac     =
16393         {
16394                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16395                 " %val_src0 = OpLoad %${t0} %src0\n"
16396                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16397                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16398                 "             OpStore %dst %val_dst\n",
16399
16400                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16401
16402                 "",
16403
16404                 "      %tmp = OpVariable %fp_tmp Function\n",
16405         };
16406
16407         const Math16ArgFragments        argFragmentModfInt      =
16408         {
16409                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16410                 " %val_src0 = OpLoad %${t0} %src0\n"
16411                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16412                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16413                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16414                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16415                 "             OpStore %dst %val_dst\n",
16416
16417                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16418
16419                 "",
16420
16421                 "      %tmp = OpVariable %fp_tmp Function\n",
16422         };
16423
16424         const Math16ArgFragments        argFragmentModfStruct   =
16425         {
16426                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16427                 " %val_src0 = OpLoad %${t0} %src0\n"
16428                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16429                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16430                 "             OpStore %tmp_ptr_s %val_tmp\n"
16431                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16432                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16433                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16434                 "             OpStore %dst %val_dst\n",
16435
16436                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16437                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16438                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16439                 "   %c_frac = OpConstant %i32 0\n"
16440                 "    %c_int = OpConstant %i32 1\n",
16441
16442                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16443                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16444
16445                 "      %tmp = OpVariable %fp_tmp Function\n",
16446         };
16447
16448         const Math16ArgFragments        argFragmentFrexpStructS =
16449         {
16450                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16451                 " %val_src0 = OpLoad %${t0} %src0\n"
16452                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16453                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16454                 "             OpStore %tmp_ptr_s %val_tmp\n"
16455                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16456                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16457                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16458                 "             OpStore %dst %val_dst\n",
16459
16460                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16461                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16462                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16463
16464                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16465                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16466
16467                 "      %tmp = OpVariable %fp_tmp Function\n",
16468         };
16469
16470         const Math16ArgFragments        argFragmentFrexpStructE =
16471         {
16472                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16473                 " %val_src0 = OpLoad %${t0} %src0\n"
16474                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16475                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16476                 "             OpStore %tmp_ptr_s %val_tmp\n"
16477                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16478                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16479                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16480                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16481                 "             OpStore %dst %val_dst\n",
16482
16483                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16484                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16485
16486                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16487                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16488
16489                 "      %tmp = OpVariable %fp_tmp Function\n",
16490         };
16491
16492         const Math16ArgFragments        argFragmentFrexpS               =
16493         {
16494                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16495                 " %val_src0 = OpLoad %${t0} %src0\n"
16496                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16497                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16498                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16499                 "             OpStore %dst %val_dst\n",
16500
16501                 "",
16502
16503                 "",
16504
16505                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16506         };
16507
16508         const Math16ArgFragments        argFragmentFrexpE               =
16509         {
16510                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16511                 " %val_src0 = OpLoad %${t0} %src0\n"
16512                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16513                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16514                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16515                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16516                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16517                 "             OpStore %dst %val_dst\n",
16518
16519                 "",
16520
16521                 "",
16522
16523                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16524         };
16525
16526         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16527         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16528         const string                            testName                                = de::toLower(funcNameString);
16529         const Math16ArgFragments*       argFragments                    = DE_NULL;
16530         const size_t                            typeStructStride                = testType.typeStructStride;
16531         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16532         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16533         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16534         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16535         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16536         VulkanFeatures                          features;
16537         SpecResource                            specResource;
16538         map<string, string>                     specs;
16539         map<string, string>                     fragments;
16540         vector<string>                          extensions;
16541         string                                          funcCall;
16542         string                                          funcVariables;
16543         string                                          variables;
16544         string                                          declarations;
16545         string                                          decorations;
16546
16547         switch (testFunc.funcArgsCount)
16548         {
16549                 case 1:
16550                 {
16551                         argFragments = &argFragment1;
16552
16553                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16554                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16555                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16556                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16557                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16558                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16559                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16560                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16561
16562                         break;
16563                 }
16564                 case 2:
16565                 {
16566                         argFragments = &argFragment2;
16567
16568                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16569
16570                         break;
16571                 }
16572                 case 3:
16573                 {
16574                         argFragments = &argFragment3;
16575
16576                         break;
16577                 }
16578                 default:
16579                 {
16580                         TCU_THROW(InternalError, "Invalid number of arguments");
16581                 }
16582         }
16583
16584         if (testFunc.funcArgsCount == 1)
16585         {
16586                 variables +=
16587                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16588                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16589
16590                 decorations +=
16591                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16592                         "OpDecorate %ssbo_src0 Binding 0\n"
16593                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16594                         "OpDecorate %ssbo_dst Binding 1\n";
16595         }
16596         else if (testFunc.funcArgsCount == 2)
16597         {
16598                 variables +=
16599                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16600                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16601                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16602
16603                 decorations +=
16604                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16605                         "OpDecorate %ssbo_src0 Binding 0\n"
16606                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16607                         "OpDecorate %ssbo_src1 Binding 1\n"
16608                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16609                         "OpDecorate %ssbo_dst Binding 2\n";
16610         }
16611         else if (testFunc.funcArgsCount == 3)
16612         {
16613                 variables +=
16614                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16615                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16616                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16617                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16618
16619                 decorations +=
16620                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16621                         "OpDecorate %ssbo_src0 Binding 0\n"
16622                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16623                         "OpDecorate %ssbo_src1 Binding 1\n"
16624                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16625                         "OpDecorate %ssbo_src2 Binding 2\n"
16626                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16627                         "OpDecorate %ssbo_dst Binding 3\n";
16628         }
16629         else
16630         {
16631                 TCU_THROW(InternalError, "Invalid number of function arguments");
16632         }
16633
16634         variables       += argFragments->variables;
16635         decorations     += argFragments->decorations;
16636
16637         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16638         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16639         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16640         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16641         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16642         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16643         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16644         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16645         specs["struct_stride"]          = de::toString(typeStructStride);
16646         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16647         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16648         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16649
16650         variables                                       = StringTemplate(variables).specialize(specs);
16651         decorations                                     = StringTemplate(decorations).specialize(specs);
16652         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16653         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16654
16655         specs["num_data_points"]        = de::toString(iterations);
16656         specs["arg_vars"]                       = variables;
16657         specs["arg_decorations"]        = decorations;
16658         specs["arg_infunc_vars"]        = funcVariables;
16659         specs["arg_func_call"]          = funcCall;
16660
16661         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16662         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16663         fragments["decoration"]         = decoration.specialize(specs);
16664         fragments["pre_main"]           = preMain.specialize(specs);
16665         fragments["testfun"]            = testFun.specialize(specs);
16666
16667         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16668         {
16669                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16670                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16671                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16672                                                                                                         : -1;
16673                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16674
16675                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16676         }
16677
16678         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16679         specResource.verifyIO = testFunc.verifyFunc;
16680
16681         extensions.push_back("VK_KHR_16bit_storage");
16682         extensions.push_back("VK_KHR_shader_float16_int8");
16683
16684         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16685         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16686
16687         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16688 }
16689
16690 template<size_t C, class SpecResource>
16691 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16692 {
16693         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16694
16695         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16696         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16697         const Math16TestFunc                    testFuncs[]             =
16698         {
16699                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16700                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16701                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16702                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16703                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16704                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16705                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16706                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16707                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16708                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16709                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16710                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16711                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16712                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16713                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16714                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16715                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16716                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16717                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16718                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16719                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16720                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16721                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16722                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16723                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16724                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16725                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16726                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16727                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16728                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16729                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16730                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16731                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16732                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16733                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16734                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16735                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16736                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16737                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16738                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16739                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16740                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16741                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16742                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16743                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16744                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16745                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16746                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16747                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16748                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16749                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16750                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16751                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16752                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16753                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16754                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16755                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16756                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16757                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16758                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16759         };
16760
16761         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16762         {
16763                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16764                 const string                    funcNameString  = testFunc.funcName;
16765
16766                 if ((C != 3) && funcNameString == "Cross")
16767                         continue;
16768
16769                 if ((C < 2) && funcNameString == "OpDot")
16770                         continue;
16771
16772                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16773                         continue;
16774
16775                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16776         }
16777
16778         return testGroup.release();
16779 }
16780
16781 template<class SpecResource>
16782 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16783 {
16784         const std::string                               testGroupName   ("arithmetic");
16785         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16786         const Math16TestFunc                    testFuncs[]             =
16787         {
16788                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16789                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16790                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16791                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16792                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16793                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16794                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16795                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16796                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16797                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16798                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16799                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16800                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16801                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16802                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16803                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16804                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16805                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16806                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16807                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16808                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16809                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16810                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16811                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16812                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16813                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16814                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16815                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16816                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16817                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16818                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16819                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16820                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16821                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16822                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16823                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16824                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16825                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16826                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16827                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16828                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16829                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16830                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16831                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16832                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16833                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16834                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16835                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16836                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16837                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16838                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16839                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16840                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16841                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16842                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16843                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16844                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16845                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16846                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16847                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16848                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16849                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16850                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16851                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16852                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16853                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16854                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16855                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16856                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16857                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16858                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16859                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16860                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16861                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16862                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16863                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16864         };
16865
16866         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16867         {
16868                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16869
16870                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16871         }
16872
16873         return testGroup.release();
16874 }
16875
16876 const string getNumberTypeName (const NumberType type)
16877 {
16878         if (type == NUMBERTYPE_INT32)
16879         {
16880                 return "int";
16881         }
16882         else if (type == NUMBERTYPE_UINT32)
16883         {
16884                 return "uint";
16885         }
16886         else if (type == NUMBERTYPE_FLOAT32)
16887         {
16888                 return "float";
16889         }
16890         else
16891         {
16892                 DE_ASSERT(false);
16893                 return "";
16894         }
16895 }
16896
16897 deInt32 getInt(de::Random& rnd)
16898 {
16899         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16900 }
16901
16902 const string repeatString (const string& str, int times)
16903 {
16904         string filler;
16905         for (int i = 0; i < times; ++i)
16906         {
16907                 filler += str;
16908         }
16909         return filler;
16910 }
16911
16912 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16913 {
16914         if (type == NUMBERTYPE_INT32)
16915         {
16916                 return numberToString<deInt32>(getInt(rnd));
16917         }
16918         else if (type == NUMBERTYPE_UINT32)
16919         {
16920                 return numberToString<deUint32>(rnd.getUint32());
16921         }
16922         else if (type == NUMBERTYPE_FLOAT32)
16923         {
16924                 return numberToString<float>(rnd.getFloat());
16925         }
16926         else
16927         {
16928                 DE_ASSERT(false);
16929                 return "";
16930         }
16931 }
16932
16933 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16934 {
16935         map<string, string> params;
16936
16937         // Vec2 to Vec4
16938         for (int width = 2; width <= 4; ++width)
16939         {
16940                 const string randomConst = numberToString(getInt(rnd));
16941                 const string widthStr = numberToString(width);
16942                 const string composite_type = "${customType}vec" + widthStr;
16943                 const int index = rnd.getInt(0, width-1);
16944
16945                 params["type"]                  = "vec";
16946                 params["name"]                  = params["type"] + "_" + widthStr;
16947                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16948                 params["compositeType"]         = composite_type;
16949                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16950                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16951                 params["indexes"]               = numberToString(index);
16952                 testCases.push_back(params);
16953         }
16954 }
16955
16956 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16957 {
16958         const int limit = 10;
16959         map<string, string> params;
16960
16961         for (int width = 2; width <= limit; ++width)
16962         {
16963                 string randomConst = numberToString(getInt(rnd));
16964                 string widthStr = numberToString(width);
16965                 int index = rnd.getInt(0, width-1);
16966
16967                 params["type"]                  = "array";
16968                 params["name"]                  = params["type"] + "_" + widthStr;
16969                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16970                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16971                 params["compositeType"]         = "%composite";
16972                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16973                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16974                 params["indexes"]               = numberToString(index);
16975                 testCases.push_back(params);
16976         }
16977 }
16978
16979 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16980 {
16981         const int limit = 10;
16982         map<string, string> params;
16983
16984         for (int width = 2; width <= limit; ++width)
16985         {
16986                 string randomConst = numberToString(getInt(rnd));
16987                 int index = rnd.getInt(0, width-1);
16988
16989                 params["type"]                  = "struct";
16990                 params["name"]                  = params["type"] + "_" + numberToString(width);
16991                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16992                 params["compositeType"]         = "%composite";
16993                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16994                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16995                 params["indexes"]               = numberToString(index);
16996                 testCases.push_back(params);
16997         }
16998 }
16999
17000 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17001 {
17002         map<string, string> params;
17003
17004         // Vec2 to Vec4
17005         for (int width = 2; width <= 4; ++width)
17006         {
17007                 string widthStr = numberToString(width);
17008
17009                 for (int column = 2 ; column <= 4; ++column)
17010                 {
17011                         int index_0 = rnd.getInt(0, column-1);
17012                         int index_1 = rnd.getInt(0, width-1);
17013                         string columnStr = numberToString(column);
17014
17015                         params["type"]          = "matrix";
17016                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
17017                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
17018                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
17019                         params["compositeType"] = "%composite";
17020
17021                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
17022                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
17023
17024                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17025                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17026                         testCases.push_back(params);
17027                 }
17028         }
17029 }
17030
17031 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17032 {
17033         createVectorCompositeCases(testCases, rnd, type);
17034         createArrayCompositeCases(testCases, rnd, type);
17035         createStructCompositeCases(testCases, rnd, type);
17036         // Matrix only supports float types
17037         if (type == NUMBERTYPE_FLOAT32)
17038         {
17039                 createMatrixCompositeCases(testCases, rnd, type);
17040         }
17041 }
17042
17043 const string getAssemblyTypeDeclaration (const NumberType type)
17044 {
17045         switch (type)
17046         {
17047                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17048                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17049                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17050                 default:                        DE_ASSERT(false); return "";
17051         }
17052 }
17053
17054 const string getAssemblyTypeName (const NumberType type)
17055 {
17056         switch (type)
17057         {
17058                 case NUMBERTYPE_INT32:          return "%i32";
17059                 case NUMBERTYPE_UINT32:         return "%u32";
17060                 case NUMBERTYPE_FLOAT32:        return "%f32";
17061                 default:                        DE_ASSERT(false); return "";
17062         }
17063 }
17064
17065 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17066 {
17067         map<string, string>     parameters(params);
17068
17069         const string customType = getAssemblyTypeName(type);
17070         map<string, string> substCustomType;
17071         substCustomType["customType"] = customType;
17072         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17073         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17074         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17075         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17076         parameters["customType"] = customType;
17077         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17078
17079         if (parameters.at("compositeType") != "%u32vec3")
17080         {
17081                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17082         }
17083
17084         return StringTemplate(
17085                 "OpCapability Shader\n"
17086                 "OpCapability Matrix\n"
17087                 "OpMemoryModel Logical GLSL450\n"
17088                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17089                 "OpExecutionMode %main LocalSize 1 1 1\n"
17090
17091                 "OpSource GLSL 430\n"
17092                 "OpName %main           \"main\"\n"
17093                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17094
17095                 // Decorators
17096                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17097                 "OpDecorate %buf BufferBlock\n"
17098                 "OpDecorate %indata DescriptorSet 0\n"
17099                 "OpDecorate %indata Binding 0\n"
17100                 "OpDecorate %outdata DescriptorSet 0\n"
17101                 "OpDecorate %outdata Binding 1\n"
17102                 "OpDecorate %customarr ArrayStride 4\n"
17103                 "${compositeDecorator}"
17104                 "OpMemberDecorate %buf 0 Offset 0\n"
17105
17106                 // General types
17107                 "%void      = OpTypeVoid\n"
17108                 "%voidf     = OpTypeFunction %void\n"
17109                 "%u32       = OpTypeInt 32 0\n"
17110                 "%i32       = OpTypeInt 32 1\n"
17111                 "%f32       = OpTypeFloat 32\n"
17112
17113                 // Composite declaration
17114                 "${compositeDecl}"
17115
17116                 // Constants
17117                 "${filler}"
17118
17119                 "${u32vec3Decl:opt}"
17120                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17121
17122                 // Inherited from custom
17123                 "%customptr = OpTypePointer Uniform ${customType}\n"
17124                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17125                 "%buf       = OpTypeStruct %customarr\n"
17126                 "%bufptr    = OpTypePointer Uniform %buf\n"
17127
17128                 "%indata    = OpVariable %bufptr Uniform\n"
17129                 "%outdata   = OpVariable %bufptr Uniform\n"
17130
17131                 "%id        = OpVariable %uvec3ptr Input\n"
17132                 "%zero      = OpConstant %i32 0\n"
17133
17134                 "%main      = OpFunction %void None %voidf\n"
17135                 "%label     = OpLabel\n"
17136                 "%idval     = OpLoad %u32vec3 %id\n"
17137                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17138
17139                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17140                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17141                 // Read the input value
17142                 "%inval     = OpLoad ${customType} %inloc\n"
17143                 // Create the composite and fill it
17144                 "${compositeConstruct}"
17145                 // Insert the input value to a place
17146                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17147                 // Read back the value from the position
17148                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17149                 // Store it in the output position
17150                 "             OpStore %outloc %out_val\n"
17151                 "             OpReturn\n"
17152                 "             OpFunctionEnd\n"
17153         ).specialize(parameters);
17154 }
17155
17156 template<typename T>
17157 BufferSp createCompositeBuffer(T number)
17158 {
17159         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17160 }
17161
17162 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17163 {
17164         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17165         de::Random                                              rnd             (deStringHash(group->getName()));
17166
17167         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17168         {
17169                 NumberType                                              numberType              = NumberType(type);
17170                 const string                                    typeName                = getNumberTypeName(numberType);
17171                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17172                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17173                 vector<map<string, string> >    testCases;
17174
17175                 createCompositeCases(testCases, rnd, numberType);
17176
17177                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17178                 {
17179                         ComputeShaderSpec       spec;
17180
17181                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17182
17183                         switch (numberType)
17184                         {
17185                                 case NUMBERTYPE_INT32:
17186                                 {
17187                                         deInt32 number = getInt(rnd);
17188                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17189                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17190                                         break;
17191                                 }
17192                                 case NUMBERTYPE_UINT32:
17193                                 {
17194                                         deUint32 number = rnd.getUint32();
17195                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17196                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17197                                         break;
17198                                 }
17199                                 case NUMBERTYPE_FLOAT32:
17200                                 {
17201                                         float number = rnd.getFloat();
17202                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17203                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17204                                         break;
17205                                 }
17206                                 default:
17207                                         DE_ASSERT(false);
17208                         }
17209
17210                         spec.numWorkGroups = IVec3(1, 1, 1);
17211                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17212                 }
17213                 group->addChild(subGroup.release());
17214         }
17215         return group.release();
17216 }
17217
17218 struct AssemblyStructInfo
17219 {
17220         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17221         : components    (comp)
17222         , index                 (idx)
17223         {}
17224
17225         deUint32 components;
17226         deUint32 index;
17227 };
17228
17229 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17230 {
17231         // Create the full index string
17232         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17233         // Convert it to list of indexes
17234         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17235
17236         map<string, string>     parameters      (params);
17237         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17238         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17239         parameters["insertIndexes"]     = fullIndex;
17240
17241         // In matrix cases the last two index is the CompositeExtract indexes
17242         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17243
17244         // Construct the extractIndex
17245         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17246         {
17247                 parameters["extractIndexes"] += " " + *index;
17248         }
17249
17250         // Remove the last 1 or 2 element depends on matrix case or not
17251         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17252
17253         deUint32 id = 0;
17254         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17255         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17256         {
17257                 string indexId = "%index_" + numberToString(id++);
17258                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17259                 parameters["accessChainIndexes"] += " " + indexId;
17260         }
17261
17262         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17263
17264         const string customType = getAssemblyTypeName(type);
17265         map<string, string> substCustomType;
17266         substCustomType["customType"] = customType;
17267         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17268         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17269         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17270         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17271         parameters["customType"] = customType;
17272
17273         const string compositeType = parameters.at("compositeType");
17274         map<string, string> substCompositeType;
17275         substCompositeType["compositeType"] = compositeType;
17276         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17277         if (compositeType != "%u32vec3")
17278         {
17279                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17280         }
17281
17282         return StringTemplate(
17283                 "OpCapability Shader\n"
17284                 "OpCapability Matrix\n"
17285                 "OpMemoryModel Logical GLSL450\n"
17286                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17287                 "OpExecutionMode %main LocalSize 1 1 1\n"
17288
17289                 "OpSource GLSL 430\n"
17290                 "OpName %main           \"main\"\n"
17291                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17292                 // Decorators
17293                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17294                 "OpDecorate %buf BufferBlock\n"
17295                 "OpDecorate %indata DescriptorSet 0\n"
17296                 "OpDecorate %indata Binding 0\n"
17297                 "OpDecorate %outdata DescriptorSet 0\n"
17298                 "OpDecorate %outdata Binding 1\n"
17299                 "OpDecorate %customarr ArrayStride 4\n"
17300                 "${compositeDecorator}"
17301                 "OpMemberDecorate %buf 0 Offset 0\n"
17302                 // General types
17303                 "%void      = OpTypeVoid\n"
17304                 "%voidf     = OpTypeFunction %void\n"
17305                 "%i32       = OpTypeInt 32 1\n"
17306                 "%u32       = OpTypeInt 32 0\n"
17307                 "%f32       = OpTypeFloat 32\n"
17308                 // Custom types
17309                 "${compositeDecl}"
17310                 // %u32vec3 if not already declared in ${compositeDecl}
17311                 "${u32vec3Decl:opt}"
17312                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17313                 // Inherited from composite
17314                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17315                 "%struct_t  = OpTypeStruct${structType}\n"
17316                 "%struct_p  = OpTypePointer Function %struct_t\n"
17317                 // Constants
17318                 "${filler}"
17319                 "${accessChainConstDeclaration}"
17320                 // Inherited from custom
17321                 "%customptr = OpTypePointer Uniform ${customType}\n"
17322                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17323                 "%buf       = OpTypeStruct %customarr\n"
17324                 "%bufptr    = OpTypePointer Uniform %buf\n"
17325                 "%indata    = OpVariable %bufptr Uniform\n"
17326                 "%outdata   = OpVariable %bufptr Uniform\n"
17327
17328                 "%id        = OpVariable %uvec3ptr Input\n"
17329                 "%zero      = OpConstant %u32 0\n"
17330                 "%main      = OpFunction %void None %voidf\n"
17331                 "%label     = OpLabel\n"
17332                 "%struct_v  = OpVariable %struct_p Function\n"
17333                 "%idval     = OpLoad %u32vec3 %id\n"
17334                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17335                 // Create the input/output type
17336                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17337                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17338                 // Read the input value
17339                 "%inval     = OpLoad ${customType} %inloc\n"
17340                 // Create the composite and fill it
17341                 "${compositeConstruct}"
17342                 // Create the struct and fill it with the composite
17343                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17344                 // Insert the value
17345                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17346                 // Store the object
17347                 "             OpStore %struct_v %comp_obj\n"
17348                 // Get deepest possible composite pointer
17349                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17350                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17351                 // Read back the stored value
17352                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17353                 "             OpStore %outloc %read_val\n"
17354                 "             OpReturn\n"
17355                 "             OpFunctionEnd\n"
17356         ).specialize(parameters);
17357 }
17358
17359 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17360 {
17361         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17362         de::Random                                              rnd                             (deStringHash(group->getName()));
17363
17364         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17365         {
17366                 NumberType                                              numberType      = NumberType(type);
17367                 const string                                    typeName        = getNumberTypeName(numberType);
17368                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17369                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17370
17371                 vector<map<string, string> >    testCases;
17372                 createCompositeCases(testCases, rnd, numberType);
17373
17374                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17375                 {
17376                         ComputeShaderSpec       spec;
17377
17378                         // Number of components inside of a struct
17379                         deUint32 structComponents = rnd.getInt(2, 8);
17380                         // Component index value
17381                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17382                         AssemblyStructInfo structInfo(structComponents, structIndex);
17383
17384                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17385
17386                         switch (numberType)
17387                         {
17388                                 case NUMBERTYPE_INT32:
17389                                 {
17390                                         deInt32 number = getInt(rnd);
17391                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17392                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17393                                         break;
17394                                 }
17395                                 case NUMBERTYPE_UINT32:
17396                                 {
17397                                         deUint32 number = rnd.getUint32();
17398                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17399                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17400                                         break;
17401                                 }
17402                                 case NUMBERTYPE_FLOAT32:
17403                                 {
17404                                         float number = rnd.getFloat();
17405                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17406                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17407                                         break;
17408                                 }
17409                                 default:
17410                                         DE_ASSERT(false);
17411                         }
17412                         spec.numWorkGroups = IVec3(1, 1, 1);
17413                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17414                 }
17415                 group->addChild(subGroup.release());
17416         }
17417         return group.release();
17418 }
17419
17420 // If the params missing, uninitialized case
17421 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17422 {
17423         map<string, string> parameters(params);
17424
17425         parameters["customType"]        = getAssemblyTypeName(type);
17426
17427         // Declare the const value, and use it in the initializer
17428         if (params.find("constValue") != params.end())
17429         {
17430                 parameters["variableInitializer"]       = " %const";
17431         }
17432         // Uninitialized case
17433         else
17434         {
17435                 parameters["commentDecl"]       = ";";
17436         }
17437
17438         return StringTemplate(
17439                 "OpCapability Shader\n"
17440                 "OpMemoryModel Logical GLSL450\n"
17441                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17442                 "OpExecutionMode %main LocalSize 1 1 1\n"
17443                 "OpSource GLSL 430\n"
17444                 "OpName %main           \"main\"\n"
17445                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17446                 // Decorators
17447                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17448                 "OpDecorate %indata DescriptorSet 0\n"
17449                 "OpDecorate %indata Binding 0\n"
17450                 "OpDecorate %outdata DescriptorSet 0\n"
17451                 "OpDecorate %outdata Binding 1\n"
17452                 "OpDecorate %in_arr ArrayStride 4\n"
17453                 "OpDecorate %in_buf BufferBlock\n"
17454                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17455                 // Base types
17456                 "%void       = OpTypeVoid\n"
17457                 "%voidf      = OpTypeFunction %void\n"
17458                 "%u32        = OpTypeInt 32 0\n"
17459                 "%i32        = OpTypeInt 32 1\n"
17460                 "%f32        = OpTypeFloat 32\n"
17461                 "%uvec3      = OpTypeVector %u32 3\n"
17462                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17463                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17464                 // Derived types
17465                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17466                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17467                 "%in_buf     = OpTypeStruct %in_arr\n"
17468                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17469                 "%indata     = OpVariable %in_bufptr Uniform\n"
17470                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17471                 "%id         = OpVariable %uvec3ptr Input\n"
17472                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17473                 // Constants
17474                 "%zero       = OpConstant %i32 0\n"
17475                 // Main function
17476                 "%main       = OpFunction %void None %voidf\n"
17477                 "%label      = OpLabel\n"
17478                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17479                 "%idval      = OpLoad %uvec3 %id\n"
17480                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17481                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17482                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17483
17484                 "%outval     = OpLoad ${customType} %out_var\n"
17485                 "              OpStore %outloc %outval\n"
17486                 "              OpReturn\n"
17487                 "              OpFunctionEnd\n"
17488         ).specialize(parameters);
17489 }
17490
17491 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17492 {
17493         DE_ASSERT(outputAllocs.size() != 0);
17494         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17495
17496         // Use custom epsilon because of the float->string conversion
17497         const float     epsilon = 0.00001f;
17498
17499         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17500         {
17501                 vector<deUint8> expectedBytes;
17502                 float                   expected;
17503                 float                   actual;
17504
17505                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17506                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17507                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17508
17509                 // Test with epsilon
17510                 if (fabs(expected - actual) > epsilon)
17511                 {
17512                         log << TestLog::Message << "Error: The actual and expected values not matching."
17513                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17514                         return false;
17515                 }
17516         }
17517         return true;
17518 }
17519
17520 // Checks if the driver crash with uninitialized cases
17521 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17522 {
17523         DE_ASSERT(outputAllocs.size() != 0);
17524         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17525
17526         // Copy and discard the result.
17527         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17528         {
17529                 vector<deUint8> expectedBytes;
17530                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17531
17532                 const size_t    width                   = expectedBytes.size();
17533                 vector<char>    data                    (width);
17534
17535                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17536         }
17537         return true;
17538 }
17539
17540 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17541 {
17542         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17543         de::Random                                              rnd             (deStringHash(group->getName()));
17544
17545         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17546         {
17547                 NumberType                                              numberType      = NumberType(type);
17548                 const string                                    typeName        = getNumberTypeName(numberType);
17549                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17550                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17551
17552                 // 2 similar subcases (initialized and uninitialized)
17553                 for (int subCase = 0; subCase < 2; ++subCase)
17554                 {
17555                         ComputeShaderSpec spec;
17556                         spec.numWorkGroups = IVec3(1, 1, 1);
17557
17558                         map<string, string>                             params;
17559
17560                         switch (numberType)
17561                         {
17562                                 case NUMBERTYPE_INT32:
17563                                 {
17564                                         deInt32 number = getInt(rnd);
17565                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17566                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17567                                         params["constValue"] = numberToString(number);
17568                                         break;
17569                                 }
17570                                 case NUMBERTYPE_UINT32:
17571                                 {
17572                                         deUint32 number = rnd.getUint32();
17573                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17574                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17575                                         params["constValue"] = numberToString(number);
17576                                         break;
17577                                 }
17578                                 case NUMBERTYPE_FLOAT32:
17579                                 {
17580                                         float number = rnd.getFloat();
17581                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17582                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17583                                         spec.verifyIO = &compareFloats;
17584                                         params["constValue"] = numberToString(number);
17585                                         break;
17586                                 }
17587                                 default:
17588                                         DE_ASSERT(false);
17589                         }
17590
17591                         // Initialized subcase
17592                         if (!subCase)
17593                         {
17594                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17595                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17596                         }
17597                         // Uninitialized subcase
17598                         else
17599                         {
17600                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17601                                 spec.verifyIO = &passthruVerify;
17602                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17603                         }
17604                 }
17605                 group->addChild(subGroup.release());
17606         }
17607         return group.release();
17608 }
17609
17610 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17611 {
17612         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17613         RGBA                                                    defaultColors[4];
17614         map<string, string>                             opNopFragments;
17615
17616         getDefaultColors(defaultColors);
17617
17618         opNopFragments["testfun"]               =
17619                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17620                 "%param1 = OpFunctionParameter %v4f32\n"
17621                 "%label_testfun = OpLabel\n"
17622                 "OpNop\n"
17623                 "OpNop\n"
17624                 "OpNop\n"
17625                 "OpNop\n"
17626                 "OpNop\n"
17627                 "OpNop\n"
17628                 "OpNop\n"
17629                 "OpNop\n"
17630                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17631                 "%b = OpFAdd %f32 %a %a\n"
17632                 "OpNop\n"
17633                 "%c = OpFSub %f32 %b %a\n"
17634                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17635                 "OpNop\n"
17636                 "OpNop\n"
17637                 "OpReturnValue %ret\n"
17638                 "OpFunctionEnd\n";
17639
17640         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17641
17642         return testGroup.release();
17643 }
17644
17645 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17646 {
17647         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17648         RGBA                                                    defaultColors[4];
17649         map<string, string>                             opNameFragments;
17650
17651         getDefaultColors(defaultColors);
17652
17653         opNameFragments["testfun"] =
17654                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17655                 "%param1     = OpFunctionParameter %v4f32\n"
17656                 "%label_func = OpLabel\n"
17657                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17658                 "%b          = OpFAdd %f32 %a %a\n"
17659                 "%c          = OpFSub %f32 %b %a\n"
17660                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17661                 "OpReturnValue %ret\n"
17662                 "OpFunctionEnd\n";
17663
17664         opNameFragments["debug"] =
17665                 "OpName %BP_main \"not_main\"";
17666
17667         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17668
17669         return testGroup.release();
17670 }
17671
17672 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17673 {
17674         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17675
17676         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17677         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17678         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17679         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17680         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17681         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17682         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17683         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17684         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17685         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17686         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17687         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17688         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17689         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17690         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17691         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17692         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17693         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17694
17695         return testGroup.release();
17696 }
17697
17698 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17699 {
17700         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17701
17702         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17703         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17704         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17705         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17706         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17707         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17708         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17709         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17710         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17711         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17712         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17713         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17714         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17715         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17716         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17717
17718         return testGroup.release();
17719 }
17720
17721 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17722 {
17723         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17724
17725         de::Random                                              rnd                             (deStringHash(group->getName()));
17726         const int               numElements             = 100;
17727         vector<float>   inputData               (numElements, 0);
17728         vector<float>   outputData              (numElements, 0);
17729         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17730
17731         const StringTemplate                    shaderTemplate  (
17732                 "${CAPS}\n"
17733                 "OpMemoryModel Logical GLSL450\n"
17734                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17735                 "OpExecutionMode %main LocalSize 1 1 1\n"
17736                 "OpSource GLSL 430\n"
17737                 "OpName %main           \"main\"\n"
17738                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17739
17740                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17741
17742                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17743
17744                 "%id        = OpVariable %uvec3ptr Input\n"
17745                 "${CONST}\n"
17746                 "%main      = OpFunction %void None %voidf\n"
17747                 "%label     = OpLabel\n"
17748                 "%idval     = OpLoad %uvec3 %id\n"
17749                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17750                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17751
17752                 "${TEST}\n"
17753
17754                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17755                 "             OpStore %outloc %res\n"
17756                 "             OpReturn\n"
17757                 "             OpFunctionEnd\n"
17758         );
17759
17760         // Each test case produces 4 boolean values, and we want each of these values
17761         // to come froma different combination of the available bit-sizes, so compute
17762         // all possible combinations here.
17763         vector<deUint32>        widths;
17764         widths.push_back(32);
17765         widths.push_back(16);
17766         widths.push_back(8);
17767
17768         vector<IVec4>   cases;
17769         for (size_t width0 = 0; width0 < widths.size(); width0++)
17770         {
17771                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17772                 {
17773                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17774                         {
17775                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17776                                 {
17777                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17778                                 }
17779                         }
17780                 }
17781         }
17782
17783         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17784         {
17785                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17786                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17787                         continue;
17788
17789                 map<string, string>     specializations;
17790                 ComputeShaderSpec       spec;
17791
17792                 // Inject appropriate capabilities and reference constants depending
17793                 // on the bit-sizes required by this test case
17794                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17795                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17796                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17797
17798                 string capsStr  = "OpCapability Shader\n";
17799                 string constStr =
17800                         "%c0i32     = OpConstant %i32 0\n"
17801                         "%c1f32     = OpConstant %f32 1.0\n"
17802                         "%c0f32     = OpConstant %f32 0.0\n";
17803
17804                 if (hasFloat32)
17805                 {
17806                         constStr        +=
17807                                 "%c10f32    = OpConstant %f32 10.0\n"
17808                                 "%c25f32    = OpConstant %f32 25.0\n"
17809                                 "%c50f32    = OpConstant %f32 50.0\n"
17810                                 "%c90f32    = OpConstant %f32 90.0\n";
17811                 }
17812
17813                 if (hasFloat16)
17814                 {
17815                         capsStr         += "OpCapability Float16\n";
17816                         constStr        +=
17817                                 "%f16       = OpTypeFloat 16\n"
17818                                 "%c10f16    = OpConstant %f16 10.0\n"
17819                                 "%c25f16    = OpConstant %f16 25.0\n"
17820                                 "%c50f16    = OpConstant %f16 50.0\n"
17821                                 "%c90f16    = OpConstant %f16 90.0\n";
17822                 }
17823
17824                 if (hasInt8)
17825                 {
17826                         capsStr         += "OpCapability Int8\n";
17827                         constStr        +=
17828                                 "%i8        = OpTypeInt 8 1\n"
17829                                 "%c10i8     = OpConstant %i8 10\n"
17830                                 "%c25i8     = OpConstant %i8 25\n"
17831                                 "%c50i8     = OpConstant %i8 50\n"
17832                                 "%c90i8     = OpConstant %i8 90\n";
17833                 }
17834
17835                 // Each invocation reads a different float32 value as input. Depending on
17836                 // the bit-sizes required by the particular test case, we also produce
17837                 // float16 and/or and int8 values by converting from the 32-bit float.
17838                 string testStr  = "";
17839                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
17840                 if (hasFloat16)
17841                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
17842                 if (hasInt8)
17843                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
17844
17845                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17846                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17847                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17848                 // other way around, so in this case we want < instead of <=.
17849                 if (cases[caseNdx][0] == 32)
17850                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17851                 else if (cases[caseNdx][0] == 16)
17852                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17853                 else
17854                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17855
17856                 if (cases[caseNdx][1] == 32)
17857                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17858                 else if (cases[caseNdx][1] == 16)
17859                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17860                 else
17861                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17862
17863                 if (cases[caseNdx][2] == 32)
17864                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17865                 else if (cases[caseNdx][2] == 16)
17866                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17867                 else
17868                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17869
17870                 if (cases[caseNdx][3] == 32)
17871                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17872                 else if (cases[caseNdx][3] == 16)
17873                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17874                 else
17875                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17876
17877                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17878                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17879                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
17880                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
17881                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17882
17883                 specializations["CAPS"]         = capsStr;
17884                 specializations["CONST"]        = constStr;
17885                 specializations["TEST"]         = testStr;
17886
17887                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
17888                 for (size_t ndx = 0; ndx < numElements; ++ndx)
17889                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17890
17891                 spec.assembly = shaderTemplate.specialize(specializations);
17892                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17893                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17894                 spec.numWorkGroups = IVec3(numElements, 1, 1);
17895                 if (hasFloat16)
17896                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17897                 if (hasInt8)
17898                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17899                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
17900
17901                 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]);
17902                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17903         }
17904
17905         return group.release();
17906 }
17907
17908 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17909 {
17910         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17911
17912         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17913
17914         return testGroup.release();
17915 }
17916
17917 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17918 {
17919         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17920         vector<CaseParameter>                   abuseCases;
17921         RGBA                                                    defaultColors[4];
17922         map<string, string>                             opNameFragments;
17923
17924         getOpNameAbuseCases(abuseCases);
17925         getDefaultColors(defaultColors);
17926
17927         opNameFragments["testfun"] =
17928                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17929                 "%param1     = OpFunctionParameter %v4f32\n"
17930                 "%label_func = OpLabel\n"
17931                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17932                 "%b          = OpFAdd %f32 %a %a\n"
17933                 "%c          = OpFSub %f32 %b %a\n"
17934                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17935                 "OpReturnValue %ret\n"
17936                 "OpFunctionEnd\n";
17937
17938         for (unsigned int i = 0; i < abuseCases.size(); i++)
17939         {
17940                 string casename;
17941                 casename = string("main") + abuseCases[i].name;
17942
17943                 opNameFragments["debug"] =
17944                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
17945
17946                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17947         }
17948
17949         for (unsigned int i = 0; i < abuseCases.size(); i++)
17950         {
17951                 string casename;
17952                 casename = string("b") + abuseCases[i].name;
17953
17954                 opNameFragments["debug"] =
17955                         "OpName %b \"" + abuseCases[i].param + "\"";
17956
17957                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17958         }
17959
17960         {
17961                 opNameFragments["debug"] =
17962                         "OpName %test_code \"name1\"\n"
17963                         "OpName %param1    \"name2\"\n"
17964                         "OpName %a         \"name3\"\n"
17965                         "OpName %b         \"name4\"\n"
17966                         "OpName %c         \"name5\"\n"
17967                         "OpName %ret       \"name6\"\n";
17968
17969                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17970         }
17971
17972         {
17973                 opNameFragments["debug"] =
17974                         "OpName %test_code \"the_same\"\n"
17975                         "OpName %param1    \"the_same\"\n"
17976                         "OpName %a         \"the_same\"\n"
17977                         "OpName %b         \"the_same\"\n"
17978                         "OpName %c         \"the_same\"\n"
17979                         "OpName %ret       \"the_same\"\n";
17980
17981                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17982         }
17983
17984         {
17985                 opNameFragments["debug"] =
17986                         "OpName %BP_main \"to_be\"\n"
17987                         "OpName %BP_main \"or_not\"\n"
17988                         "OpName %BP_main \"to_be\"\n";
17989
17990                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17991         }
17992
17993         {
17994                 opNameFragments["debug"] =
17995                         "OpName %b \"to_be\"\n"
17996                         "OpName %b \"or_not\"\n"
17997                         "OpName %b \"to_be\"\n";
17998
17999                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18000         }
18001
18002         return abuseGroup.release();
18003 }
18004
18005
18006 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
18007 {
18008         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
18009         vector<CaseParameter>                   abuseCases;
18010         RGBA                                                    defaultColors[4];
18011         map<string, string>                             opMemberNameFragments;
18012
18013         getOpNameAbuseCases(abuseCases);
18014         getDefaultColors(defaultColors);
18015
18016         opMemberNameFragments["pre_main"] =
18017                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
18018
18019         opMemberNameFragments["testfun"] =
18020                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18021                 "%param1     = OpFunctionParameter %v4f32\n"
18022                 "%label_func = OpLabel\n"
18023                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18024                 "%b          = OpFAdd %f32 %a %a\n"
18025                 "%c          = OpFSub %f32 %b %a\n"
18026                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18027                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18028                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18029                 "OpReturnValue %ret\n"
18030                 "OpFunctionEnd\n";
18031
18032         for (unsigned int i = 0; i < abuseCases.size(); i++)
18033         {
18034                 string casename;
18035                 casename = string("f3str_x") + abuseCases[i].name;
18036
18037                 opMemberNameFragments["debug"] =
18038                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18039
18040                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18041         }
18042
18043         {
18044                 opMemberNameFragments["debug"] =
18045                         "OpMemberName %f3str 0 \"name1\"\n"
18046                         "OpMemberName %f3str 1 \"name2\"\n"
18047                         "OpMemberName %f3str 2 \"name3\"\n";
18048
18049                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18050         }
18051
18052         {
18053                 opMemberNameFragments["debug"] =
18054                         "OpMemberName %f3str 0 \"the_same\"\n"
18055                         "OpMemberName %f3str 1 \"the_same\"\n"
18056                         "OpMemberName %f3str 2 \"the_same\"\n";
18057
18058                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18059         }
18060
18061         {
18062                 opMemberNameFragments["debug"] =
18063                         "OpMemberName %f3str 0 \"to_be\"\n"
18064                         "OpMemberName %f3str 1 \"or_not\"\n"
18065                         "OpMemberName %f3str 0 \"to_be\"\n"
18066                         "OpMemberName %f3str 2 \"makes_no\"\n"
18067                         "OpMemberName %f3str 0 \"difference\"\n"
18068                         "OpMemberName %f3str 0 \"to_me\"\n";
18069
18070
18071                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18072         }
18073
18074         return abuseGroup.release();
18075 }
18076
18077 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18078 {
18079         const bool testComputePipeline = true;
18080
18081         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18082         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18083         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18084
18085         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18086         computeTests->addChild(createLocalSizeGroup(testCtx));
18087         computeTests->addChild(createOpNopGroup(testCtx));
18088         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18089         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18090         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18091         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18092         computeTests->addChild(createOpLineGroup(testCtx));
18093         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18094         computeTests->addChild(createOpNoLineGroup(testCtx));
18095         computeTests->addChild(createOpConstantNullGroup(testCtx));
18096         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18097         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18098         computeTests->addChild(createSpecConstantGroup(testCtx));
18099         computeTests->addChild(createOpSourceGroup(testCtx));
18100         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18101         computeTests->addChild(createDecorationGroupGroup(testCtx));
18102         computeTests->addChild(createOpPhiGroup(testCtx));
18103         computeTests->addChild(createLoopControlGroup(testCtx));
18104         computeTests->addChild(createFunctionControlGroup(testCtx));
18105         computeTests->addChild(createSelectionControlGroup(testCtx));
18106         computeTests->addChild(createBlockOrderGroup(testCtx));
18107         computeTests->addChild(createMultipleShaderGroup(testCtx));
18108         computeTests->addChild(createMemoryAccessGroup(testCtx));
18109         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18110         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18111         computeTests->addChild(createNoContractionGroup(testCtx));
18112         computeTests->addChild(createOpUndefGroup(testCtx));
18113         computeTests->addChild(createOpUnreachableGroup(testCtx));
18114         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18115         computeTests->addChild(createOpFRemGroup(testCtx));
18116         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18117         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18118         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18119         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18120         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18121         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18122         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18123         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18124         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18125         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18126         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18127         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18128         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18129         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18130         computeTests->addChild(createOpNMinGroup(testCtx));
18131         computeTests->addChild(createOpNMaxGroup(testCtx));
18132         computeTests->addChild(createOpNClampGroup(testCtx));
18133         {
18134                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18135
18136                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18137                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18138
18139                 computeTests->addChild(computeAndroidTests.release());
18140         }
18141
18142         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18143         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18144         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18145         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18146         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18147         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18148         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18149         computeTests->addChild(createIndexingComputeGroup(testCtx));
18150         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18151         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18152         computeTests->addChild(createOpNameGroup(testCtx));
18153         computeTests->addChild(createOpMemberNameGroup(testCtx));
18154         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18155         computeTests->addChild(createFloat16Group(testCtx));
18156         computeTests->addChild(createBoolGroup(testCtx));
18157         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18158
18159         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18160         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18161         graphicsTests->addChild(createOpNopTests(testCtx));
18162         graphicsTests->addChild(createOpSourceTests(testCtx));
18163         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18164         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18165         graphicsTests->addChild(createOpLineTests(testCtx));
18166         graphicsTests->addChild(createOpNoLineTests(testCtx));
18167         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18168         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18169         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18170         graphicsTests->addChild(createOpUndefTests(testCtx));
18171         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18172         graphicsTests->addChild(createModuleTests(testCtx));
18173         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18174         graphicsTests->addChild(createOpPhiTests(testCtx));
18175         graphicsTests->addChild(createNoContractionTests(testCtx));
18176         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18177         graphicsTests->addChild(createLoopTests(testCtx));
18178         graphicsTests->addChild(createSpecConstantTests(testCtx));
18179         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18180         graphicsTests->addChild(createBarrierTests(testCtx));
18181         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18182         graphicsTests->addChild(createFRemTests(testCtx));
18183         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18184         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18185
18186         {
18187                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18188
18189                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18190                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18191
18192                 graphicsTests->addChild(graphicsAndroidTests.release());
18193         }
18194         graphicsTests->addChild(createOpNameTests(testCtx));
18195         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18196         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18197
18198         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18199         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18200         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18201         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18202         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18203         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18204         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18205         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18206         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18207         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18208         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18209         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18210         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18211         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18212         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18213         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18214         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18215         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18216         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18217
18218         graphicsTests->addChild(createFloat16Tests(testCtx));
18219
18220         instructionTests->addChild(computeTests.release());
18221         instructionTests->addChild(graphicsTests.release());
18222
18223         return instructionTests.release();
18224 }
18225
18226 } // SpirVAssembly
18227 } // vkt